2 NNCP -- Node to Node copy, utilities for store-and-forward data exchange
3 Copyright (C) 2016-2020 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)
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)
106 }(hops[i], pktTrns, curSize, pipeRPrev, pipeW)
107 curSize = PktEncOverhead + PktSizeOverhead + sizeWithTags(PktOverhead+curSize)
110 _, err := CopyProgressed(
112 SDS{"pkt": pktName, "fullsize": curSize},
117 for i := 0; i <= len(hops); i++ {
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))
130 type DummyCloser struct{}
132 func (dc DummyCloser) Close() error { return nil }
134 func prepareTxFile(srcPath string) (reader io.Reader, closer io.Closer, fileSize int64, archived bool, rerr error) {
136 // Read content from stdin, saving to temporary file, encrypting
138 src, err := ioutil.TempFile("", "nncp-file")
143 os.Remove(src.Name())
144 tmpW := bufio.NewWriter(src)
145 tmpKey := make([]byte, chacha20poly1305.KeySize)
146 if _, rerr = rand.Read(tmpKey[:]); rerr != nil {
149 aead, err := chacha20poly1305.New(tmpKey)
154 nonce := make([]byte, aead.NonceSize())
155 written, err := aeadProcess(aead, nonce, true, bufio.NewReader(os.Stdin), tmpW)
160 fileSize = int64(written)
161 if err = tmpW.Flush(); err != nil {
164 src.Seek(0, io.SeekStart)
167 if _, err := aeadProcess(aead, nonce, false, bufio.NewReader(src), w); err != nil {
168 w.CloseWithError(err)
176 srcStat, err := os.Stat(srcPath)
181 mode := srcStat.Mode()
183 if mode.IsRegular() {
184 // It is regular file, just send it
185 src, err := os.Open(srcPath)
190 fileSize = srcStat.Size()
191 reader = bufio.NewReader(src)
197 rerr = errors.New("unsupported file type")
201 // It is directory, create PAX archive with its contents
203 basePath := filepath.Base(srcPath)
204 rootPath, err := filepath.Abs(srcPath)
214 dirs := make([]einfo, 0, 1<<10)
215 files := make([]einfo, 0, 1<<10)
216 rerr = filepath.Walk(rootPath, func(path string, info os.FileInfo, err error) error {
221 // directory header, PAX record header+contents
222 fileSize += TarBlockSize + 2*TarBlockSize
223 dirs = append(dirs, einfo{path: path, modTime: info.ModTime()})
225 // file header, PAX record header+contents, file content
226 fileSize += TarBlockSize + 2*TarBlockSize + info.Size()
227 if n := info.Size() % TarBlockSize; n != 0 {
228 fileSize += TarBlockSize - n // padding
230 files = append(files, einfo{
232 modTime: info.ModTime(),
244 closer = DummyCloser{}
245 fileSize += 2 * TarBlockSize // termination block
248 tarWr := tar.NewWriter(w)
250 Typeflag: tar.TypeDir,
252 PAXRecords: map[string]string{
253 "comment": "Autogenerated by " + VersionGet(),
255 Format: tar.FormatPAX,
257 for _, e := range dirs {
258 hdr.Name = basePath + e.path[len(rootPath):]
259 hdr.ModTime = e.modTime
260 if err = tarWr.WriteHeader(&hdr); err != nil {
261 w.CloseWithError(err)
264 hdr.Typeflag = tar.TypeReg
266 for _, e := range files {
267 hdr.Name = basePath + e.path[len(rootPath):]
268 hdr.ModTime = e.modTime
270 if err = tarWr.WriteHeader(&hdr); err != nil {
271 w.CloseWithError(err)
273 fd, err := os.Open(e.path)
275 w.CloseWithError(err)
277 _, err = io.Copy(tarWr, bufio.NewReader(fd))
279 w.CloseWithError(err)
289 func (ctx *Ctx) TxFile(
292 srcPath, dstPath string,
294 minSize, maxSize int64,
296 dstPathSpecified := false
299 return errors.New("Must provide destination filename")
301 dstPath = filepath.Base(srcPath)
303 dstPathSpecified = true
305 dstPath = filepath.Clean(dstPath)
306 if filepath.IsAbs(dstPath) {
307 return errors.New("Relative destination path required")
309 reader, closer, fileSize, archived, err := prepareTxFile(srcPath)
316 if fileSize > maxSize {
317 return errors.New("Too big than allowed")
319 if archived && !dstPathSpecified {
323 if fileSize <= chunkSize {
324 pkt, err := NewPkt(PktTypeFile, nice, []byte(dstPath))
328 _, err = ctx.Tx(node, pkt, nice, fileSize, minSize, reader, dstPath)
338 ctx.LogI("tx", sds, "sent")
340 ctx.LogE("tx", sds, err, "sent")
346 metaPkt := ChunkedMeta{
348 FileSize: uint64(fileSize),
349 ChunkSize: uint64(chunkSize),
350 Checksums: make([][32]byte, 0, (fileSize/chunkSize)+1),
352 for i := int64(0); i < (fileSize/chunkSize)+1; i++ {
354 metaPkt.Checksums = append(metaPkt.Checksums, *hsh)
362 if leftSize <= chunkSize {
363 sizeToSend = leftSize
365 sizeToSend = chunkSize
367 path = dstPath + ChunkedSuffixPart + strconv.Itoa(chunkNum)
368 pkt, err = NewPkt(PktTypeFile, nice, []byte(path))
372 hsh, err = blake2b.New256(nil)
382 io.TeeReader(reader, hsh),
394 ctx.LogI("tx", sds, "sent")
396 ctx.LogE("tx", sds, err, "sent")
399 hsh.Sum(metaPkt.Checksums[chunkNum][:0])
400 leftSize -= sizeToSend
406 var metaBuf bytes.Buffer
407 _, err = xdr.Marshal(&metaBuf, metaPkt)
411 path = dstPath + ChunkedSuffixMeta
412 pkt, err = NewPkt(PktTypeFile, nice, []byte(path))
416 metaPktSize := int64(metaBuf.Len())
417 _, err = ctx.Tx(node, pkt, nice, metaPktSize, minSize, &metaBuf, path)
427 ctx.LogI("tx", sds, "sent")
429 ctx.LogE("tx", sds, err, "sent")
434 func (ctx *Ctx) TxFreq(
436 nice, replyNice uint8,
437 srcPath, dstPath string,
438 minSize int64) error {
439 dstPath = filepath.Clean(dstPath)
440 if filepath.IsAbs(dstPath) {
441 return errors.New("Relative destination path required")
443 srcPath = filepath.Clean(srcPath)
444 if filepath.IsAbs(srcPath) {
445 return errors.New("Relative source path required")
447 pkt, err := NewPkt(PktTypeFreq, replyNice, []byte(srcPath))
451 src := strings.NewReader(dstPath)
452 size := int64(src.Len())
453 _, err = ctx.Tx(node, pkt, nice, size, minSize, src, srcPath)
458 "replynice": int(replyNice),
463 ctx.LogI("tx", sds, "sent")
465 ctx.LogE("tx", sds, err, "sent")
470 func (ctx *Ctx) TxExec(
472 nice, replyNice uint8,
478 path := make([][]byte, 0, 1+len(args))
479 path = append(path, []byte(handle))
480 for _, arg := range args {
481 path = append(path, []byte(arg))
483 pkt, err := NewPkt(PktTypeExec, replyNice, bytes.Join(path, []byte{0}))
487 var compressed bytes.Buffer
488 compressor, err := zstd.NewWriter(
490 zstd.WithEncoderLevel(zstd.SpeedDefault),
495 _, err = io.Copy(compressor, in)
500 size := int64(compressed.Len())
501 _, err = ctx.Tx(node, pkt, nice, size, minSize, &compressed, handle)
506 "replynice": int(replyNice),
507 "dst": strings.Join(append([]string{handle}, args...), " "),
511 ctx.LogI("tx", sds, "sent")
513 ctx.LogE("tx", sds, err, "sent")
518 func (ctx *Ctx) TxTrns(node *Node, nice uint8, size int64, src io.Reader) error {
525 ctx.LogD("tx", sds, "taken")
526 if !ctx.IsEnoughSpace(size) {
527 err := errors.New("is not enough space")
528 ctx.LogE("tx", sds, err, err.Error())
531 tmp, err := ctx.NewTmpFileWHash()
535 if _, err = CopyProgressed(
536 tmp.W, src, "Tx trns",
537 SDS{"pkt": node.Id.String(), "fullsize": size},
542 nodePath := filepath.Join(ctx.Spool, node.Id.String())
543 err = tmp.Commit(filepath.Join(nodePath, string(TTx)))
545 ctx.LogI("tx", sds, "sent")
547 ctx.LogI("tx", SdsAdd(sds, SDS{"err": err}), "sent")
549 os.Symlink(nodePath, filepath.Join(ctx.Spool, node.Name))