]> Cypherpunks.ru repositories - nncp.git/blob - src/cypherpunks.ru/nncp/cmd/nncp-bundle/main.go
e79f9e14d195d5f5e2879b939524e586e7f45dda
[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-2017 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.Fprintln(os.Stderr, "nncp-bundle -- Create/digest stream of NNCP encrypted packets\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.Int("nice", 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 not writings")
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         if *niceRaw < 1 || *niceRaw > 255 {
82                 log.Fatalln("-nice must be between 1 and 255")
83         }
84         nice := uint8(*niceRaw)
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                                         Name: strings.Join([]string{
124                                                 nncp.NNCPBundlePrefix,
125                                                 nodeId.String(),
126                                                 ctx.SelfId.String(),
127                                                 pktName,
128                                         }, "/"),
129                                         Mode:     0440,
130                                         Size:     job.Size,
131                                         Typeflag: tar.TypeReg,
132                                 }); err != nil {
133                                         log.Fatalln("Error writing tar header:", err)
134                                 }
135                                 if _, err = io.Copy(tarWr, job.Fd); err != nil {
136                                         log.Fatalln("Error during copying to tar:", err)
137                                 }
138                                 job.Fd.Close()
139                                 if err = tarWr.Flush(); err != nil {
140                                         log.Fatalln("Error during tar flushing:", err)
141                                 }
142                                 if err = bufStdout.Flush(); err != nil {
143                                         log.Fatalln("Error during stdout flushing:", err)
144                                 }
145                                 if *doDelete {
146                                         if err = os.Remove(job.Fd.Name()); err != nil {
147                                                 log.Fatalln("Error during deletion:", err)
148                                         }
149                                 }
150                                 ctx.LogI("nncp-bundle", nncp.SdsAdd(sds, nncp.SDS{
151                                         "size": strconv.FormatInt(job.Size, 10),
152                                 }), "")
153                         }
154                 }
155                 if err = tarWr.Close(); err != nil {
156                         log.Fatalln("Error during tar closing:", err)
157                 }
158         } else {
159                 bufStdin := bufio.NewReaderSize(os.Stdin, CopyBufSize*2)
160                 var peeked []byte
161                 var prefixIdx int
162                 var tarR *tar.Reader
163                 var entry *tar.Header
164                 var exists bool
165                 pktEncBuf := make([]byte, nncp.PktEncOverhead)
166                 var pktEnc *nncp.PktEnc
167                 var pktName string
168                 var selfPath string
169                 var dstPath string
170                 for {
171                         peeked, err = bufStdin.Peek(CopyBufSize)
172                         if err != nil && err != io.EOF {
173                                 log.Fatalln("Error during reading:", err)
174                         }
175                         prefixIdx = bytes.Index(peeked, []byte(nncp.NNCPBundlePrefix))
176                         if prefixIdx == -1 {
177                                 if err == io.EOF {
178                                         break
179                                 }
180                                 bufStdin.Discard(bufStdin.Buffered() - (len(nncp.NNCPBundlePrefix) - 1))
181                                 continue
182                         }
183                         bufStdin.Discard(prefixIdx)
184                         tarR = tar.NewReader(bufStdin)
185                         sds["xx"] = string(nncp.TRx)
186                         entry, err = tarR.Next()
187                         if err != nil {
188                                 if err != io.EOF {
189                                         ctx.LogD(
190                                                 "nncp-bundle",
191                                                 nncp.SdsAdd(sds, nncp.SDS{"err": err}),
192                                                 "error reading tar",
193                                         )
194                                 }
195                                 continue
196                         }
197                         sds["pkt"] = entry.Name
198                         if entry.Size < nncp.PktEncOverhead {
199                                 ctx.LogD("nncp-bundle", sds, "Too small packet")
200                                 continue
201                         }
202                         pktName = filepath.Base(entry.Name)
203                         if _, err = nncp.FromBase32(pktName); err != nil {
204                                 ctx.LogD("nncp-bundle", sds, "Bad packet name")
205                                 continue
206                         }
207                         if _, err = io.ReadFull(tarR, pktEncBuf); err != nil {
208                                 ctx.LogD("nncp-bundle", nncp.SdsAdd(sds, nncp.SDS{"err": err}), "read")
209                                 continue
210                         }
211                         if _, err = xdr.Unmarshal(bytes.NewReader(pktEncBuf), &pktEnc); err != nil {
212                                 ctx.LogD("nncp-bundle", sds, "Bad packet structure")
213                                 continue
214                         }
215                         if pktEnc.Magic != nncp.MagicNNCPEv2 {
216                                 ctx.LogD("nncp-bundle", sds, "Bad packet magic number")
217                                 continue
218                         }
219                         if pktEnc.Nice > nice {
220                                 ctx.LogD("nncp-bundle", sds, "too nice")
221                                 continue
222                         }
223                         if *pktEnc.Sender == *ctx.SelfId && *doDelete {
224                                 if len(nodeIds) > 0 {
225                                         if _, exists = nodeIds[*pktEnc.Recipient]; !exists {
226                                                 ctx.LogD("nncp-bundle", sds, "Recipient is not requested")
227                                                 continue
228                                         }
229                                 }
230                                 nodeId32 := nncp.ToBase32(pktEnc.Recipient[:])
231                                 sds["xx"] = string(nncp.TTx)
232                                 sds["node"] = nodeId32
233                                 sds["pkt"] = pktName
234                                 dstPath = filepath.Join(
235                                         ctx.Spool,
236                                         nodeId32,
237                                         string(nncp.TTx),
238                                         pktName,
239                                 )
240                                 if _, err = os.Stat(dstPath); err != nil {
241                                         ctx.LogD("nncp-bundle", sds, "Packet is already missing")
242                                         continue
243                                 }
244                                 hsh, err := blake2b.New256(nil)
245                                 if err != nil {
246                                         log.Fatalln("Error during hasher creation:", err)
247                                 }
248                                 if _, err = hsh.Write(pktEncBuf); err != nil {
249                                         log.Fatalln("Error during writing:", err)
250                                 }
251                                 if _, err = io.Copy(hsh, tarR); err != nil {
252                                         log.Fatalln("Error during copying:", err)
253                                 }
254                                 if nncp.ToBase32(hsh.Sum(nil)) == pktName {
255                                         ctx.LogI("nncp-bundle", sds, "removed")
256                                         if !*dryRun {
257                                                 os.Remove(dstPath)
258                                         }
259                                 } else {
260                                         ctx.LogE("nncp-bundle", sds, "bad checksum")
261                                 }
262                                 continue
263                         }
264                         if *pktEnc.Recipient != *ctx.SelfId {
265                                 ctx.LogD("nncp-bundle", sds, "Unknown recipient")
266                                 continue
267                         }
268                         if len(nodeIds) > 0 {
269                                 if _, exists = nodeIds[*pktEnc.Sender]; !exists {
270                                         ctx.LogD("nncp-bundle", sds, "Sender is not requested")
271                                         continue
272                                 }
273                         }
274                         sds["node"] = nncp.ToBase32(pktEnc.Recipient[:])
275                         sds["pkt"] = pktName
276                         selfPath = filepath.Join(ctx.Spool, ctx.SelfId.String(), string(nncp.TRx))
277                         dstPath = filepath.Join(selfPath, pktName)
278                         if _, err = os.Stat(dstPath); err == nil || !os.IsNotExist(err) {
279                                 ctx.LogD("nncp-bundle", sds, "Packet already exists")
280                                 continue
281                         }
282                         if _, err = os.Stat(dstPath + nncp.SeenSuffix); err == nil || !os.IsNotExist(err) {
283                                 ctx.LogD("nncp-bundle", sds, "Packet already exists")
284                                 continue
285                         }
286                         if *doCheck {
287                                 if *dryRun {
288                                         hsh, err := blake2b.New256(nil)
289                                         if err != nil {
290                                                 log.Fatalln("Error during hasher creation:", err)
291                                         }
292                                         if _, err = hsh.Write(pktEncBuf); err != nil {
293                                                 log.Fatalln("Error during writing:", err)
294                                         }
295                                         if _, err = io.Copy(hsh, tarR); err != nil {
296                                                 log.Fatalln("Error during copying:", err)
297                                         }
298                                         if nncp.ToBase32(hsh.Sum(nil)) != pktName {
299                                                 ctx.LogE("nncp-bundle", sds, "bad checksum")
300                                                 continue
301                                         }
302                                 } else {
303                                         tmp, err := ctx.NewTmpFileWHash()
304                                         if err != nil {
305                                                 log.Fatalln("Error during temporary file creation:", err)
306                                         }
307                                         if _, err = tmp.W.Write(pktEncBuf); err != nil {
308                                                 log.Fatalln("Error during writing:", err)
309                                         }
310                                         if _, err = io.Copy(tmp.W, tarR); err != nil {
311                                                 log.Fatalln("Error during copying:", err)
312                                         }
313                                         if err = tmp.W.Flush(); err != nil {
314                                                 log.Fatalln("Error during flusing:", err)
315                                         }
316                                         if nncp.ToBase32(tmp.Hsh.Sum(nil)) == pktName {
317                                                 if err = tmp.Commit(selfPath); err != nil {
318                                                         log.Fatalln("Error during commiting:", err)
319                                                 }
320                                         } else {
321                                                 ctx.LogE("nncp-bundle", sds, "bad checksum")
322                                                 tmp.Cancel()
323                                                 continue
324                                         }
325                                 }
326                         } else {
327                                 if *dryRun {
328                                         if _, err = io.Copy(ioutil.Discard, tarR); err != nil {
329                                                 log.Fatalln("Error during copying:", err)
330                                         }
331                                 } else {
332                                         tmp, err := ctx.NewTmpFile()
333                                         if err != nil {
334                                                 log.Fatalln("Error during temporary file creation:", err)
335                                         }
336                                         bufTmp := bufio.NewWriterSize(tmp, CopyBufSize)
337                                         if _, err = bufTmp.Write(pktEncBuf); err != nil {
338                                                 log.Fatalln("Error during writing:", err)
339                                         }
340                                         if _, err = io.Copy(bufTmp, tarR); err != nil {
341                                                 log.Fatalln("Error during copying:", err)
342                                         }
343                                         if err = bufTmp.Flush(); err != nil {
344                                                 log.Fatalln("Error during flushing:", err)
345                                         }
346                                         tmp.Sync()
347                                         tmp.Close()
348                                         if err = os.MkdirAll(selfPath, os.FileMode(0700)); err != nil {
349                                                 log.Fatalln("Error during mkdir:", err)
350                                         }
351                                         if err = os.Rename(tmp.Name(), dstPath); err != nil {
352                                                 log.Fatalln("Error during renaming:", err)
353                                         }
354                                 }
355                         }
356                         ctx.LogI("nncp-bundle", nncp.SdsAdd(sds, nncp.SDS{
357                                 "size": strconv.FormatInt(entry.Size, 10),
358                         }), "")
359                 }
360         }
361 }