]> Cypherpunks.ru repositories - nncp.git/blob - src/cmd/nncp-bundle/main.go
recfile log format
[nncp.git] / src / cmd / nncp-bundle / main.go
1 /*
2 NNCP -- Node to Node copy, utilities for store-and-forward data exchange
3 Copyright (C) 2016-2021 Sergey Matveev <stargrave@stargrave.org>
4
5 This program is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation, version 3 of the License.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 GNU General Public License for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with this program.  If not, see <http://www.gnu.org/licenses/>.
16 */
17
18 // Create/digest stream of NNCP encrypted packets.
19 package main
20
21 import (
22         "archive/tar"
23         "bufio"
24         "bytes"
25         "errors"
26         "flag"
27         "fmt"
28         "io"
29         "io/ioutil"
30         "log"
31         "os"
32         "path/filepath"
33         "strings"
34
35         xdr "github.com/davecgh/go-xdr/xdr2"
36         "go.cypherpunks.ru/nncp/v5"
37         "golang.org/x/crypto/blake2b"
38 )
39
40 const (
41         CopyBufSize = 1 << 17
42 )
43
44 func usage() {
45         fmt.Fprintf(os.Stderr, nncp.UsageHeader())
46         fmt.Fprintf(os.Stderr, "nncp-bundle -- Create/digest stream of NNCP encrypted packets\n\n")
47         fmt.Fprintf(os.Stderr, "Usage: %s [options] -tx [-delete] NODE [NODE ...] > ...\n", os.Args[0])
48         fmt.Fprintf(os.Stderr, "       %s [options] -rx -delete [-dryrun] [NODE ...] < ...\n", os.Args[0])
49         fmt.Fprintf(os.Stderr, "       %s [options] -rx [-check] [-dryrun] [NODE ...] < ...\n", os.Args[0])
50         fmt.Fprintln(os.Stderr, "Options:")
51         flag.PrintDefaults()
52 }
53
54 func main() {
55         var (
56                 cfgPath   = flag.String("cfg", nncp.DefaultCfgPath, "Path to configuration file")
57                 niceRaw   = flag.String("nice", nncp.NicenessFmt(255), "Minimal required niceness")
58                 doRx      = flag.Bool("rx", false, "Receive packets")
59                 doTx      = flag.Bool("tx", false, "Transfer packets")
60                 doDelete  = flag.Bool("delete", false, "Delete transferred packets")
61                 doCheck   = flag.Bool("check", false, "Check integrity while receiving")
62                 dryRun    = flag.Bool("dryrun", false, "Do no writes")
63                 spoolPath = flag.String("spool", "", "Override path to spool")
64                 logPath   = flag.String("log", "", "Override path to logfile")
65                 quiet     = flag.Bool("quiet", false, "Print only errors")
66                 showPrgrs = flag.Bool("progress", false, "Force progress showing")
67                 omitPrgrs = flag.Bool("noprogress", false, "Omit progress showing")
68                 debug     = flag.Bool("debug", false, "Print debug messages")
69                 version   = flag.Bool("version", false, "Print version information")
70                 warranty  = flag.Bool("warranty", false, "Print warranty information")
71         )
72         flag.Usage = usage
73         flag.Parse()
74         if *warranty {
75                 fmt.Println(nncp.Warranty)
76                 return
77         }
78         if *version {
79                 fmt.Println(nncp.VersionGet())
80                 return
81         }
82         nice, err := nncp.NicenessParse(*niceRaw)
83         if err != nil {
84                 log.Fatalln(err)
85         }
86         if *doRx && *doTx {
87                 log.Fatalln("-rx and -tx can not be set simultaneously")
88         }
89         if !*doRx && !*doTx {
90                 log.Fatalln("At least one of -rx and -tx must be specified")
91         }
92
93         ctx, err := nncp.CtxFromCmdline(
94                 *cfgPath,
95                 *spoolPath,
96                 *logPath,
97                 *quiet,
98                 *showPrgrs,
99                 *omitPrgrs,
100                 *debug,
101         )
102         if err != nil {
103                 log.Fatalln("Error during initialization:", err)
104         }
105
106         nodeIds := make(map[nncp.NodeId]struct{}, flag.NArg())
107         for i := 0; i < flag.NArg(); i++ {
108                 node, err := ctx.FindNode(flag.Arg(i))
109                 if err != nil {
110                         log.Fatalln("Invalid specified:", err)
111                 }
112                 nodeIds[*node.Id] = struct{}{}
113         }
114
115         ctx.Umask()
116
117         if *doTx {
118                 var pktName string
119                 bufStdout := bufio.NewWriter(os.Stdout)
120                 tarWr := tar.NewWriter(bufStdout)
121                 for nodeId := range nodeIds {
122                         les := nncp.LEs{
123                                 {K: "XX", V: string(nncp.TTx)},
124                                 {K: "Node", V: nodeId.String()},
125                                 {K: "Pkt", V: "dummy"},
126                         }
127                         for job := range ctx.Jobs(&nodeId, nncp.TTx) {
128                                 pktName = filepath.Base(job.Fd.Name())
129                                 les[len(les)-1].V = pktName
130                                 if job.PktEnc.Nice > nice {
131                                         ctx.LogD("nncp-bundle", les, "too nice")
132                                         job.Fd.Close() // #nosec G104
133                                         continue
134                                 }
135                                 if err = tarWr.WriteHeader(&tar.Header{
136                                         Format:   tar.FormatUSTAR,
137                                         Name:     nncp.NNCPBundlePrefix,
138                                         Mode:     0700,
139                                         Typeflag: tar.TypeDir,
140                                 }); err != nil {
141                                         log.Fatalln("Error writing tar header:", err)
142                                 }
143                                 if err = tarWr.WriteHeader(&tar.Header{
144                                         Format: tar.FormatPAX,
145                                         Name: strings.Join([]string{
146                                                 nncp.NNCPBundlePrefix,
147                                                 nodeId.String(),
148                                                 ctx.SelfId.String(),
149                                                 pktName,
150                                         }, "/"),
151                                         Mode:     0400,
152                                         Size:     job.Size,
153                                         Typeflag: tar.TypeReg,
154                                 }); err != nil {
155                                         log.Fatalln("Error writing tar header:", err)
156                                 }
157                                 if _, err = nncp.CopyProgressed(
158                                         tarWr, job.Fd, "Tx",
159                                         append(les, nncp.LEs{
160                                                 {K: "Pkt", V: nncp.Base32Codec.EncodeToString(job.HshValue[:])},
161                                                 {K: "FullSize", V: job.Size},
162                                         }...),
163                                         ctx.ShowPrgrs,
164                                 ); err != nil {
165                                         log.Fatalln("Error during copying to tar:", err)
166                                 }
167                                 job.Fd.Close() // #nosec G104
168                                 if err = tarWr.Flush(); err != nil {
169                                         log.Fatalln("Error during tar flushing:", err)
170                                 }
171                                 if err = bufStdout.Flush(); err != nil {
172                                         log.Fatalln("Error during stdout flushing:", err)
173                                 }
174                                 if *doDelete {
175                                         if err = os.Remove(job.Fd.Name()); err != nil {
176                                                 log.Fatalln("Error during deletion:", err)
177                                         }
178                                 }
179                                 ctx.LogI("nncp-bundle", append(les, nncp.LE{K: "Size", V: job.Size}), "")
180                         }
181                 }
182                 if err = tarWr.Close(); err != nil {
183                         log.Fatalln("Error during tar closing:", err)
184                 }
185         } else {
186                 bufStdin := bufio.NewReaderSize(os.Stdin, CopyBufSize*2)
187                 pktEncBuf := make([]byte, nncp.PktEncOverhead)
188                 var pktEnc *nncp.PktEnc
189                 for {
190                         peeked, err := bufStdin.Peek(CopyBufSize)
191                         if err != nil && err != io.EOF {
192                                 log.Fatalln("Error during reading:", err)
193                         }
194                         prefixIdx := bytes.Index(peeked, []byte(nncp.NNCPBundlePrefix))
195                         if prefixIdx == -1 {
196                                 if err == io.EOF {
197                                         break
198                                 }
199                                 bufStdin.Discard(bufStdin.Buffered() - (len(nncp.NNCPBundlePrefix) - 1)) // #nosec G104
200                                 continue
201                         }
202                         if _, err = bufStdin.Discard(prefixIdx); err != nil {
203                                 panic(err)
204                         }
205                         tarR := tar.NewReader(bufStdin)
206                         entry, err := tarR.Next()
207                         if err != nil {
208                                 if err != io.EOF {
209                                         ctx.LogD(
210                                                 "nncp-bundle",
211                                                 nncp.LEs{{K: "XX", V: string(nncp.TRx)}, {K: "Err", V: err}},
212                                                 "error reading tar",
213                                         )
214                                 }
215                                 continue
216                         }
217                         if entry.Typeflag != tar.TypeDir {
218                                 ctx.LogD(
219                                         "nncp-bundle",
220                                         nncp.LEs{{K: "XX", V: string(nncp.TRx)}},
221                                         "Expected NNCP/",
222                                 )
223                                 continue
224                         }
225                         entry, err = tarR.Next()
226                         if err != nil {
227                                 if err != io.EOF {
228                                         ctx.LogD(
229                                                 "nncp-bundle",
230                                                 nncp.LEs{{K: "XX", V: string(nncp.TRx)}, {K: "Err", V: err}},
231                                                 "error reading tar",
232                                         )
233                                 }
234                                 continue
235                         }
236                         les := nncp.LEs{{K: "XX", V: string(nncp.TRx)}, {K: "Pkt", V: entry.Name}}
237                         if entry.Size < nncp.PktEncOverhead {
238                                 ctx.LogD("nncp-bundle", les, "Too small packet")
239                                 continue
240                         }
241                         if !ctx.IsEnoughSpace(entry.Size) {
242                                 ctx.LogE("nncp-bundle", les, errors.New("not enough spool space"), "")
243                                 continue
244                         }
245                         pktName := filepath.Base(entry.Name)
246                         if _, err = nncp.Base32Codec.DecodeString(pktName); err != nil {
247                                 ctx.LogD("nncp-bundle", append(les, nncp.LE{K: "Err", V: "bad packet name"}), "")
248                                 continue
249                         }
250                         if _, err = io.ReadFull(tarR, pktEncBuf); err != nil {
251                                 ctx.LogD("nncp-bundle", append(les, nncp.LE{K: "Err", V: err}), "read")
252                                 continue
253                         }
254                         if _, err = xdr.Unmarshal(bytes.NewReader(pktEncBuf), &pktEnc); err != nil {
255                                 ctx.LogD("nncp-bundle", les, "Bad packet structure")
256                                 continue
257                         }
258                         if pktEnc.Magic != nncp.MagicNNCPEv4 {
259                                 ctx.LogD("nncp-bundle", les, "Bad packet magic number")
260                                 continue
261                         }
262                         if pktEnc.Nice > nice {
263                                 ctx.LogD("nncp-bundle", les, "too nice")
264                                 continue
265                         }
266                         if *pktEnc.Sender == *ctx.SelfId && *doDelete {
267                                 if len(nodeIds) > 0 {
268                                         if _, exists := nodeIds[*pktEnc.Recipient]; !exists {
269                                                 ctx.LogD("nncp-bundle", les, "Recipient is not requested")
270                                                 continue
271                                         }
272                                 }
273                                 nodeId32 := nncp.Base32Codec.EncodeToString(pktEnc.Recipient[:])
274                                 les := nncp.LEs{
275                                         {K: "XX", V: string(nncp.TTx)},
276                                         {K: "Node", V: nodeId32},
277                                         {K: "Pkt", V: pktName},
278                                 }
279                                 dstPath := filepath.Join(ctx.Spool, nodeId32, string(nncp.TTx), pktName)
280                                 if _, err = os.Stat(dstPath); err != nil {
281                                         ctx.LogD("nncp-bundle", les, "Packet is already missing")
282                                         continue
283                                 }
284                                 hsh, err := blake2b.New256(nil)
285                                 if err != nil {
286                                         log.Fatalln("Error during hasher creation:", err)
287                                 }
288                                 if _, err = hsh.Write(pktEncBuf); err != nil {
289                                         log.Fatalln("Error during writing:", err)
290                                 }
291                                 if _, err = nncp.CopyProgressed(
292                                         hsh, tarR, "Rx",
293                                         append(les, nncp.LE{K: "FullSize", V: entry.Size}),
294                                         ctx.ShowPrgrs,
295                                 ); err != nil {
296                                         log.Fatalln("Error during copying:", err)
297                                 }
298                                 if nncp.Base32Codec.EncodeToString(hsh.Sum(nil)) == pktName {
299                                         ctx.LogI("nncp-bundle", les, "removed")
300                                         if !*dryRun {
301                                                 os.Remove(dstPath) // #nosec G104
302                                         }
303                                 } else {
304                                         ctx.LogE("nncp-bundle", les, errors.New("bad checksum"), "")
305                                 }
306                                 continue
307                         }
308                         if *pktEnc.Recipient != *ctx.SelfId {
309                                 ctx.LogD("nncp-bundle", les, "Unknown recipient")
310                                 continue
311                         }
312                         if len(nodeIds) > 0 {
313                                 if _, exists := nodeIds[*pktEnc.Sender]; !exists {
314                                         ctx.LogD("nncp-bundle", les, "Sender is not requested")
315                                         continue
316                                 }
317                         }
318                         sender := nncp.Base32Codec.EncodeToString(pktEnc.Sender[:])
319                         les = nncp.LEs{
320                                 {K: "XX", V: string(nncp.TRx)},
321                                 {K: "Node", V: sender},
322                                 {K: "Pkt", V: pktName},
323                                 {K: "FullSize", V: entry.Size},
324                         }
325                         dstDirPath := filepath.Join(ctx.Spool, sender, string(nncp.TRx))
326                         dstPath := filepath.Join(dstDirPath, pktName)
327                         if _, err = os.Stat(dstPath); err == nil || !os.IsNotExist(err) {
328                                 ctx.LogD("nncp-bundle", les, "Packet already exists")
329                                 continue
330                         }
331                         if _, err = os.Stat(dstPath + nncp.SeenSuffix); err == nil || !os.IsNotExist(err) {
332                                 ctx.LogD("nncp-bundle", les, "Packet already exists")
333                                 continue
334                         }
335                         if *doCheck {
336                                 if *dryRun {
337                                         hsh, err := blake2b.New256(nil)
338                                         if err != nil {
339                                                 log.Fatalln("Error during hasher creation:", err)
340                                         }
341                                         if _, err = hsh.Write(pktEncBuf); err != nil {
342                                                 log.Fatalln("Error during writing:", err)
343                                         }
344                                         if _, err = nncp.CopyProgressed(hsh, tarR, "check", les, ctx.ShowPrgrs); err != nil {
345                                                 log.Fatalln("Error during copying:", err)
346                                         }
347                                         if nncp.Base32Codec.EncodeToString(hsh.Sum(nil)) != pktName {
348                                                 ctx.LogE("nncp-bundle", les, errors.New("bad checksum"), "")
349                                                 continue
350                                         }
351                                 } else {
352                                         tmp, err := ctx.NewTmpFileWHash()
353                                         if err != nil {
354                                                 log.Fatalln("Error during temporary file creation:", err)
355                                         }
356                                         if _, err = tmp.W.Write(pktEncBuf); err != nil {
357                                                 log.Fatalln("Error during writing:", err)
358                                         }
359                                         if _, err = nncp.CopyProgressed(tmp.W, tarR, "check", les, ctx.ShowPrgrs); err != nil {
360                                                 log.Fatalln("Error during copying:", err)
361                                         }
362                                         if err = tmp.W.Flush(); err != nil {
363                                                 log.Fatalln("Error during flusing:", err)
364                                         }
365                                         if nncp.Base32Codec.EncodeToString(tmp.Hsh.Sum(nil)) == pktName {
366                                                 if err = tmp.Commit(dstDirPath); err != nil {
367                                                         log.Fatalln("Error during commiting:", err)
368                                                 }
369                                         } else {
370                                                 ctx.LogE("nncp-bundle", les, errors.New("bad checksum"), "")
371                                                 tmp.Cancel()
372                                                 continue
373                                         }
374                                 }
375                         } else {
376                                 if *dryRun {
377                                         if _, err = nncp.CopyProgressed(ioutil.Discard, tarR, "Rx", les, ctx.ShowPrgrs); err != nil {
378                                                 log.Fatalln("Error during copying:", err)
379                                         }
380                                 } else {
381                                         tmp, err := ctx.NewTmpFile()
382                                         if err != nil {
383                                                 log.Fatalln("Error during temporary file creation:", err)
384                                         }
385                                         bufTmp := bufio.NewWriterSize(tmp, CopyBufSize)
386                                         if _, err = bufTmp.Write(pktEncBuf); err != nil {
387                                                 log.Fatalln("Error during writing:", err)
388                                         }
389                                         if _, err = nncp.CopyProgressed(bufTmp, tarR, "Rx", les, ctx.ShowPrgrs); err != nil {
390                                                 log.Fatalln("Error during copying:", err)
391                                         }
392                                         if err = bufTmp.Flush(); err != nil {
393                                                 log.Fatalln("Error during flushing:", err)
394                                         }
395                                         if err = tmp.Sync(); err != nil {
396                                                 log.Fatalln("Error during syncing:", err)
397                                         }
398                                         if err = tmp.Close(); err != nil {
399                                                 log.Fatalln("Error during closing:", err)
400                                         }
401                                         if err = os.MkdirAll(dstDirPath, os.FileMode(0777)); err != nil {
402                                                 log.Fatalln("Error during mkdir:", err)
403                                         }
404                                         if err = os.Rename(tmp.Name(), dstPath); err != nil {
405                                                 log.Fatalln("Error during renaming:", err)
406                                         }
407                                         if err = nncp.DirSync(dstDirPath); err != nil {
408                                                 log.Fatalln("Error during syncing:", err)
409                                         }
410                                 }
411                         }
412                         for _, le := range les {
413                                 if le.K == "FullSize" {
414                                         les = append(les, nncp.LE{K: "Size", V: le.V})
415                                         break
416                                 }
417                         }
418                         ctx.LogI("nncp-bundle", les, "")
419                 }
420         }
421 }