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/>.
35 xdr "github.com/davecgh/go-xdr/xdr2"
36 "github.com/klauspost/compress/zstd"
37 "golang.org/x/crypto/blake2b"
38 "golang.org/x/crypto/chacha20poly1305"
56 hops := make([]*Node, 0, 1+len(node.Via))
57 hops = append(hops, node)
59 for i := len(node.Via); i > 0; i-- {
60 lastNode = ctx.Neigh[*node.Via[i-1]]
61 hops = append(hops, lastNode)
64 for i := 0; i < len(hops); i++ {
65 expectedSize = PktEncOverhead + PktSizeOverhead + sizeWithTags(PktOverhead+expectedSize)
67 padSize := minSize - expectedSize
71 if !ctx.IsEnoughSpace(size + padSize) {
72 return nil, errors.New("is not enough space")
74 tmp, err := ctx.NewTmpFileWHash()
79 errs := make(chan error)
81 pipeR, pipeW := io.Pipe()
82 go func(size int64, src io.Reader, dst io.WriteCloser) {
88 errs <- PktEncWrite(ctx.Self, hops[0], pkt, nice, size, padSize, src, dst)
89 dst.Close() // #nosec G104
90 }(curSize, src, pipeW)
91 curSize = PktEncOverhead + PktSizeOverhead + sizeWithTags(PktOverhead+curSize) + padSize
93 var pipeRPrev io.Reader
94 for i := 1; i < len(hops); i++ {
95 pktTrns, _ := NewPkt(PktTypeTrns, 0, hops[i-1].Id[:])
97 pipeR, pipeW = io.Pipe()
98 go func(node *Node, pkt *Pkt, size int64, src io.Reader, dst io.WriteCloser) {
104 errs <- PktEncWrite(ctx.Self, node, pkt, nice, size, 0, src, dst)
105 dst.Close() // #nosec G104
106 }(hops[i], pktTrns, curSize, pipeRPrev, pipeW)
107 curSize = PktEncOverhead + PktSizeOverhead + sizeWithTags(PktOverhead+curSize)
110 _, err := CopyProgressed(
112 LEs{{"Pkt", pktName}, {"FullSize", curSize}},
117 for i := 0; i <= len(hops); i++ {
120 tmp.Fd.Close() // #nosec G104
124 nodePath := filepath.Join(ctx.Spool, lastNode.Id.String())
125 err = tmp.Commit(filepath.Join(nodePath, string(TTx)))
126 os.Symlink(nodePath, filepath.Join(ctx.Spool, lastNode.Name)) // #nosec G104
130 type DummyCloser struct{}
132 func (dc DummyCloser) Close() error { return nil }
134 func throughTmpFile(r io.Reader) (
140 src, err := ioutil.TempFile("", "nncp-file")
145 os.Remove(src.Name()) // #nosec G104
146 tmpW := bufio.NewWriter(src)
147 tmpKey := make([]byte, chacha20poly1305.KeySize)
148 if _, rerr = rand.Read(tmpKey[:]); rerr != nil {
151 aead, err := chacha20poly1305.New(tmpKey)
156 nonce := make([]byte, aead.NonceSize())
157 written, err := aeadProcess(aead, nonce, true, r, tmpW)
162 fileSize = int64(written)
163 if err = tmpW.Flush(); err != nil {
167 if _, err = src.Seek(0, io.SeekStart); err != nil {
173 if _, err := aeadProcess(aead, nonce, false, bufio.NewReader(src), w); err != nil {
174 w.CloseWithError(err) // #nosec G104
182 func prepareTxFile(srcPath string) (
190 reader, closer, fileSize, rerr = throughTmpFile(bufio.NewReader(os.Stdin))
194 srcStat, err := os.Stat(srcPath)
199 mode := srcStat.Mode()
201 if mode.IsRegular() {
202 // It is regular file, just send it
203 src, err := os.Open(srcPath)
208 fileSize = srcStat.Size()
209 reader = bufio.NewReader(src)
215 rerr = errors.New("unsupported file type")
219 // It is directory, create PAX archive with its contents
221 basePath := filepath.Base(srcPath)
222 rootPath, err := filepath.Abs(srcPath)
232 dirs := make([]einfo, 0, 1<<10)
233 files := make([]einfo, 0, 1<<10)
234 rerr = filepath.Walk(rootPath, func(path string, info os.FileInfo, err error) error {
239 // directory header, PAX record header+contents
240 fileSize += TarBlockSize + 2*TarBlockSize
241 dirs = append(dirs, einfo{path: path, modTime: info.ModTime()})
243 // file header, PAX record header+contents, file content
244 fileSize += TarBlockSize + 2*TarBlockSize + info.Size()
245 if n := info.Size() % TarBlockSize; n != 0 {
246 fileSize += TarBlockSize - n // padding
248 files = append(files, einfo{
250 modTime: info.ModTime(),
262 closer = DummyCloser{}
263 fileSize += 2 * TarBlockSize // termination block
266 tarWr := tar.NewWriter(w)
268 Typeflag: tar.TypeDir,
270 PAXRecords: map[string]string{
271 "comment": "Autogenerated by " + VersionGet(),
273 Format: tar.FormatPAX,
275 for _, e := range dirs {
276 hdr.Name = basePath + e.path[len(rootPath):]
277 hdr.ModTime = e.modTime
278 if err = tarWr.WriteHeader(&hdr); err != nil {
279 return w.CloseWithError(err)
282 hdr.Typeflag = tar.TypeReg
284 for _, e := range files {
285 hdr.Name = basePath + e.path[len(rootPath):]
286 hdr.ModTime = e.modTime
288 if err = tarWr.WriteHeader(&hdr); err != nil {
289 return w.CloseWithError(err)
291 fd, err := os.Open(e.path)
293 fd.Close() // #nosec G104
294 return w.CloseWithError(err)
296 if _, err = io.Copy(tarWr, bufio.NewReader(fd)); err != nil {
297 fd.Close() // #nosec G104
298 return w.CloseWithError(err)
300 fd.Close() // #nosec G104
302 if err = tarWr.Close(); err != nil {
303 return w.CloseWithError(err)
310 func (ctx *Ctx) TxFile(
313 srcPath, dstPath string,
315 minSize, maxSize int64,
317 dstPathSpecified := false
320 return errors.New("Must provide destination filename")
322 dstPath = filepath.Base(srcPath)
324 dstPathSpecified = true
326 dstPath = filepath.Clean(dstPath)
327 if filepath.IsAbs(dstPath) {
328 return errors.New("Relative destination path required")
330 reader, closer, fileSize, archived, err := prepareTxFile(srcPath)
337 if fileSize > maxSize {
338 return errors.New("Too big than allowed")
340 if archived && !dstPathSpecified {
344 if fileSize <= chunkSize {
345 pkt, err := NewPkt(PktTypeFile, nice, []byte(dstPath))
349 _, err = ctx.Tx(node, pkt, nice, fileSize, minSize, reader, dstPath)
359 ctx.LogI("tx", les, "sent")
361 ctx.LogE("tx", les, err, "sent")
367 metaPkt := ChunkedMeta{
369 FileSize: uint64(fileSize),
370 ChunkSize: uint64(chunkSize),
371 Checksums: make([][32]byte, 0, (fileSize/chunkSize)+1),
373 for i := int64(0); i < (fileSize/chunkSize)+1; i++ {
375 metaPkt.Checksums = append(metaPkt.Checksums, *hsh)
383 if leftSize <= chunkSize {
384 sizeToSend = leftSize
386 sizeToSend = chunkSize
388 path = dstPath + ChunkedSuffixPart + strconv.Itoa(chunkNum)
389 pkt, err = NewPkt(PktTypeFile, nice, []byte(path))
393 hsh, err = blake2b.New256(nil)
403 io.TeeReader(reader, hsh),
412 {"Size", sizeToSend},
415 ctx.LogI("tx", les, "sent")
417 ctx.LogE("tx", les, err, "sent")
420 hsh.Sum(metaPkt.Checksums[chunkNum][:0])
421 leftSize -= sizeToSend
427 var metaBuf bytes.Buffer
428 _, err = xdr.Marshal(&metaBuf, metaPkt)
432 path = dstPath + ChunkedSuffixMeta
433 pkt, err = NewPkt(PktTypeFile, nice, []byte(path))
437 metaPktSize := int64(metaBuf.Len())
438 _, err = ctx.Tx(node, pkt, nice, metaPktSize, minSize, &metaBuf, path)
445 {"Size", metaPktSize},
448 ctx.LogI("tx", les, "sent")
450 ctx.LogE("tx", les, err, "sent")
455 func (ctx *Ctx) TxFreq(
457 nice, replyNice uint8,
458 srcPath, dstPath string,
459 minSize int64) error {
460 dstPath = filepath.Clean(dstPath)
461 if filepath.IsAbs(dstPath) {
462 return errors.New("Relative destination path required")
464 srcPath = filepath.Clean(srcPath)
465 if filepath.IsAbs(srcPath) {
466 return errors.New("Relative source path required")
468 pkt, err := NewPkt(PktTypeFreq, replyNice, []byte(srcPath))
472 src := strings.NewReader(dstPath)
473 size := int64(src.Len())
474 _, err = ctx.Tx(node, pkt, nice, size, minSize, src, srcPath)
479 {"ReplyNice", int(replyNice)},
484 ctx.LogI("tx", les, "sent")
486 ctx.LogE("tx", les, err, "sent")
491 func (ctx *Ctx) TxExec(
493 nice, replyNice uint8,
501 path := make([][]byte, 0, 1+len(args))
502 path = append(path, []byte(handle))
503 for _, arg := range args {
504 path = append(path, []byte(arg))
506 pktType := PktTypeExec
508 pktType = PktTypeExecFat
510 pkt, err := NewPkt(pktType, replyNice, bytes.Join(path, []byte{0}))
516 if !noCompress && !useTmp {
517 var compressed bytes.Buffer
518 compressor, err := zstd.NewWriter(
520 zstd.WithEncoderLevel(zstd.SpeedDefault),
525 if _, err = io.Copy(compressor, in); err != nil {
526 compressor.Close() // #nosec G104
529 if err = compressor.Close(); err != nil {
532 size = int64(compressed.Len())
533 _, err = ctx.Tx(node, pkt, nice, size, minSize, &compressed, handle)
535 if noCompress && !useTmp {
536 var data bytes.Buffer
537 if _, err = io.Copy(&data, in); err != nil {
540 size = int64(data.Len())
541 _, err = ctx.Tx(node, pkt, nice, size, minSize, &data, handle)
543 if !noCompress && useTmp {
545 compressor, err := zstd.NewWriter(w, zstd.WithEncoderLevel(zstd.SpeedDefault))
549 copyErr := make(chan error)
551 _, err := io.Copy(compressor, in)
553 compressor.Close() // #nosec G104
556 err = compressor.Close()
560 tmpReader, closer, fileSize, err := throughTmpFile(r)
572 _, err = ctx.Tx(node, pkt, nice, size, minSize, tmpReader, handle)
574 if noCompress && useTmp {
575 tmpReader, closer, fileSize, err := throughTmpFile(in)
583 _, err = ctx.Tx(node, pkt, nice, size, minSize, tmpReader, handle)
590 {"ReplyNice", int(replyNice)},
591 {"Dst", strings.Join(append([]string{handle}, args...), " ")},
595 ctx.LogI("tx", les, "sent")
597 ctx.LogE("tx", les, err, "sent")
602 func (ctx *Ctx) TxTrns(node *Node, nice uint8, size int64, src io.Reader) error {
609 ctx.LogD("tx", les, "taken")
610 if !ctx.IsEnoughSpace(size) {
611 err := errors.New("is not enough space")
612 ctx.LogE("tx", les, err, err.Error())
615 tmp, err := ctx.NewTmpFileWHash()
619 if _, err = CopyProgressed(
620 tmp.W, src, "Tx trns",
621 LEs{{"Pkt", node.Id.String()}, {"FullSize", size}},
626 nodePath := filepath.Join(ctx.Spool, node.Id.String())
627 err = tmp.Commit(filepath.Join(nodePath, string(TTx)))
629 ctx.LogI("tx", les, "sent")
631 ctx.LogI("tx", append(les, LE{"Err", err}), "sent")
633 os.Symlink(nodePath, filepath.Join(ctx.Spool, node.Name)) // #nosec G104