]> Cypherpunks.ru repositories - nncp.git/blob - src/cmd/nncp-bundle/main.go
Operations progress
[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-2019 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         sds := nncp.SDS{}
118         if *doTx {
119                 sds["xx"] = string(nncp.TTx)
120                 var pktName string
121                 bufStdout := bufio.NewWriter(os.Stdout)
122                 tarWr := tar.NewWriter(bufStdout)
123                 for nodeId, _ := range nodeIds {
124                         sds["node"] = nodeId.String()
125                         for job := range ctx.Jobs(&nodeId, nncp.TTx) {
126                                 pktName = filepath.Base(job.Fd.Name())
127                                 sds["pkt"] = pktName
128                                 if job.PktEnc.Nice > nice {
129                                         ctx.LogD("nncp-bundle", sds, "too nice")
130                                         job.Fd.Close()
131                                         continue
132                                 }
133                                 if err = tarWr.WriteHeader(&tar.Header{
134                                         Format:   tar.FormatUSTAR,
135                                         Name:     nncp.NNCPBundlePrefix,
136                                         Mode:     0700,
137                                         Typeflag: tar.TypeDir,
138                                 }); err != nil {
139                                         log.Fatalln("Error writing tar header:", err)
140                                 }
141                                 if err = tarWr.WriteHeader(&tar.Header{
142                                         Format: tar.FormatPAX,
143                                         Name: strings.Join([]string{
144                                                 nncp.NNCPBundlePrefix,
145                                                 nodeId.String(),
146                                                 ctx.SelfId.String(),
147                                                 pktName,
148                                         }, "/"),
149                                         Mode:     0400,
150                                         Size:     job.Size,
151                                         Typeflag: tar.TypeReg,
152                                 }); err != nil {
153                                         log.Fatalln("Error writing tar header:", err)
154                                 }
155                                 if _, err = nncp.CopyProgressed(
156                                         tarWr, job.Fd,
157                                         nncp.SdsAdd(sds, nncp.SDS{
158                                                 "pkt":      nncp.ToBase32(job.HshValue[:]),
159                                                 "fullsize": job.Size,
160                                         }),
161                                         ctx.ShowPrgrs,
162                                 ); err != nil {
163                                         log.Fatalln("Error during copying to tar:", err)
164                                 }
165                                 job.Fd.Close()
166                                 if err = tarWr.Flush(); err != nil {
167                                         log.Fatalln("Error during tar flushing:", err)
168                                 }
169                                 if err = bufStdout.Flush(); err != nil {
170                                         log.Fatalln("Error during stdout flushing:", err)
171                                 }
172                                 if *doDelete {
173                                         if err = os.Remove(job.Fd.Name()); err != nil {
174                                                 log.Fatalln("Error during deletion:", err)
175                                         }
176                                 }
177                                 ctx.LogI("nncp-bundle", nncp.SdsAdd(sds, nncp.SDS{"size": job.Size}), "")
178                         }
179                 }
180                 if err = tarWr.Close(); err != nil {
181                         log.Fatalln("Error during tar closing:", err)
182                 }
183         } else {
184                 bufStdin := bufio.NewReaderSize(os.Stdin, CopyBufSize*2)
185                 var peeked []byte
186                 var prefixIdx int
187                 var tarR *tar.Reader
188                 var entry *tar.Header
189                 var exists bool
190                 pktEncBuf := make([]byte, nncp.PktEncOverhead)
191                 var pktEnc *nncp.PktEnc
192                 var pktName string
193                 var selfPath string
194                 var dstPath string
195                 for {
196                         peeked, err = bufStdin.Peek(CopyBufSize)
197                         if err != nil && err != io.EOF {
198                                 log.Fatalln("Error during reading:", err)
199                         }
200                         prefixIdx = bytes.Index(peeked, []byte(nncp.NNCPBundlePrefix))
201                         if prefixIdx == -1 {
202                                 if err == io.EOF {
203                                         break
204                                 }
205                                 bufStdin.Discard(bufStdin.Buffered() - (len(nncp.NNCPBundlePrefix) - 1))
206                                 continue
207                         }
208                         bufStdin.Discard(prefixIdx)
209                         tarR = tar.NewReader(bufStdin)
210                         sds["xx"] = string(nncp.TRx)
211                         entry, err = tarR.Next()
212                         if err != nil {
213                                 if err != io.EOF {
214                                         ctx.LogD(
215                                                 "nncp-bundle",
216                                                 nncp.SdsAdd(sds, nncp.SDS{"err": err}),
217                                                 "error reading tar",
218                                         )
219                                 }
220                                 continue
221                         }
222                         if entry.Typeflag != tar.TypeDir {
223                                 ctx.LogD("nncp-bundle", sds, "Expected NNCP/")
224                                 continue
225                         }
226                         entry, err = tarR.Next()
227                         if err != nil {
228                                 if err != io.EOF {
229                                         ctx.LogD(
230                                                 "nncp-bundle",
231                                                 nncp.SdsAdd(sds, nncp.SDS{"err": err}),
232                                                 "error reading tar",
233                                         )
234                                 }
235                                 continue
236                         }
237                         sds["pkt"] = entry.Name
238                         if entry.Size < nncp.PktEncOverhead {
239                                 ctx.LogD("nncp-bundle", sds, "Too small packet")
240                                 continue
241                         }
242                         pktName = filepath.Base(entry.Name)
243                         if _, err = nncp.FromBase32(pktName); err != nil {
244                                 ctx.LogD("nncp-bundle", nncp.SdsAdd(sds, nncp.SDS{"err": "bad packet name"}), "")
245                                 continue
246                         }
247                         if _, err = io.ReadFull(tarR, pktEncBuf); err != nil {
248                                 ctx.LogD("nncp-bundle", nncp.SdsAdd(sds, nncp.SDS{"err": err}), "read")
249                                 continue
250                         }
251                         if _, err = xdr.Unmarshal(bytes.NewReader(pktEncBuf), &pktEnc); err != nil {
252                                 ctx.LogD("nncp-bundle", sds, "Bad packet structure")
253                                 continue
254                         }
255                         if pktEnc.Magic != nncp.MagicNNCPEv4 {
256                                 ctx.LogD("nncp-bundle", sds, "Bad packet magic number")
257                                 continue
258                         }
259                         if pktEnc.Nice > nice {
260                                 ctx.LogD("nncp-bundle", sds, "too nice")
261                                 continue
262                         }
263                         if *pktEnc.Sender == *ctx.SelfId && *doDelete {
264                                 if len(nodeIds) > 0 {
265                                         if _, exists = nodeIds[*pktEnc.Recipient]; !exists {
266                                                 ctx.LogD("nncp-bundle", sds, "Recipient is not requested")
267                                                 continue
268                                         }
269                                 }
270                                 nodeId32 := nncp.ToBase32(pktEnc.Recipient[:])
271                                 sds["xx"] = string(nncp.TTx)
272                                 sds["node"] = nodeId32
273                                 sds["pkt"] = pktName
274                                 dstPath = filepath.Join(
275                                         ctx.Spool,
276                                         nodeId32,
277                                         string(nncp.TTx),
278                                         pktName,
279                                 )
280                                 if _, err = os.Stat(dstPath); err != nil {
281                                         ctx.LogD("nncp-bundle", sds, "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,
293                                         nncp.SdsAdd(sds, nncp.SDS{"fullsize": entry.Size}),
294                                         ctx.ShowPrgrs,
295                                 ); err != nil {
296                                         log.Fatalln("Error during copying:", err)
297                                 }
298                                 if nncp.ToBase32(hsh.Sum(nil)) == pktName {
299                                         ctx.LogI("nncp-bundle", sds, "removed")
300                                         if !*dryRun {
301                                                 os.Remove(dstPath)
302                                         }
303                                 } else {
304                                         ctx.LogE("nncp-bundle", sds, errors.New("bad checksum"), "")
305                                 }
306                                 continue
307                         }
308                         if *pktEnc.Recipient != *ctx.SelfId {
309                                 ctx.LogD("nncp-bundle", sds, "Unknown recipient")
310                                 continue
311                         }
312                         if len(nodeIds) > 0 {
313                                 if _, exists = nodeIds[*pktEnc.Sender]; !exists {
314                                         ctx.LogD("nncp-bundle", sds, "Sender is not requested")
315                                         continue
316                                 }
317                         }
318                         sds["node"] = nncp.ToBase32(pktEnc.Recipient[:])
319                         sds["pkt"] = pktName
320                         sds["fullsize"] = entry.Size
321                         selfPath = filepath.Join(ctx.Spool, ctx.SelfId.String(), string(nncp.TRx))
322                         dstPath = filepath.Join(selfPath, pktName)
323                         if _, err = os.Stat(dstPath); err == nil || !os.IsNotExist(err) {
324                                 ctx.LogD("nncp-bundle", sds, "Packet already exists")
325                                 continue
326                         }
327                         if _, err = os.Stat(dstPath + nncp.SeenSuffix); err == nil || !os.IsNotExist(err) {
328                                 ctx.LogD("nncp-bundle", sds, "Packet already exists")
329                                 continue
330                         }
331                         if *doCheck {
332                                 if *dryRun {
333                                         hsh, err := blake2b.New256(nil)
334                                         if err != nil {
335                                                 log.Fatalln("Error during hasher creation:", err)
336                                         }
337                                         if _, err = hsh.Write(pktEncBuf); err != nil {
338                                                 log.Fatalln("Error during writing:", err)
339                                         }
340                                         if _, err = nncp.CopyProgressed(hsh, tarR, sds, ctx.ShowPrgrs); err != nil {
341                                                 log.Fatalln("Error during copying:", err)
342                                         }
343                                         if nncp.ToBase32(hsh.Sum(nil)) != pktName {
344                                                 ctx.LogE("nncp-bundle", sds, errors.New("bad checksum"), "")
345                                                 continue
346                                         }
347                                 } else {
348                                         tmp, err := ctx.NewTmpFileWHash()
349                                         if err != nil {
350                                                 log.Fatalln("Error during temporary file creation:", err)
351                                         }
352                                         if _, err = tmp.W.Write(pktEncBuf); err != nil {
353                                                 log.Fatalln("Error during writing:", err)
354                                         }
355                                         if _, err = nncp.CopyProgressed(tmp.W, tarR, sds, ctx.ShowPrgrs); err != nil {
356                                                 log.Fatalln("Error during copying:", err)
357                                         }
358                                         if err = tmp.W.Flush(); err != nil {
359                                                 log.Fatalln("Error during flusing:", err)
360                                         }
361                                         if nncp.ToBase32(tmp.Hsh.Sum(nil)) == pktName {
362                                                 if err = tmp.Commit(selfPath); err != nil {
363                                                         log.Fatalln("Error during commiting:", err)
364                                                 }
365                                         } else {
366                                                 ctx.LogE("nncp-bundle", sds, errors.New("bad checksum"), "")
367                                                 tmp.Cancel()
368                                                 continue
369                                         }
370                                 }
371                         } else {
372                                 if *dryRun {
373                                         if _, err = nncp.CopyProgressed(ioutil.Discard, tarR, sds, ctx.ShowPrgrs); err != nil {
374                                                 log.Fatalln("Error during copying:", err)
375                                         }
376                                 } else {
377                                         tmp, err := ctx.NewTmpFile()
378                                         if err != nil {
379                                                 log.Fatalln("Error during temporary file creation:", err)
380                                         }
381                                         bufTmp := bufio.NewWriterSize(tmp, CopyBufSize)
382                                         if _, err = bufTmp.Write(pktEncBuf); err != nil {
383                                                 log.Fatalln("Error during writing:", err)
384                                         }
385                                         if _, err = nncp.CopyProgressed(bufTmp, tarR, sds, ctx.ShowPrgrs); err != nil {
386                                                 log.Fatalln("Error during copying:", err)
387                                         }
388                                         if err = bufTmp.Flush(); err != nil {
389                                                 log.Fatalln("Error during flushing:", err)
390                                         }
391                                         if err = tmp.Sync(); err != nil {
392                                                 log.Fatalln("Error during syncing:", err)
393                                         }
394                                         tmp.Close()
395                                         if err = os.MkdirAll(selfPath, os.FileMode(0777)); err != nil {
396                                                 log.Fatalln("Error during mkdir:", err)
397                                         }
398                                         if err = os.Rename(tmp.Name(), dstPath); err != nil {
399                                                 log.Fatalln("Error during renaming:", err)
400                                         }
401                                         if err = nncp.DirSync(selfPath); err != nil {
402                                                 log.Fatalln("Error during syncing:", err)
403                                         }
404                                 }
405                         }
406                         ctx.LogI("nncp-bundle", nncp.SdsAdd(sds, nncp.SDS{
407                                 "size": sds["fullsize"],
408                         }), "")
409                 }
410         }
411 }