2 NNCP -- Node to Node copy, utilities for store-and-forward data exchange
3 Copyright (C) 2016-2019 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"
55 hops := make([]*Node, 0, 1+len(node.Via))
56 hops = append(hops, node)
58 for i := len(node.Via); i > 0; i-- {
59 lastNode = ctx.Neigh[*node.Via[i-1]]
60 hops = append(hops, lastNode)
63 for i := 0; i < len(hops); i++ {
64 expectedSize = PktEncOverhead + PktSizeOverhead + sizeWithTags(PktOverhead+expectedSize)
66 padSize := minSize - expectedSize
70 if !ctx.IsEnoughSpace(size + padSize) {
71 return nil, errors.New("is not enough space")
73 tmp, err := ctx.NewTmpFileWHash()
78 errs := make(chan error)
80 pipeR, pipeW := io.Pipe()
81 go func(size int64, src io.Reader, dst io.WriteCloser) {
84 "nice": strconv.Itoa(int(nice)),
85 "size": strconv.FormatInt(size, 10),
87 errs <- PktEncWrite(ctx.Self, hops[0], pkt, nice, size, padSize, src, dst)
89 }(curSize, src, pipeW)
90 curSize = PktEncOverhead + PktSizeOverhead + sizeWithTags(PktOverhead+curSize) + padSize
92 var pipeRPrev io.Reader
93 for i := 1; i < len(hops); i++ {
94 pktTrns, _ := NewPkt(PktTypeTrns, 0, hops[i-1].Id[:])
96 pipeR, pipeW = io.Pipe()
97 go func(node *Node, pkt *Pkt, size int64, src io.Reader, dst io.WriteCloser) {
100 "nice": strconv.Itoa(int(nice)),
101 "size": strconv.FormatInt(size, 10),
103 errs <- PktEncWrite(ctx.Self, node, pkt, nice, size, 0, src, dst)
105 }(hops[i], pktTrns, curSize, pipeRPrev, pipeW)
106 curSize = PktEncOverhead + PktSizeOverhead + sizeWithTags(PktOverhead+curSize)
109 _, err := io.Copy(tmp.W, pipeR)
112 for i := 0; i <= len(hops); i++ {
119 nodePath := filepath.Join(ctx.Spool, lastNode.Id.String())
120 err = tmp.Commit(filepath.Join(nodePath, string(TTx)))
121 os.Symlink(nodePath, filepath.Join(ctx.Spool, lastNode.Name))
125 type DummyCloser struct{}
127 func (dc DummyCloser) Close() error { return nil }
129 func prepareTxFile(srcPath string) (reader io.Reader, closer io.Closer, fileSize int64, archived bool, rerr error) {
131 // Read content from stdin, saving to temporary file, encrypting
133 src, err := ioutil.TempFile("", "nncp-file")
138 os.Remove(src.Name())
139 tmpW := bufio.NewWriter(src)
140 tmpKey := make([]byte, chacha20poly1305.KeySize)
141 if _, rerr = rand.Read(tmpKey[:]); rerr != nil {
144 aead, err := chacha20poly1305.New(tmpKey)
149 nonce := make([]byte, aead.NonceSize())
150 written, err := aeadProcess(aead, nonce, true, bufio.NewReader(os.Stdin), tmpW)
155 fileSize = int64(written)
156 if err = tmpW.Flush(); err != nil {
159 src.Seek(0, io.SeekStart)
162 if _, err := aeadProcess(aead, nonce, false, bufio.NewReader(src), w); err != nil {
163 w.CloseWithError(err)
171 srcStat, err := os.Stat(srcPath)
176 mode := srcStat.Mode()
178 if mode.IsRegular() {
179 // It is regular file, just send it
180 src, err := os.Open(srcPath)
185 fileSize = srcStat.Size()
186 reader = bufio.NewReader(src)
192 rerr = errors.New("unsupported file type")
196 // It is directory, create PAX archive with its contents
198 basePath := filepath.Base(srcPath)
199 rootPath, err := filepath.Abs(srcPath)
209 dirs := make([]einfo, 0, 1<<10)
210 files := make([]einfo, 0, 1<<10)
211 rerr = filepath.Walk(rootPath, func(path string, info os.FileInfo, err error) error {
216 // directory header, PAX record header+contents
217 fileSize += TarBlockSize + 2*TarBlockSize
218 dirs = append(dirs, einfo{path: path, modTime: info.ModTime()})
220 // file header, PAX record header+contents, file content
221 fileSize += TarBlockSize + 2*TarBlockSize + info.Size()
222 if n := info.Size() % TarBlockSize; n != 0 {
223 fileSize += TarBlockSize - n // padding
225 files = append(files, einfo{
227 modTime: info.ModTime(),
239 closer = DummyCloser{}
240 fileSize += 2 * TarBlockSize // termination block
243 tarWr := tar.NewWriter(w)
245 Typeflag: tar.TypeDir,
247 PAXRecords: map[string]string{
248 "comment": "Autogenerated by " + VersionGet(),
250 Format: tar.FormatPAX,
252 for _, e := range dirs {
253 hdr.Name = basePath + e.path[len(rootPath):]
254 hdr.ModTime = e.modTime
255 if err = tarWr.WriteHeader(&hdr); err != nil {
256 w.CloseWithError(err)
259 hdr.Typeflag = tar.TypeReg
261 for _, e := range files {
262 hdr.Name = basePath + e.path[len(rootPath):]
263 hdr.ModTime = e.modTime
265 if err = tarWr.WriteHeader(&hdr); err != nil {
266 w.CloseWithError(err)
268 fd, err := os.Open(e.path)
270 w.CloseWithError(err)
272 _, err = io.Copy(tarWr, bufio.NewReader(fd))
274 w.CloseWithError(err)
284 func (ctx *Ctx) TxFile(
287 srcPath, dstPath string,
289 minSize, maxSize int64,
291 dstPathSpecified := false
294 return errors.New("Must provide destination filename")
296 dstPath = filepath.Base(srcPath)
298 dstPathSpecified = true
300 dstPath = filepath.Clean(dstPath)
301 if filepath.IsAbs(dstPath) {
302 return errors.New("Relative destination path required")
304 reader, closer, fileSize, archived, err := prepareTxFile(srcPath)
311 if fileSize > maxSize {
312 return errors.New("Too big than allowed")
314 if archived && !dstPathSpecified {
318 if fileSize <= chunkSize {
319 pkt, err := NewPkt(PktTypeFile, nice, []byte(dstPath))
323 _, err = ctx.Tx(node, pkt, nice, fileSize, minSize, reader)
327 "nice": strconv.Itoa(int(nice)),
330 "size": strconv.FormatInt(fileSize, 10),
333 ctx.LogI("tx", sds, "sent")
335 ctx.LogE("tx", SdsAdd(sds, SDS{"err": err}), "sent")
341 metaPkt := ChunkedMeta{
343 FileSize: uint64(fileSize),
344 ChunkSize: uint64(chunkSize),
345 Checksums: make([][32]byte, 0, (fileSize/chunkSize)+1),
347 for i := int64(0); i < (fileSize/chunkSize)+1; i++ {
349 metaPkt.Checksums = append(metaPkt.Checksums, *hsh)
357 if leftSize <= chunkSize {
358 sizeToSend = leftSize
360 sizeToSend = chunkSize
362 path = dstPath + ChunkedSuffixPart + strconv.Itoa(chunkNum)
363 pkt, err = NewPkt(PktTypeFile, nice, []byte(path))
367 hsh, err = blake2b.New256(nil)
377 io.TeeReader(reader, hsh),
382 "nice": strconv.Itoa(int(nice)),
385 "size": strconv.FormatInt(sizeToSend, 10),
388 ctx.LogI("tx", sds, "sent")
390 ctx.LogE("tx", SdsAdd(sds, SDS{"err": err}), "sent")
393 hsh.Sum(metaPkt.Checksums[chunkNum][:0])
394 leftSize -= sizeToSend
400 var metaBuf bytes.Buffer
401 _, err = xdr.Marshal(&metaBuf, metaPkt)
405 path = dstPath + ChunkedSuffixMeta
406 pkt, err = NewPkt(PktTypeFile, nice, []byte(path))
410 metaPktSize := int64(metaBuf.Len())
411 _, err = ctx.Tx(node, pkt, nice, metaPktSize, minSize, &metaBuf)
415 "nice": strconv.Itoa(int(nice)),
418 "size": strconv.FormatInt(metaPktSize, 10),
421 ctx.LogI("tx", sds, "sent")
423 ctx.LogE("tx", SdsAdd(sds, SDS{"err": err}), "sent")
428 func (ctx *Ctx) TxFreq(
430 nice, replyNice uint8,
431 srcPath, dstPath string,
432 minSize int64) error {
433 dstPath = filepath.Clean(dstPath)
434 if filepath.IsAbs(dstPath) {
435 return errors.New("Relative destination path required")
437 srcPath = filepath.Clean(srcPath)
438 if filepath.IsAbs(srcPath) {
439 return errors.New("Relative source path required")
441 pkt, err := NewPkt(PktTypeFreq, replyNice, []byte(srcPath))
445 src := strings.NewReader(dstPath)
446 size := int64(src.Len())
447 _, err = ctx.Tx(node, pkt, nice, size, minSize, src)
451 "nice": strconv.Itoa(int(nice)),
452 "replynice": strconv.Itoa(int(replyNice)),
457 ctx.LogI("tx", sds, "sent")
459 ctx.LogE("tx", SdsAdd(sds, SDS{"err": err}), "sent")
464 func (ctx *Ctx) TxExec(
466 nice, replyNice uint8,
472 path := make([][]byte, 0, 1+len(args))
473 path = append(path, []byte(handle))
474 for _, arg := range args {
475 path = append(path, []byte(arg))
477 pkt, err := NewPkt(PktTypeExec, replyNice, bytes.Join(path, []byte{0}))
481 var compressed bytes.Buffer
482 compressor, err := zstd.NewWriter(
484 zstd.WithEncoderLevel(zstd.SpeedDefault),
489 _, err = io.Copy(compressor, in)
494 size := int64(compressed.Len())
495 _, err = ctx.Tx(node, pkt, nice, size, minSize, &compressed)
499 "nice": strconv.Itoa(int(nice)),
500 "replynice": strconv.Itoa(int(replyNice)),
501 "dst": strings.Join(append([]string{handle}, args...), " "),
502 "size": strconv.FormatInt(size, 10),
505 ctx.LogI("tx", sds, "sent")
507 ctx.LogE("tx", SdsAdd(sds, SDS{"err": err}), "sent")
512 func (ctx *Ctx) TxTrns(node *Node, nice uint8, size int64, src io.Reader) error {
516 "nice": strconv.Itoa(int(nice)),
517 "size": strconv.FormatInt(size, 10),
519 ctx.LogD("tx", sds, "taken")
520 if !ctx.IsEnoughSpace(size) {
521 err := errors.New("is not enough space")
522 ctx.LogE("tx", SdsAdd(sds, SDS{"err": err}), err.Error())
525 tmp, err := ctx.NewTmpFileWHash()
529 if _, err = io.Copy(tmp.W, src); err != nil {
532 nodePath := filepath.Join(ctx.Spool, node.Id.String())
533 err = tmp.Commit(filepath.Join(nodePath, string(TTx)))
535 ctx.LogI("tx", sds, "sent")
537 ctx.LogI("tx", SdsAdd(sds, SDS{"err": err}), "sent")
539 os.Symlink(nodePath, filepath.Join(ctx.Spool, node.Name))