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,
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 archived && !dstPathSpecified {
315 if fileSize <= chunkSize {
316 pkt, err := NewPkt(PktTypeFile, nice, []byte(dstPath))
320 _, err = ctx.Tx(node, pkt, nice, fileSize, minSize, reader)
324 "nice": strconv.Itoa(int(nice)),
327 "size": strconv.FormatInt(fileSize, 10),
330 ctx.LogI("tx", sds, "sent")
332 ctx.LogE("tx", SdsAdd(sds, SDS{"err": err}), "sent")
338 metaPkt := ChunkedMeta{
340 FileSize: uint64(fileSize),
341 ChunkSize: uint64(chunkSize),
342 Checksums: make([][32]byte, 0, (fileSize/chunkSize)+1),
344 for i := int64(0); i < (fileSize/chunkSize)+1; i++ {
346 metaPkt.Checksums = append(metaPkt.Checksums, *hsh)
354 if leftSize <= chunkSize {
355 sizeToSend = leftSize
357 sizeToSend = chunkSize
359 path = dstPath + ChunkedSuffixPart + strconv.Itoa(chunkNum)
360 pkt, err = NewPkt(PktTypeFile, nice, []byte(path))
364 hsh, err = blake2b.New256(nil)
374 io.TeeReader(reader, hsh),
379 "nice": strconv.Itoa(int(nice)),
382 "size": strconv.FormatInt(sizeToSend, 10),
385 ctx.LogI("tx", sds, "sent")
387 ctx.LogE("tx", SdsAdd(sds, SDS{"err": err}), "sent")
390 hsh.Sum(metaPkt.Checksums[chunkNum][:0])
391 leftSize -= sizeToSend
397 var metaBuf bytes.Buffer
398 _, err = xdr.Marshal(&metaBuf, metaPkt)
402 path = dstPath + ChunkedSuffixMeta
403 pkt, err = NewPkt(PktTypeFile, nice, []byte(path))
407 metaPktSize := int64(metaBuf.Len())
408 _, err = ctx.Tx(node, pkt, nice, metaPktSize, minSize, &metaBuf)
412 "nice": strconv.Itoa(int(nice)),
415 "size": strconv.FormatInt(metaPktSize, 10),
418 ctx.LogI("tx", sds, "sent")
420 ctx.LogE("tx", SdsAdd(sds, SDS{"err": err}), "sent")
425 func (ctx *Ctx) TxFreq(
427 nice, replyNice uint8,
428 srcPath, dstPath string,
429 minSize int64) error {
430 dstPath = filepath.Clean(dstPath)
431 if filepath.IsAbs(dstPath) {
432 return errors.New("Relative destination path required")
434 srcPath = filepath.Clean(srcPath)
435 if filepath.IsAbs(srcPath) {
436 return errors.New("Relative source path required")
438 pkt, err := NewPkt(PktTypeFreq, replyNice, []byte(srcPath))
442 src := strings.NewReader(dstPath)
443 size := int64(src.Len())
444 _, err = ctx.Tx(node, pkt, nice, size, minSize, src)
448 "nice": strconv.Itoa(int(nice)),
449 "replynice": strconv.Itoa(int(replyNice)),
454 ctx.LogI("tx", sds, "sent")
456 ctx.LogE("tx", SdsAdd(sds, SDS{"err": err}), "sent")
461 func (ctx *Ctx) TxExec(
463 nice, replyNice uint8,
469 path := make([][]byte, 0, 1+len(args))
470 path = append(path, []byte(handle))
471 for _, arg := range args {
472 path = append(path, []byte(arg))
474 pkt, err := NewPkt(PktTypeExec, replyNice, bytes.Join(path, []byte{0}))
478 var compressed bytes.Buffer
479 compressor, err := zstd.NewWriter(
481 zstd.WithEncoderLevel(zstd.SpeedDefault),
486 _, err = io.Copy(compressor, in)
491 size := int64(compressed.Len())
492 _, err = ctx.Tx(node, pkt, nice, size, minSize, &compressed)
496 "nice": strconv.Itoa(int(nice)),
497 "replynice": strconv.Itoa(int(replyNice)),
498 "dst": strings.Join(append([]string{handle}, args...), " "),
499 "size": strconv.FormatInt(size, 10),
502 ctx.LogI("tx", sds, "sent")
504 ctx.LogE("tx", SdsAdd(sds, SDS{"err": err}), "sent")
509 func (ctx *Ctx) TxTrns(node *Node, nice uint8, size int64, src io.Reader) error {
513 "nice": strconv.Itoa(int(nice)),
514 "size": strconv.FormatInt(size, 10),
516 ctx.LogD("tx", sds, "taken")
517 if !ctx.IsEnoughSpace(size) {
518 err := errors.New("is not enough space")
519 ctx.LogE("tx", SdsAdd(sds, SDS{"err": err}), err.Error())
522 tmp, err := ctx.NewTmpFileWHash()
526 if _, err = io.Copy(tmp.W, src); err != nil {
529 nodePath := filepath.Join(ctx.Spool, node.Id.String())
530 err = tmp.Commit(filepath.Join(nodePath, string(TTx)))
532 ctx.LogI("tx", sds, "sent")
534 ctx.LogI("tx", SdsAdd(sds, SDS{"err": err}), "sent")
536 os.Symlink(nodePath, filepath.Join(ctx.Spool, node.Name))