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