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