2 NNCP -- Node to Node copy, utilities for store-and-forward data exchange
3 Copyright (C) 2016-2021 Sergey Matveev <stargrave@stargrave.org>
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.
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.
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/>.
18 // Create/digest stream of NNCP encrypted packets.
35 xdr "github.com/davecgh/go-xdr/xdr2"
36 "go.cypherpunks.ru/nncp/v5"
37 "golang.org/x/crypto/blake2b"
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:")
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")
75 fmt.Println(nncp.Warranty)
79 fmt.Println(nncp.VersionGet())
82 nice, err := nncp.NicenessParse(*niceRaw)
87 log.Fatalln("-rx and -tx can not be set simultaneously")
90 log.Fatalln("At least one of -rx and -tx must be specified")
93 ctx, err := nncp.CtxFromCmdline(
103 log.Fatalln("Error during initialization:", err)
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))
110 log.Fatalln("Invalid specified:", err)
112 nodeIds[*node.Id] = struct{}{}
119 bufStdout := bufio.NewWriter(os.Stdout)
120 tarWr := tar.NewWriter(bufStdout)
121 for nodeId := range nodeIds {
123 {K: "XX", V: string(nncp.TTx)},
124 {K: "Node", V: nodeId.String()},
125 {K: "Pkt", V: "dummy"},
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")
134 fd, err := os.Open(job.Path)
136 log.Fatalln("Error during opening:", err)
138 if err = tarWr.WriteHeader(&tar.Header{
139 Format: tar.FormatUSTAR,
140 Name: nncp.NNCPBundlePrefix,
142 Typeflag: tar.TypeDir,
144 log.Fatalln("Error writing tar header:", err)
146 if err = tarWr.WriteHeader(&tar.Header{
147 Format: tar.FormatPAX,
148 Name: strings.Join([]string{
149 nncp.NNCPBundlePrefix,
156 Typeflag: tar.TypeReg,
158 log.Fatalln("Error writing tar header:", err)
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},
168 log.Fatalln("Error during copying to tar:", err)
170 if err = fd.Close(); err != nil {
171 log.Fatalln("Error during closing:", err)
173 if err = tarWr.Flush(); err != nil {
174 log.Fatalln("Error during tar flushing:", err)
176 if err = bufStdout.Flush(); err != nil {
177 log.Fatalln("Error during stdout flushing:", err)
180 if err = os.Remove(job.Path); err != nil {
181 log.Fatalln("Error during deletion:", err)
184 ctx.LogI("nncp-bundle", append(les, nncp.LE{K: "Size", V: job.Size}), "")
187 if err = tarWr.Close(); err != nil {
188 log.Fatalln("Error during tar closing:", err)
191 bufStdin := bufio.NewReaderSize(os.Stdin, CopyBufSize*2)
192 pktEncBuf := make([]byte, nncp.PktEncOverhead)
193 var pktEnc *nncp.PktEnc
195 peeked, err := bufStdin.Peek(CopyBufSize)
196 if err != nil && err != io.EOF {
197 log.Fatalln("Error during reading:", err)
199 prefixIdx := bytes.Index(peeked, []byte(nncp.NNCPBundlePrefix))
204 bufStdin.Discard(bufStdin.Buffered() - (len(nncp.NNCPBundlePrefix) - 1)) // #nosec G104
207 if _, err = bufStdin.Discard(prefixIdx); err != nil {
210 tarR := tar.NewReader(bufStdin)
211 entry, err := tarR.Next()
216 nncp.LEs{{K: "XX", V: string(nncp.TRx)}, {K: "Err", V: err}},
222 if entry.Typeflag != tar.TypeDir {
225 nncp.LEs{{K: "XX", V: string(nncp.TRx)}},
230 entry, err = tarR.Next()
235 nncp.LEs{{K: "XX", V: string(nncp.TRx)}, {K: "Err", V: err}},
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")
246 if !ctx.IsEnoughSpace(entry.Size) {
247 ctx.LogE("nncp-bundle", les, errors.New("not enough spool space"), "")
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"}), "")
255 if _, err = io.ReadFull(tarR, pktEncBuf); err != nil {
256 ctx.LogD("nncp-bundle", append(les, nncp.LE{K: "Err", V: err}), "read")
259 if _, err = xdr.Unmarshal(bytes.NewReader(pktEncBuf), &pktEnc); err != nil {
260 ctx.LogD("nncp-bundle", les, "Bad packet structure")
263 if pktEnc.Magic != nncp.MagicNNCPEv4 {
264 ctx.LogD("nncp-bundle", les, "Bad packet magic number")
267 if pktEnc.Nice > nice {
268 ctx.LogD("nncp-bundle", les, "too nice")
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")
278 nodeId32 := nncp.Base32Codec.EncodeToString(pktEnc.Recipient[:])
280 {K: "XX", V: string(nncp.TTx)},
281 {K: "Node", V: nodeId32},
282 {K: "Pkt", V: pktName},
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")
289 hsh, err := blake2b.New256(nil)
291 log.Fatalln("Error during hasher creation:", err)
293 if _, err = hsh.Write(pktEncBuf); err != nil {
294 log.Fatalln("Error during writing:", err)
296 if _, err = nncp.CopyProgressed(
298 append(les, nncp.LE{K: "FullSize", V: entry.Size}),
301 log.Fatalln("Error during copying:", err)
303 if nncp.Base32Codec.EncodeToString(hsh.Sum(nil)) == pktName {
304 ctx.LogI("nncp-bundle", les, "removed")
306 os.Remove(dstPath) // #nosec G104
309 ctx.LogE("nncp-bundle", les, errors.New("bad checksum"), "")
313 if *pktEnc.Recipient != *ctx.SelfId {
314 ctx.LogD("nncp-bundle", les, "Unknown recipient")
317 if len(nodeIds) > 0 {
318 if _, exists := nodeIds[*pktEnc.Sender]; !exists {
319 ctx.LogD("nncp-bundle", les, "Sender is not requested")
323 sender := nncp.Base32Codec.EncodeToString(pktEnc.Sender[:])
325 {K: "XX", V: string(nncp.TRx)},
326 {K: "Node", V: sender},
327 {K: "Pkt", V: pktName},
328 {K: "FullSize", V: entry.Size},
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")
336 if _, err = os.Stat(dstPath + nncp.SeenSuffix); err == nil || !os.IsNotExist(err) {
337 ctx.LogD("nncp-bundle", les, "Packet already exists")
342 hsh, err := blake2b.New256(nil)
344 log.Fatalln("Error during hasher creation:", err)
346 if _, err = hsh.Write(pktEncBuf); err != nil {
347 log.Fatalln("Error during writing:", err)
349 if _, err = nncp.CopyProgressed(hsh, tarR, "check", les, ctx.ShowPrgrs); err != nil {
350 log.Fatalln("Error during copying:", err)
352 if nncp.Base32Codec.EncodeToString(hsh.Sum(nil)) != pktName {
353 ctx.LogE("nncp-bundle", les, errors.New("bad checksum"), "")
357 tmp, err := ctx.NewTmpFileWHash()
359 log.Fatalln("Error during temporary file creation:", err)
361 if _, err = tmp.W.Write(pktEncBuf); err != nil {
362 log.Fatalln("Error during writing:", err)
364 if _, err = nncp.CopyProgressed(tmp.W, tarR, "check", les, ctx.ShowPrgrs); err != nil {
365 log.Fatalln("Error during copying:", err)
367 if err = tmp.W.Flush(); err != nil {
368 log.Fatalln("Error during flusing:", err)
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)
375 ctx.LogE("nncp-bundle", les, errors.New("bad checksum"), "")
382 if _, err = nncp.CopyProgressed(ioutil.Discard, tarR, "Rx", les, ctx.ShowPrgrs); err != nil {
383 log.Fatalln("Error during copying:", err)
386 tmp, err := ctx.NewTmpFile()
388 log.Fatalln("Error during temporary file creation:", err)
390 bufTmp := bufio.NewWriterSize(tmp, CopyBufSize)
391 if _, err = bufTmp.Write(pktEncBuf); err != nil {
392 log.Fatalln("Error during writing:", err)
394 if _, err = nncp.CopyProgressed(bufTmp, tarR, "Rx", les, ctx.ShowPrgrs); err != nil {
395 log.Fatalln("Error during copying:", err)
397 if err = bufTmp.Flush(); err != nil {
398 log.Fatalln("Error during flushing:", err)
400 if err = tmp.Sync(); err != nil {
401 log.Fatalln("Error during syncing:", err)
403 if err = tmp.Close(); err != nil {
404 log.Fatalln("Error during closing:", err)
406 if err = os.MkdirAll(dstDirPath, os.FileMode(0777)); err != nil {
407 log.Fatalln("Error during mkdir:", err)
409 if err = os.Rename(tmp.Name(), dstPath); err != nil {
410 log.Fatalln("Error during renaming:", err)
412 if err = nncp.DirSync(dstDirPath); err != nil {
413 log.Fatalln("Error during syncing:", err)
417 for _, le := range les {
418 if le.K == "FullSize" {
419 les = append(les, nncp.LE{K: "Size", V: le.V})
423 ctx.LogI("nncp-bundle", les, "")