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/>.
37 xdr "github.com/davecgh/go-xdr/xdr2"
38 "github.com/dustin/go-humanize"
39 "github.com/klauspost/compress/zstd"
40 "golang.org/x/crypto/blake2b"
41 "golang.org/x/crypto/poly1305"
48 func newNotification(fromTo *FromToJSON, subject string, body []byte) io.Reader {
50 "From: " + fromTo.From,
52 "Subject: " + mime.BEncoding.Encode("UTF-8", subject),
55 lines = append(lines, []string{
57 "Content-Type: text/plain; charset=utf-8",
58 "Content-Transfer-Encoding: base64",
60 base64.StdEncoding.EncodeToString(body),
63 return strings.NewReader(strings.Join(lines, "\n"))
69 dryRun, doSeen, noFile, noFreq, noExec, noTrns bool,
71 dirLock, err := ctx.LockDir(nodeId, "toss")
73 ctx.LogE("rx", SDS{}, err, "lock")
76 defer ctx.UnlockDir(dirLock)
78 sendmail := ctx.Neigh[*ctx.SelfId].Exec["sendmail"]
79 decompressor, err := zstd.NewReader(nil)
83 defer decompressor.Close()
84 for job := range ctx.Jobs(nodeId, TRx) {
85 pktName := filepath.Base(job.Fd.Name())
86 sds := SDS{"node": job.PktEnc.Sender, "pkt": pktName}
87 if job.PktEnc.Nice > nice {
88 ctx.LogD("rx", SdsAdd(sds, SDS{"nice": int(job.PktEnc.Nice)}), "too nice")
91 pipeR, pipeW := io.Pipe()
92 go func(job Job) error {
93 pipeWB := bufio.NewWriter(pipeW)
94 _, _, err := PktEncRead(
97 bufio.NewReader(job.Fd),
100 job.Fd.Close() // #nosec G104
102 ctx.LogE("rx", sds, err, "decryption")
103 return pipeW.CloseWithError(err)
105 if err = pipeWB.Flush(); err != nil {
106 ctx.LogE("rx", sds, err, "decryption flush")
107 return pipeW.CloseWithError(err)
114 var pktSizeBlocks int64
115 if _, err = xdr.Unmarshal(pipeR, &pkt); err != nil {
116 ctx.LogE("rx", sds, err, "unmarshal")
120 pktSize = job.Size - PktEncOverhead - PktOverhead - PktSizeOverhead
121 pktSizeBlocks = pktSize / (EncBlkSize + poly1305.TagSize)
122 if pktSize%(EncBlkSize+poly1305.TagSize) != 0 {
123 pktSize -= poly1305.TagSize
125 pktSize -= pktSizeBlocks * poly1305.TagSize
126 sds["size"] = pktSize
127 ctx.LogD("rx", sds, "taken")
133 path := bytes.Split(pkt.Path[:int(pkt.PathLen)], []byte{0})
134 handle := string(path[0])
135 args := make([]string, 0, len(path)-1)
136 for _, p := range path[1:] {
137 args = append(args, string(p))
139 argsStr := strings.Join(append([]string{handle}, args...), " ")
140 sds := SdsAdd(sds, SDS{
144 sender := ctx.Neigh[*job.PktEnc.Sender]
145 cmdline, exists := sender.Exec[handle]
146 if !exists || len(cmdline) == 0 {
147 ctx.LogE("rx", sds, errors.New("No handle found"), "")
151 if err = decompressor.Reset(pipeR); err != nil {
157 append(cmdline[1:len(cmdline)], args...)...,
161 "NNCP_SELF="+ctx.Self.Id.String(),
162 "NNCP_SENDER="+sender.Id.String(),
163 "NNCP_NICE="+strconv.Itoa(int(pkt.Nice)),
165 cmd.Stdin = decompressor
166 output, err := cmd.Output()
168 ctx.LogE("rx", sds, err, "handle")
172 if len(sendmail) > 0 && ctx.NotifyExec != nil {
173 notify, exists := ctx.NotifyExec[sender.Name+"."+handle]
175 notify, exists = ctx.NotifyExec["*."+handle]
180 append(sendmail[1:len(sendmail)], notify.To)...,
182 cmd.Stdin = newNotification(notify, fmt.Sprintf(
183 "Exec from %s: %s", sender.Name, argsStr,
185 if err = cmd.Run(); err != nil {
186 ctx.LogE("rx", sds, err, "notify")
191 ctx.LogI("rx", sds, "")
194 if fd, err := os.Create(job.Fd.Name() + SeenSuffix); err == nil {
195 fd.Close() // #nosec G104
198 if err = os.Remove(job.Fd.Name()); err != nil {
199 ctx.LogE("rx", sds, err, "remove")
207 dst := string(pkt.Path[:int(pkt.PathLen)])
208 sds := SdsAdd(sds, SDS{"type": "file", "dst": dst})
209 if filepath.IsAbs(dst) {
210 ctx.LogE("rx", sds, errors.New("non-relative destination path"), "")
214 incoming := ctx.Neigh[*job.PktEnc.Sender].Incoming
216 ctx.LogE("rx", sds, errors.New("incoming is not allowed"), "")
220 dir := filepath.Join(*incoming, path.Dir(dst))
221 if err = os.MkdirAll(dir, os.FileMode(0777)); err != nil {
222 ctx.LogE("rx", sds, err, "mkdir")
227 tmp, err := TempFile(dir, "file")
229 ctx.LogE("rx", sds, err, "mktemp")
233 sds["tmp"] = tmp.Name()
234 ctx.LogD("rx", sds, "created")
235 bufW := bufio.NewWriter(tmp)
236 if _, err = CopyProgressed(
237 bufW, pipeR, "Rx file",
238 SdsAdd(sds, SDS{"fullsize": sds["size"]}),
241 ctx.LogE("rx", sds, err, "copy")
245 if err = bufW.Flush(); err != nil {
246 tmp.Close() // #nosec G104
247 ctx.LogE("rx", sds, err, "copy")
251 if err = tmp.Sync(); err != nil {
252 tmp.Close() // #nosec G104
253 ctx.LogE("rx", sds, err, "copy")
257 if err = tmp.Close(); err != nil {
258 ctx.LogE("rx", sds, err, "copy")
262 dstPathOrig := filepath.Join(*incoming, dst)
263 dstPath := dstPathOrig
266 if _, err = os.Stat(dstPath); err != nil {
267 if os.IsNotExist(err) {
270 ctx.LogE("rx", sds, err, "stat")
274 dstPath = dstPathOrig + "." + strconv.Itoa(dstPathCtr)
277 if err = os.Rename(tmp.Name(), dstPath); err != nil {
278 ctx.LogE("rx", sds, err, "rename")
281 if err = DirSync(*incoming); err != nil {
282 ctx.LogE("rx", sds, err, "sync")
287 ctx.LogI("rx", sds, "")
290 if fd, err := os.Create(job.Fd.Name() + SeenSuffix); err == nil {
291 fd.Close() // #nosec G104
294 if err = os.Remove(job.Fd.Name()); err != nil {
295 ctx.LogE("rx", sds, err, "remove")
298 if len(sendmail) > 0 && ctx.NotifyFile != nil {
301 append(sendmail[1:len(sendmail)], ctx.NotifyFile.To)...,
303 cmd.Stdin = newNotification(ctx.NotifyFile, fmt.Sprintf(
304 "File from %s: %s (%s)",
305 ctx.Neigh[*job.PktEnc.Sender].Name,
307 humanize.IBytes(uint64(pktSize)),
309 if err = cmd.Run(); err != nil {
310 ctx.LogE("rx", sds, err, "notify")
318 src := string(pkt.Path[:int(pkt.PathLen)])
319 if filepath.IsAbs(src) {
320 ctx.LogE("rx", sds, errors.New("non-relative source path"), "")
324 sds := SdsAdd(sds, SDS{"type": "freq", "src": src})
325 dstRaw, err := ioutil.ReadAll(pipeR)
327 ctx.LogE("rx", sds, err, "read")
331 dst := string(dstRaw)
333 sender := ctx.Neigh[*job.PktEnc.Sender]
334 freqPath := sender.FreqPath
336 ctx.LogE("rx", sds, errors.New("freqing is not allowed"), "")
344 filepath.Join(*freqPath, src),
351 ctx.LogE("rx", sds, err, "tx file")
356 ctx.LogI("rx", sds, "")
359 if fd, err := os.Create(job.Fd.Name() + SeenSuffix); err == nil {
360 fd.Close() // #nosec G104
363 if err = os.Remove(job.Fd.Name()); err != nil {
364 ctx.LogE("rx", sds, err, "remove")
367 if len(sendmail) > 0 && ctx.NotifyFreq != nil {
370 append(sendmail[1:len(sendmail)], ctx.NotifyFreq.To)...,
372 cmd.Stdin = newNotification(ctx.NotifyFreq, fmt.Sprintf(
373 "Freq from %s: %s", sender.Name, src,
375 if err = cmd.Run(); err != nil {
376 ctx.LogE("rx", sds, err, "notify")
384 dst := new([blake2b.Size256]byte)
385 copy(dst[:], pkt.Path[:int(pkt.PathLen)])
386 nodeId := NodeId(*dst)
387 node, known := ctx.Neigh[nodeId]
388 sds := SdsAdd(sds, SDS{"type": "trns", "dst": nodeId})
390 ctx.LogE("rx", sds, errors.New("unknown node"), "")
394 ctx.LogD("rx", sds, "taken")
396 if err = ctx.TxTrns(node, job.PktEnc.Nice, pktSize, pipeR); err != nil {
397 ctx.LogE("rx", sds, err, "tx trns")
402 ctx.LogI("rx", sds, "")
405 if fd, err := os.Create(job.Fd.Name() + SeenSuffix); err == nil {
406 fd.Close() // #nosec G104
409 if err = os.Remove(job.Fd.Name()); err != nil {
410 ctx.LogE("rx", sds, err, "remove")
415 ctx.LogE("rx", sds, errors.New("unknown type"), "")
419 pipeR.Close() // #nosec G104