]> Cypherpunks.ru repositories - nncp.git/blob - src/cmd/nncp-xfer/main.go
a2d1d29658cd30e9b9152f90c25d686d739bf9fd
[nncp.git] / src / cmd / nncp-xfer / main.go
1 /*
2 NNCP -- Node to Node copy, utilities for store-and-forward data exchange
3 Copyright (C) 2016-2019 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, version 3 of the License.
8
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.
13
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/>.
16 */
17
18 // Exchange NNCP inbound and outbounds packets with external directory.
19 package main
20
21 import (
22         "bufio"
23         "flag"
24         "fmt"
25         "io"
26         "log"
27         "os"
28         "path/filepath"
29         "strconv"
30
31         "github.com/davecgh/go-xdr/xdr2"
32         "go.cypherpunks.ru/nncp/v4"
33 )
34
35 func usage() {
36         fmt.Fprintf(os.Stderr, nncp.UsageHeader())
37         fmt.Fprintf(os.Stderr, "nncp-xfer -- copy inbound and outbounds packets\n\n")
38         fmt.Fprintf(os.Stderr, "Usage: %s [options] DIR\nOptions:\n", os.Args[0])
39         flag.PrintDefaults()
40 }
41
42 func main() {
43         var (
44                 cfgPath   = flag.String("cfg", nncp.DefaultCfgPath, "Path to configuration file")
45                 nodeRaw   = flag.String("node", "", "Process only that node")
46                 niceRaw   = flag.String("nice", nncp.NicenessFmt(255), "Minimal required niceness")
47                 rxOnly    = flag.Bool("rx", false, "Only receive packets")
48                 txOnly    = flag.Bool("tx", false, "Only transfer packets")
49                 mkdir     = flag.Bool("mkdir", false, "Create necessary outbound directories")
50                 keep      = flag.Bool("keep", false, "Do not delete transferred packets")
51                 spoolPath = flag.String("spool", "", "Override path to spool")
52                 logPath   = flag.String("log", "", "Override path to logfile")
53                 quiet     = flag.Bool("quiet", false, "Print only errors")
54                 debug     = flag.Bool("debug", false, "Print debug messages")
55                 version   = flag.Bool("version", false, "Print version information")
56                 warranty  = flag.Bool("warranty", false, "Print warranty information")
57         )
58         flag.Usage = usage
59         flag.Parse()
60         if *warranty {
61                 fmt.Println(nncp.Warranty)
62                 return
63         }
64         if *version {
65                 fmt.Println(nncp.VersionGet())
66                 return
67         }
68         if flag.NArg() != 1 {
69                 usage()
70                 os.Exit(1)
71         }
72         nice, err := nncp.NicenessParse(*niceRaw)
73         if err != nil {
74                 log.Fatalln(err)
75         }
76         if *rxOnly && *txOnly {
77                 log.Fatalln("-rx and -tx can not be set simultaneously")
78         }
79
80         ctx, err := nncp.CtxFromCmdline(*cfgPath, *spoolPath, *logPath, *quiet, *debug)
81         if err != nil {
82                 log.Fatalln("Error during initialization:", err)
83         }
84
85         var nodeOnly *nncp.Node
86         if *nodeRaw != "" {
87                 nodeOnly, err = ctx.FindNode(*nodeRaw)
88                 if err != nil {
89                         log.Fatalln("Invalid -node specified:", err)
90                 }
91         }
92
93         selfPath := filepath.Join(flag.Arg(0), ctx.SelfId.String())
94         isBad := false
95         var dir *os.File
96         var fis []os.FileInfo
97         sds := nncp.SDS{}
98         if *txOnly {
99                 goto Tx
100         }
101         sds["xx"] = string(nncp.TRx)
102         sds["dir"] = selfPath
103         ctx.LogD("nncp-xfer", sds, "self")
104         if _, err = os.Stat(selfPath); err != nil {
105                 if os.IsNotExist(err) {
106                         ctx.LogD("nncp-xfer", sds, "no dir")
107                         goto Tx
108                 }
109                 ctx.LogE("nncp-xfer", nncp.SdsAdd(sds, nncp.SDS{"err": err}), "stat")
110                 isBad = true
111                 goto Tx
112         }
113         dir, err = os.Open(selfPath)
114         if err != nil {
115                 ctx.LogE("nncp-xfer", nncp.SdsAdd(sds, nncp.SDS{"err": err}), "open")
116                 isBad = true
117                 goto Tx
118         }
119         fis, err = dir.Readdir(0)
120         dir.Close()
121         if err != nil {
122                 ctx.LogE("nncp-xfer", nncp.SdsAdd(sds, nncp.SDS{"err": err}), "read")
123                 isBad = true
124                 goto Tx
125         }
126         for _, fi := range fis {
127                 if !fi.IsDir() {
128                         continue
129                 }
130                 nodeId, err := nncp.NodeIdFromString(fi.Name())
131                 sds["node"] = fi.Name()
132                 if err != nil {
133                         ctx.LogD("nncp-xfer", sds, "is not NodeId")
134                         continue
135                 }
136                 if nodeOnly != nil && *nodeId != *nodeOnly.Id {
137                         ctx.LogD("nncp-xfer", sds, "skip")
138                         continue
139                 }
140                 if _, known := ctx.Neigh[*nodeId]; !known {
141                         ctx.LogD("nncp-xfer", sds, "unknown")
142                         continue
143                 }
144                 dir, err = os.Open(filepath.Join(selfPath, fi.Name()))
145                 if err != nil {
146                         ctx.LogE("nncp-xfer", nncp.SdsAdd(sds, nncp.SDS{"err": err}), "open")
147                         isBad = true
148                         continue
149                 }
150                 fisInt, err := dir.Readdir(0)
151                 dir.Close()
152                 if err != nil {
153                         ctx.LogE("nncp-xfer", nncp.SdsAdd(sds, nncp.SDS{"err": err}), "read")
154                         isBad = true
155                         continue
156                 }
157                 for _, fiInt := range fisInt {
158                         if !fi.IsDir() {
159                                 continue
160                         }
161                         filename := filepath.Join(dir.Name(), fiInt.Name())
162                         sds["file"] = filename
163                         delete(sds, "size")
164                         fd, err := os.Open(filename)
165                         if err != nil {
166                                 ctx.LogE("nncp-xfer", nncp.SdsAdd(sds, nncp.SDS{"err": err}), "open")
167                                 isBad = true
168                                 continue
169                         }
170                         var pktEnc nncp.PktEnc
171                         _, err = xdr.Unmarshal(fd, &pktEnc)
172                         if err != nil || pktEnc.Magic != nncp.MagicNNCPEv4 {
173                                 ctx.LogD("nncp-xfer", sds, "is not a packet")
174                                 fd.Close()
175                                 continue
176                         }
177                         if pktEnc.Nice > nice {
178                                 ctx.LogD("nncp-xfer", sds, "too nice")
179                                 fd.Close()
180                                 continue
181                         }
182                         sds["size"] = strconv.FormatInt(fiInt.Size(), 10)
183                         if !ctx.IsEnoughSpace(fiInt.Size()) {
184                                 ctx.LogE("nncp-xfer", sds, "is not enough space")
185                                 fd.Close()
186                                 continue
187                         }
188                         fd.Seek(0, 0)
189                         tmp, err := ctx.NewTmpFileWHash()
190                         if err != nil {
191                                 log.Fatalln(err)
192                         }
193                         if _, err = io.CopyN(tmp.W, bufio.NewReader(fd), fiInt.Size()); err != nil {
194                                 ctx.LogE("nncp-xfer", nncp.SdsAdd(sds, nncp.SDS{"err": err}), "copy")
195                                 isBad = true
196                                 fd.Close()
197                                 tmp.Cancel()
198                                 continue
199                         }
200                         fd.Close()
201                         if err = tmp.Commit(filepath.Join(
202                                 ctx.Spool,
203                                 nodeId.String(),
204                                 string(nncp.TRx),
205                         )); err != nil {
206                                 log.Fatalln(err)
207                         }
208                         ctx.LogI("nncp-xfer", sds, "")
209                         if !*keep {
210                                 if err = os.Remove(filename); err != nil {
211                                         ctx.LogE("nncp-xfer", nncp.SdsAdd(sds, nncp.SDS{"err": err}), "remove")
212                                         isBad = true
213                                 }
214                         }
215                 }
216         }
217
218 Tx:
219         if *rxOnly {
220                 if isBad {
221                         os.Exit(1)
222                 }
223                 return
224         }
225         sds["xx"] = string(nncp.TTx)
226         for nodeId, _ := range ctx.Neigh {
227                 sds["node"] = nodeId
228                 if nodeOnly != nil && nodeId != *nodeOnly.Id {
229                         ctx.LogD("nncp-xfer", sds, "skip")
230                         continue
231                 }
232                 dirLock, err := ctx.LockDir(&nodeId, nncp.TTx)
233                 if err != nil {
234                         continue
235                 }
236                 nodePath := filepath.Join(flag.Arg(0), nodeId.String())
237                 sds["dir"] = nodePath
238                 _, err = os.Stat(nodePath)
239                 if err != nil {
240                         if os.IsNotExist(err) {
241                                 ctx.LogD("nncp-xfer", sds, "does not exist")
242                                 if !*mkdir {
243                                         ctx.UnlockDir(dirLock)
244                                         continue
245                                 }
246                                 if err = os.Mkdir(nodePath, os.FileMode(0777)); err != nil {
247                                         ctx.UnlockDir(dirLock)
248                                         ctx.LogE("nncp-xfer", nncp.SdsAdd(sds, nncp.SDS{"err": err}), "mkdir")
249                                         isBad = true
250                                         continue
251                                 }
252                         } else {
253                                 ctx.UnlockDir(dirLock)
254                                 ctx.LogE("nncp-xfer", nncp.SdsAdd(sds, nncp.SDS{"err": err}), "stat")
255                                 isBad = true
256                                 continue
257                         }
258                 }
259                 dstPath := filepath.Join(nodePath, ctx.SelfId.String())
260                 sds["dir"] = dstPath
261                 _, err = os.Stat(dstPath)
262                 if err != nil {
263                         if os.IsNotExist(err) {
264                                 if err = os.Mkdir(dstPath, os.FileMode(0777)); err != nil {
265                                         ctx.UnlockDir(dirLock)
266                                         ctx.LogE("nncp-xfer", nncp.SdsAdd(sds, nncp.SDS{"err": err}), "mkdir")
267                                         isBad = true
268                                         continue
269                                 }
270                         } else {
271                                 ctx.UnlockDir(dirLock)
272                                 ctx.LogE("nncp-xfer", nncp.SdsAdd(sds, nncp.SDS{"err": err}), "stat")
273                                 isBad = true
274                                 continue
275                         }
276                 }
277                 delete(sds, "dir")
278                 for job := range ctx.Jobs(&nodeId, nncp.TTx) {
279                         pktName := filepath.Base(job.Fd.Name())
280                         sds["pkt"] = pktName
281                         if job.PktEnc.Nice > nice {
282                                 ctx.LogD("nncp-xfer", sds, "too nice")
283                                 job.Fd.Close()
284                                 continue
285                         }
286                         if _, err = os.Stat(filepath.Join(dstPath, pktName)); err == nil || !os.IsNotExist(err) {
287                                 ctx.LogD("nncp-xfer", sds, "already exists")
288                                 job.Fd.Close()
289                                 continue
290                         }
291                         if _, err = os.Stat(filepath.Join(dstPath, pktName+nncp.SeenSuffix)); err == nil || !os.IsNotExist(err) {
292                                 ctx.LogD("nncp-xfer", sds, "already exists")
293                                 job.Fd.Close()
294                                 continue
295                         }
296                         tmp, err := nncp.TempFile(dstPath, "xfer")
297                         if err != nil {
298                                 ctx.LogE("nncp-xfer", nncp.SdsAdd(sds, nncp.SDS{"err": err}), "mktemp")
299                                 job.Fd.Close()
300                                 isBad = true
301                                 break
302                         }
303                         sds["tmp"] = tmp.Name()
304                         ctx.LogD("nncp-xfer", sds, "created")
305                         bufW := bufio.NewWriter(tmp)
306                         copied, err := io.Copy(bufW, bufio.NewReader(job.Fd))
307                         job.Fd.Close()
308                         if err != nil {
309                                 ctx.LogE("nncp-xfer", nncp.SdsAdd(sds, nncp.SDS{"err": err}), "copy")
310                                 tmp.Close()
311                                 isBad = true
312                                 continue
313                         }
314                         if err = bufW.Flush(); err != nil {
315                                 tmp.Close()
316                                 ctx.LogE("nncp-xfer", nncp.SdsAdd(sds, nncp.SDS{"err": err}), "flush")
317                                 isBad = true
318                                 continue
319                         }
320                         if err = tmp.Sync(); err != nil {
321                                 tmp.Close()
322                                 ctx.LogE("nncp-xfer", nncp.SdsAdd(sds, nncp.SDS{"err": err}), "sync")
323                                 isBad = true
324                                 continue
325                         }
326                         tmp.Close()
327                         if err = os.Rename(tmp.Name(), filepath.Join(dstPath, pktName)); err != nil {
328                                 ctx.LogE("nncp-xfer", nncp.SdsAdd(sds, nncp.SDS{"err": err}), "rename")
329                                 isBad = true
330                                 continue
331                         }
332                         os.Remove(filepath.Join(dstPath, pktName+".part"))
333                         delete(sds, "tmp")
334                         ctx.LogI("nncp-xfer", nncp.SdsAdd(sds, nncp.SDS{
335                                 "size": strconv.FormatInt(copied, 10),
336                         }), "")
337                         if !*keep {
338                                 if err = os.Remove(job.Fd.Name()); err != nil {
339                                         ctx.LogE("nncp-xfer", nncp.SdsAdd(sds, nncp.SDS{"err": err}), "remove")
340                                         isBad = true
341                                 }
342                         }
343                 }
344                 ctx.UnlockDir(dirLock)
345         }
346         if isBad {
347                 os.Exit(1)
348         }
349 }