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 sds["xx"] = string(nncp.TTx)
121 bufStdout := bufio.NewWriter(os.Stdout)
122 tarWr := tar.NewWriter(bufStdout)
123 for nodeId, _ := range nodeIds {
124 sds["node"] = nodeId.String()
125 for job := range ctx.Jobs(&nodeId, nncp.TTx) {
126 pktName = filepath.Base(job.Fd.Name())
128 if job.PktEnc.Nice > nice {
129 ctx.LogD("nncp-bundle", sds, "too nice")
130 job.Fd.Close() // #nosec G104
133 if err = tarWr.WriteHeader(&tar.Header{
134 Format: tar.FormatUSTAR,
135 Name: nncp.NNCPBundlePrefix,
137 Typeflag: tar.TypeDir,
139 log.Fatalln("Error writing tar header:", err)
141 if err = tarWr.WriteHeader(&tar.Header{
142 Format: tar.FormatPAX,
143 Name: strings.Join([]string{
144 nncp.NNCPBundlePrefix,
151 Typeflag: tar.TypeReg,
153 log.Fatalln("Error writing tar header:", err)
155 if _, err = nncp.CopyProgressed(
157 nncp.SdsAdd(sds, nncp.SDS{
158 "pkt": nncp.Base32Codec.EncodeToString(job.HshValue[:]),
159 "fullsize": job.Size,
163 log.Fatalln("Error during copying to tar:", err)
165 job.Fd.Close() // #nosec G104
166 if err = tarWr.Flush(); err != nil {
167 log.Fatalln("Error during tar flushing:", err)
169 if err = bufStdout.Flush(); err != nil {
170 log.Fatalln("Error during stdout flushing:", err)
173 if err = os.Remove(job.Fd.Name()); err != nil {
174 log.Fatalln("Error during deletion:", err)
177 ctx.LogI("nncp-bundle", nncp.SdsAdd(sds, nncp.SDS{"size": job.Size}), "")
180 if err = tarWr.Close(); err != nil {
181 log.Fatalln("Error during tar closing:", err)
184 bufStdin := bufio.NewReaderSize(os.Stdin, CopyBufSize*2)
185 pktEncBuf := make([]byte, nncp.PktEncOverhead)
186 var pktEnc *nncp.PktEnc
188 peeked, err := bufStdin.Peek(CopyBufSize)
189 if err != nil && err != io.EOF {
190 log.Fatalln("Error during reading:", err)
192 prefixIdx := bytes.Index(peeked, []byte(nncp.NNCPBundlePrefix))
197 bufStdin.Discard(bufStdin.Buffered() - (len(nncp.NNCPBundlePrefix) - 1)) // #nosec G104
200 if _, err = bufStdin.Discard(prefixIdx); err != nil {
203 tarR := tar.NewReader(bufStdin)
204 sds["xx"] = string(nncp.TRx)
205 entry, err := tarR.Next()
210 nncp.SdsAdd(sds, nncp.SDS{"err": err}),
216 if entry.Typeflag != tar.TypeDir {
217 ctx.LogD("nncp-bundle", sds, "Expected NNCP/")
220 entry, err = tarR.Next()
225 nncp.SdsAdd(sds, nncp.SDS{"err": err}),
231 sds["pkt"] = entry.Name
232 if entry.Size < nncp.PktEncOverhead {
233 ctx.LogD("nncp-bundle", sds, "Too small packet")
236 if !ctx.IsEnoughSpace(entry.Size) {
237 ctx.LogE("nncp-bundle", sds, errors.New("not enough spool space"), "")
240 pktName := filepath.Base(entry.Name)
241 if _, err = nncp.Base32Codec.DecodeString(pktName); err != nil {
242 ctx.LogD("nncp-bundle", nncp.SdsAdd(sds, nncp.SDS{"err": "bad packet name"}), "")
245 if _, err = io.ReadFull(tarR, pktEncBuf); err != nil {
246 ctx.LogD("nncp-bundle", nncp.SdsAdd(sds, nncp.SDS{"err": err}), "read")
249 if _, err = xdr.Unmarshal(bytes.NewReader(pktEncBuf), &pktEnc); err != nil {
250 ctx.LogD("nncp-bundle", sds, "Bad packet structure")
253 if pktEnc.Magic != nncp.MagicNNCPEv4 {
254 ctx.LogD("nncp-bundle", sds, "Bad packet magic number")
257 if pktEnc.Nice > nice {
258 ctx.LogD("nncp-bundle", sds, "too nice")
261 if *pktEnc.Sender == *ctx.SelfId && *doDelete {
262 if len(nodeIds) > 0 {
263 if _, exists := nodeIds[*pktEnc.Recipient]; !exists {
264 ctx.LogD("nncp-bundle", sds, "Recipient is not requested")
268 nodeId32 := nncp.Base32Codec.EncodeToString(pktEnc.Recipient[:])
269 sds["xx"] = string(nncp.TTx)
270 sds["node"] = nodeId32
272 dstPath := filepath.Join(
278 if _, err = os.Stat(dstPath); err != nil {
279 ctx.LogD("nncp-bundle", sds, "Packet is already missing")
282 hsh, err := blake2b.New256(nil)
284 log.Fatalln("Error during hasher creation:", err)
286 if _, err = hsh.Write(pktEncBuf); err != nil {
287 log.Fatalln("Error during writing:", err)
289 if _, err = nncp.CopyProgressed(
291 nncp.SdsAdd(sds, nncp.SDS{"fullsize": entry.Size}),
294 log.Fatalln("Error during copying:", err)
296 if nncp.Base32Codec.EncodeToString(hsh.Sum(nil)) == pktName {
297 ctx.LogI("nncp-bundle", sds, "removed")
299 os.Remove(dstPath) // #nosec G104
302 ctx.LogE("nncp-bundle", sds, errors.New("bad checksum"), "")
306 if *pktEnc.Recipient != *ctx.SelfId {
307 ctx.LogD("nncp-bundle", sds, "Unknown recipient")
310 if len(nodeIds) > 0 {
311 if _, exists := nodeIds[*pktEnc.Sender]; !exists {
312 ctx.LogD("nncp-bundle", sds, "Sender is not requested")
316 sender := nncp.Base32Codec.EncodeToString(pktEnc.Sender[:])
319 sds["fullsize"] = entry.Size
320 dstDirPath := filepath.Join(ctx.Spool, sender, string(nncp.TRx))
321 dstPath := filepath.Join(dstDirPath, pktName)
322 if _, err = os.Stat(dstPath); err == nil || !os.IsNotExist(err) {
323 ctx.LogD("nncp-bundle", sds, "Packet already exists")
326 if _, err = os.Stat(dstPath + nncp.SeenSuffix); err == nil || !os.IsNotExist(err) {
327 ctx.LogD("nncp-bundle", sds, "Packet already exists")
332 hsh, err := blake2b.New256(nil)
334 log.Fatalln("Error during hasher creation:", err)
336 if _, err = hsh.Write(pktEncBuf); err != nil {
337 log.Fatalln("Error during writing:", err)
339 if _, err = nncp.CopyProgressed(hsh, tarR, "check", sds, ctx.ShowPrgrs); err != nil {
340 log.Fatalln("Error during copying:", err)
342 if nncp.Base32Codec.EncodeToString(hsh.Sum(nil)) != pktName {
343 ctx.LogE("nncp-bundle", sds, errors.New("bad checksum"), "")
347 tmp, err := ctx.NewTmpFileWHash()
349 log.Fatalln("Error during temporary file creation:", err)
351 if _, err = tmp.W.Write(pktEncBuf); err != nil {
352 log.Fatalln("Error during writing:", err)
354 if _, err = nncp.CopyProgressed(tmp.W, tarR, "check", sds, ctx.ShowPrgrs); err != nil {
355 log.Fatalln("Error during copying:", err)
357 if err = tmp.W.Flush(); err != nil {
358 log.Fatalln("Error during flusing:", err)
360 if nncp.Base32Codec.EncodeToString(tmp.Hsh.Sum(nil)) == pktName {
361 if err = tmp.Commit(dstDirPath); err != nil {
362 log.Fatalln("Error during commiting:", err)
365 ctx.LogE("nncp-bundle", sds, errors.New("bad checksum"), "")
372 if _, err = nncp.CopyProgressed(ioutil.Discard, tarR, "Rx", sds, ctx.ShowPrgrs); err != nil {
373 log.Fatalln("Error during copying:", err)
376 tmp, err := ctx.NewTmpFile()
378 log.Fatalln("Error during temporary file creation:", err)
380 bufTmp := bufio.NewWriterSize(tmp, CopyBufSize)
381 if _, err = bufTmp.Write(pktEncBuf); err != nil {
382 log.Fatalln("Error during writing:", err)
384 if _, err = nncp.CopyProgressed(bufTmp, tarR, "Rx", sds, ctx.ShowPrgrs); err != nil {
385 log.Fatalln("Error during copying:", err)
387 if err = bufTmp.Flush(); err != nil {
388 log.Fatalln("Error during flushing:", err)
390 if err = tmp.Sync(); err != nil {
391 log.Fatalln("Error during syncing:", err)
393 if err = tmp.Close(); err != nil {
394 log.Fatalln("Error during closing:", err)
396 if err = os.MkdirAll(dstDirPath, os.FileMode(0777)); err != nil {
397 log.Fatalln("Error during mkdir:", err)
399 if err = os.Rename(tmp.Name(), dstPath); err != nil {
400 log.Fatalln("Error during renaming:", err)
402 if err = nncp.DirSync(dstDirPath); err != nil {
403 log.Fatalln("Error during syncing:", err)
407 ctx.LogI("nncp-bundle", nncp.SdsAdd(sds, nncp.SDS{
408 "size": sds["fullsize"],