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