2 NNCP -- Node to Node copy, utilities for store-and-forward data exchange
3 Copyright (C) 2016-2017 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, either version 3 of the License, or
8 (at your option) any later version.
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.
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/>.
19 // Create/digest stream of NNCP encrypted packets
37 "github.com/davecgh/go-xdr/xdr2"
38 "golang.org/x/crypto/blake2b"
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 [NODE ...] < ...\n", os.Args[0])
50 fmt.Fprintf(os.Stderr, " %s [options] -rx [-check] [NODE ...] < ...\n", os.Args[0])
51 fmt.Fprintln(os.Stderr, "Options:")
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 quiet = flag.Bool("quiet", false, "Print only errors")
64 debug = flag.Bool("debug", false, "Print debug messages")
65 version = flag.Bool("version", false, "Print version information")
66 warranty = flag.Bool("warranty", false, "Print warranty information")
71 fmt.Println(nncp.Warranty)
75 fmt.Println(nncp.VersionGet())
78 if *niceRaw < 1 || *niceRaw > 255 {
79 log.Fatalln("-nice must be between 1 and 255")
81 nice := uint8(*niceRaw)
83 log.Fatalln("-rx and -tx can not be set simultaneously")
86 log.Fatalln("At least one of -rx and -tx must be specified")
89 cfgRaw, err := ioutil.ReadFile(nncp.CfgPathFromEnv(cfgPath))
91 log.Fatalln("Can not read config:", err)
93 ctx, err := nncp.CfgParse(cfgRaw)
95 log.Fatalln("Can not parse config:", err)
100 nodeIds := make(map[nncp.NodeId]struct{}, flag.NArg())
101 for i := 0; i < flag.NArg(); i++ {
102 node, err := ctx.FindNode(flag.Arg(i))
104 log.Fatalln("Invalid specified:", err)
106 nodeIds[*node.Id] = struct{}{}
111 sds["xx"] = string(nncp.TTx)
113 bufStdout := bufio.NewWriter(os.Stdout)
114 tarWr := tar.NewWriter(bufStdout)
115 for nodeId, _ := range nodeIds {
116 sds["node"] = nodeId.String()
117 for job := range ctx.Jobs(&nodeId, nncp.TTx) {
118 pktName = filepath.Base(job.Fd.Name())
120 if job.PktEnc.Nice > nice {
121 ctx.LogD("nncp-bundle", sds, "too nice")
125 if err = tarWr.WriteHeader(&tar.Header{
126 Name: strings.Join([]string{
127 nncp.NNCPBundlePrefix,
134 Typeflag: tar.TypeReg,
136 log.Fatalln("Error writing tar header:", err)
138 if _, err = io.Copy(tarWr, job.Fd); err != nil {
139 log.Fatalln("Error during copying to tar:", err)
142 if err = tarWr.Flush(); err != nil {
143 log.Fatalln("Error during tar flushing:", err)
145 if err = bufStdout.Flush(); err != nil {
146 log.Fatalln("Error during stdout flushing:", err)
149 if err = os.Remove(job.Fd.Name()); err != nil {
150 log.Fatalln("Error during deletion:", err)
153 ctx.LogI("nncp-bundle", nncp.SdsAdd(sds, nncp.SDS{
154 "size": strconv.FormatInt(job.Size, 10),
158 if err = tarWr.Close(); err != nil {
159 log.Fatalln("Error during tar closing:", err)
162 bufStdin := bufio.NewReaderSize(os.Stdin, CopyBufSize*2)
166 var entry *tar.Header
168 pktEncBuf := make([]byte, nncp.PktEncOverhead)
169 var pktEnc *nncp.PktEnc
174 peeked, err = bufStdin.Peek(CopyBufSize)
175 if err != nil && err != io.EOF {
176 log.Fatalln("Error during reading:", err)
178 prefixIdx = bytes.Index(peeked, []byte(nncp.NNCPBundlePrefix))
183 bufStdin.Discard(bufStdin.Buffered() - (len(nncp.NNCPBundlePrefix) - 1))
186 bufStdin.Discard(prefixIdx)
187 tarR = tar.NewReader(bufStdin)
188 sds["xx"] = string(nncp.TRx)
189 entry, err = tarR.Next()
194 nncp.SdsAdd(sds, nncp.SDS{"err": err}),
200 sds["pkt"] = entry.Name
201 if entry.Size < nncp.PktEncOverhead {
202 ctx.LogD("nncp-bundle", sds, "Too small packet")
205 pktName = filepath.Base(entry.Name)
206 if _, err = nncp.FromBase32(pktName); err != nil {
207 ctx.LogD("nncp-bundle", sds, "Bad packet name")
210 if _, err = io.ReadFull(tarR, pktEncBuf); err != nil {
211 ctx.LogD("nncp-bundle", nncp.SdsAdd(sds, nncp.SDS{"err": err}), "read")
214 if _, err = xdr.Unmarshal(bytes.NewReader(pktEncBuf), &pktEnc); err != nil {
215 ctx.LogD("nncp-bundle", sds, "Bad packet structure")
218 if pktEnc.Magic != nncp.MagicNNCPEv2 {
219 ctx.LogD("nncp-bundle", sds, "Bad packet magic number")
222 if pktEnc.Nice > nice {
223 ctx.LogD("nncp-bundle", sds, "too nice")
226 if *pktEnc.Sender == *ctx.SelfId && *doDelete {
227 if len(nodeIds) > 0 {
228 if _, exists = nodeIds[*pktEnc.Recipient]; !exists {
229 ctx.LogD("nncp-bundle", sds, "Recipient is not requested")
233 nodeId32 := nncp.ToBase32(pktEnc.Recipient[:])
234 sds["xx"] = string(nncp.TTx)
235 sds["node"] = nodeId32
237 dstPath = filepath.Join(
243 if _, err = os.Stat(dstPath); err != nil {
244 ctx.LogD("nncp-bundle", sds, "Packet is already missing")
247 hsh, err := blake2b.New256(nil)
249 log.Fatalln("Error during hasher creation:", err)
251 if _, err = hsh.Write(pktEncBuf); err != nil {
252 log.Fatalln("Error during writing:", err)
254 if _, err = io.Copy(hsh, tarR); err != nil {
255 log.Fatalln("Error during copying:", err)
257 if nncp.ToBase32(hsh.Sum(nil)) == pktName {
258 ctx.LogI("nncp-bundle", sds, "removed")
261 ctx.LogE("nncp-bundle", sds, "bad checksum")
265 if *pktEnc.Recipient != *ctx.SelfId {
266 ctx.LogD("nncp-bundle", sds, "Unknown recipient")
269 if len(nodeIds) > 0 {
270 if _, exists = nodeIds[*pktEnc.Sender]; !exists {
271 ctx.LogD("nncp-bundle", sds, "Sender is not requested")
275 sds["node"] = nncp.ToBase32(pktEnc.Recipient[:])
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")
283 if _, err = os.Stat(dstPath + nncp.SeenPostfix); err == nil || !os.IsNotExist(err) {
284 ctx.LogD("nncp-bundle", sds, "Packet already exists")
288 tmp, err := ctx.NewTmpFileWHash()
290 log.Fatalln("Error during temporary file creation:", err)
292 if _, err = tmp.W.Write(pktEncBuf); err != nil {
293 log.Fatalln("Error during writing:", err)
295 if _, err = io.Copy(tmp.W, tarR); err != nil {
296 log.Fatalln("Error during copying:", err)
298 if err = tmp.W.Flush(); err != nil {
299 log.Fatalln("Error during flusing:", err)
301 if nncp.ToBase32(tmp.Hsh.Sum(nil)) == pktName {
302 if err = tmp.Commit(selfPath); err != nil {
303 log.Fatalln("Error during commiting:", err)
306 ctx.LogE("nncp-bundle", sds, "bad checksum")
311 tmp, err := ctx.NewTmpFile()
313 log.Fatalln("Error during temporary file creation:", err)
315 bufTmp := bufio.NewWriterSize(tmp, CopyBufSize)
316 if _, err = bufTmp.Write(pktEncBuf); err != nil {
317 log.Fatalln("Error during writing:", err)
319 if _, err = io.Copy(bufTmp, tarR); err != nil {
320 log.Fatalln("Error during copying:", err)
322 if err = bufTmp.Flush(); err != nil {
323 log.Fatalln("Error during flushing:", err)
327 if err = os.MkdirAll(selfPath, os.FileMode(0700)); err != nil {
328 log.Fatalln("Error during mkdir:", err)
330 if err = os.Rename(tmp.Name(), dstPath); err != nil {
331 log.Fatalln("Error during renaming:", err)
334 ctx.LogI("nncp-bundle", nncp.SdsAdd(sds, nncp.SDS{
335 "size": strconv.FormatInt(entry.Size, 10),