]> Cypherpunks.ru repositories - nncp.git/blob - src/cypherpunks.ru/nncp/toss.go
-dryrun for tosser
[nncp.git] / src / cypherpunks.ru / nncp / toss.go
1 /*
2 NNCP -- Node to Node copy, utilities for store-and-forward data exchange
3 Copyright (C) 2016-2017 Sergey Matveev <stargrave@stargrave.org>
4
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, either version 3 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program.  If not, see <http://www.gnu.org/licenses/>.
17 */
18
19 package nncp
20
21 import (
22         "bufio"
23         "compress/zlib"
24         "fmt"
25         "io"
26         "io/ioutil"
27         "log"
28         "mime"
29         "os"
30         "os/exec"
31         "path"
32         "path/filepath"
33         "strconv"
34         "strings"
35
36         "github.com/davecgh/go-xdr/xdr2"
37         "github.com/dustin/go-humanize"
38         "golang.org/x/crypto/blake2b"
39         "golang.org/x/sys/unix"
40 )
41
42 func newNotification(fromTo *FromToYAML, subject string) io.Reader {
43         return strings.NewReader(fmt.Sprintf(
44                 "From: %s\nTo: %s\nSubject: %s\n",
45                 fromTo.From,
46                 fromTo.To,
47                 mime.BEncoding.Encode("UTF-8", subject),
48         ))
49 }
50
51 func (ctx *Ctx) LockDir(nodeId *NodeId, xx TRxTx) (*os.File, error) {
52         ctx.ensureRxDir(nodeId)
53         lockPath := filepath.Join(ctx.Spool, nodeId.String(), string(xx)) + ".lock"
54         dirLock, err := os.OpenFile(
55                 lockPath,
56                 os.O_CREATE|os.O_WRONLY,
57                 os.FileMode(0600),
58         )
59         if err != nil {
60                 ctx.LogE("lockdir", SDS{"path": lockPath, "err": err}, "")
61                 return nil, err
62         }
63         err = unix.Flock(int(dirLock.Fd()), unix.LOCK_EX|unix.LOCK_NB)
64         if err != nil {
65                 ctx.LogE("lockdir", SDS{"path": lockPath, "err": err}, "")
66                 dirLock.Close()
67                 return nil, err
68         }
69         return dirLock, nil
70 }
71
72 func (ctx *Ctx) UnlockDir(fd *os.File) {
73         if fd != nil {
74                 unix.Flock(int(fd.Fd()), unix.LOCK_UN)
75                 fd.Close()
76         }
77 }
78
79 func (ctx *Ctx) Toss(nodeId *NodeId, nice uint8, dryRun bool) {
80         dirLock, err := ctx.LockDir(nodeId, TRx)
81         if err != nil {
82                 return
83         }
84         defer ctx.UnlockDir(dirLock)
85         for job := range ctx.Jobs(nodeId, TRx) {
86                 pktName := filepath.Base(job.Fd.Name())
87                 sds := SDS{"node": job.PktEnc.Sender, "pkt": pktName}
88                 if job.PktEnc.Nice > nice {
89                         ctx.LogD("rx", SdsAdd(sds, SDS{
90                                 "nice": strconv.Itoa(int(job.PktEnc.Nice)),
91                         }), "too nice")
92                         continue
93                 }
94                 pipeR, pipeW := io.Pipe()
95                 errs := make(chan error, 1)
96                 go func(job Job) {
97                         pipeWB := bufio.NewWriter(pipeW)
98                         _, err := PktEncRead(
99                                 ctx.Self,
100                                 ctx.Neigh,
101                                 bufio.NewReader(job.Fd),
102                                 pipeWB,
103                         )
104                         errs <- err
105                         pipeWB.Flush()
106                         pipeW.Close()
107                         job.Fd.Close()
108                         if err != nil {
109                                 ctx.LogE("rx", SdsAdd(sds, SDS{"err": err}), "decryption")
110                         }
111                 }(job)
112                 var pkt Pkt
113                 var err error
114                 var pktSize int64
115                 if _, err = xdr.Unmarshal(pipeR, &pkt); err != nil {
116                         ctx.LogE("rx", SdsAdd(sds, SDS{"err": err}), "unmarshal")
117                         goto Closing
118                 }
119                 pktSize = job.Size - PktEncOverhead - PktOverhead
120                 sds["size"] = strconv.FormatInt(pktSize, 10)
121                 ctx.LogD("rx", sds, "taken")
122                 switch pkt.Type {
123                 case PktTypeMail:
124                         recipients := string(pkt.Path[:int(pkt.PathLen)])
125                         sds := SdsAdd(sds, SDS{
126                                 "type": "mail",
127                                 "dst":  recipients,
128                         })
129                         decompressor, err := zlib.NewReader(pipeR)
130                         if err != nil {
131                                 log.Fatalln(err)
132                         }
133                         sendmail := ctx.Neigh[*job.PktEnc.Sender].Sendmail
134                         if !dryRun {
135                                 cmd := exec.Command(
136                                         sendmail[0],
137                                         append(
138                                                 sendmail[1:len(sendmail)],
139                                                 strings.Split(recipients, " ")...,
140                                         )...,
141                                 )
142                                 cmd.Stdin = decompressor
143                                 if err = cmd.Run(); err != nil {
144                                         ctx.LogE("rx", SdsAdd(sds, SDS{"err": err}), "sendmail")
145                                         goto Closing
146                                 }
147                         }
148                         ctx.LogI("rx", sds, "")
149                         if !dryRun {
150                                 if err = os.Remove(job.Fd.Name()); err != nil {
151                                         ctx.LogE("rx", SdsAdd(sds, SDS{"err": err}), "remove")
152                                 }
153                         }
154                 case PktTypeFile:
155                         dst := string(pkt.Path[:int(pkt.PathLen)])
156                         sds := SdsAdd(sds, SDS{"type": "file", "dst": dst})
157                         incoming := ctx.Neigh[*job.PktEnc.Sender].Incoming
158                         if incoming == nil {
159                                 ctx.LogE("rx", sds, "incoming is not allowed")
160                                 goto Closing
161                         }
162                         dir := filepath.Join(*incoming, path.Dir(dst))
163                         if err = os.MkdirAll(dir, os.FileMode(0700)); err != nil {
164                                 ctx.LogE("rx", SdsAdd(sds, SDS{"err": err}), "mkdir")
165                                 goto Closing
166                         }
167                         if !dryRun {
168                                 tmp, err := ioutil.TempFile(dir, "nncp-file")
169                                 sds["tmp"] = tmp.Name()
170                                 ctx.LogD("rx", sds, "created")
171                                 if err != nil {
172                                         ctx.LogE("rx", SdsAdd(sds, SDS{"err": err}), "mktemp")
173                                         goto Closing
174                                 }
175                                 bufW := bufio.NewWriter(tmp)
176                                 if _, err = io.Copy(bufW, pipeR); err != nil {
177                                         ctx.LogE("rx", SdsAdd(sds, SDS{"err": err}), "copy")
178                                         goto Closing
179                                 }
180                                 bufW.Flush()
181                                 tmp.Sync()
182                                 tmp.Close()
183                                 dstPathOrig := filepath.Join(*incoming, dst)
184                                 dstPath := dstPathOrig
185                                 dstPathCtr := 0
186                                 for {
187                                         if _, err = os.Stat(dstPath); err != nil {
188                                                 if os.IsNotExist(err) {
189                                                         break
190                                                 }
191                                                 ctx.LogE("rx", SdsAdd(sds, SDS{"err": err}), "stat")
192                                                 goto Closing
193                                         }
194                                         dstPath = dstPathOrig + strconv.Itoa(dstPathCtr)
195                                         dstPathCtr++
196                                 }
197                                 if err = os.Rename(tmp.Name(), dstPath); err != nil {
198                                         ctx.LogE("rx", SdsAdd(sds, SDS{"err": err}), "rename")
199                                 }
200                                 delete(sds, "tmp")
201                         }
202                         ctx.LogI("rx", sds, "")
203                         if !dryRun {
204                                 if err = os.Remove(job.Fd.Name()); err != nil {
205                                         ctx.LogE("rx", SdsAdd(sds, SDS{"err": err}), "remove")
206                                 }
207                                 sendmail := ctx.Neigh[*ctx.Self.Id].Sendmail
208                                 if ctx.NotifyFile != nil {
209                                         cmd := exec.Command(
210                                                 sendmail[0],
211                                                 append(sendmail[1:len(sendmail)], ctx.NotifyFile.To)...,
212                                         )
213                                         cmd.Stdin = newNotification(ctx.NotifyFile, fmt.Sprintf(
214                                                 "File from %s: %s (%s)",
215                                                 ctx.Neigh[*job.PktEnc.Sender].Name,
216                                                 dst,
217                                                 humanize.IBytes(uint64(pktSize)),
218                                         ))
219                                         cmd.Run()
220                                 }
221                         }
222                 case PktTypeFreq:
223                         src := string(pkt.Path[:int(pkt.PathLen)])
224                         sds := SdsAdd(sds, SDS{"type": "freq", "src": src})
225                         dstRaw, err := ioutil.ReadAll(pipeR)
226                         if err != nil {
227                                 ctx.LogE("rx", SdsAdd(sds, SDS{"err": err}), "read")
228                                 goto Closing
229                         }
230                         dst := string(dstRaw)
231                         sds["dst"] = dst
232                         sender := ctx.Neigh[*job.PktEnc.Sender]
233                         freq := sender.Freq
234                         if freq == nil {
235                                 ctx.LogE("rx", sds, "freqing is not allowed")
236                                 goto Closing
237                         }
238                         if !dryRun {
239                                 if err = ctx.TxFile(sender, job.PktEnc.Nice, filepath.Join(*freq, src), dst); err != nil {
240                                         ctx.LogE("rx", SdsAdd(sds, SDS{"err": err}), "tx file")
241                                         goto Closing
242                                 }
243                         }
244                         ctx.LogI("rx", sds, "")
245                         if !dryRun {
246                                 if err = os.Remove(job.Fd.Name()); err != nil {
247                                         ctx.LogE("rx", SdsAdd(sds, SDS{"err": err}), "remove")
248                                 }
249                                 if ctx.NotifyFreq != nil {
250                                         sendmail := ctx.Neigh[*ctx.Self.Id].Sendmail
251                                         cmd := exec.Command(
252                                                 sendmail[0],
253                                                 append(sendmail[1:len(sendmail)], ctx.NotifyFreq.To)...,
254                                         )
255                                         cmd.Stdin = newNotification(ctx.NotifyFreq, fmt.Sprintf(
256                                                 "Freq from %s: %s",
257                                                 ctx.Neigh[*job.PktEnc.Sender].Name,
258                                                 src,
259                                         ))
260                                         cmd.Run()
261                                 }
262                         }
263                 case PktTypeTrns:
264                         dst := new([blake2b.Size256]byte)
265                         copy(dst[:], pkt.Path[:int(pkt.PathLen)])
266                         nodeId := NodeId(*dst)
267                         node, known := ctx.Neigh[nodeId]
268                         sds := SdsAdd(sds, SDS{"type": "trns", "dst": nodeId})
269                         if !known {
270                                 ctx.LogE("rx", sds, "unknown node")
271                                 goto Closing
272                         }
273                         ctx.LogD("rx", sds, "taken")
274                         if !dryRun {
275                                 if err = ctx.TxTrns(node, job.PktEnc.Nice, pktSize, pipeR); err != nil {
276                                         ctx.LogE("rx", SdsAdd(sds, SDS{"err": err}), "tx trns")
277                                         goto Closing
278                                 }
279                         }
280                         ctx.LogI("rx", sds, "")
281                         if !dryRun {
282                                 if err = os.Remove(job.Fd.Name()); err != nil {
283                                         ctx.LogE("rx", SdsAdd(sds, SDS{"err": err}), "remove")
284                                 }
285                         }
286                 default:
287                         ctx.LogE("rx", sds, "unknown type")
288                 }
289         Closing:
290                 pipeR.Close()
291         }
292 }