]> Cypherpunks.ru repositories - nncp.git/blob - src/cmd/nncp-xfer/main.go
Operations progress
[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         "errors"
24         "flag"
25         "fmt"
26         "io"
27         "log"
28         "os"
29         "path/filepath"
30
31         xdr "github.com/davecgh/go-xdr/xdr2"
32         "go.cypherpunks.ru/nncp/v5"
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                 showPrgrs = flag.Bool("progress", false, "Force progress showing")
55                 omitPrgrs = flag.Bool("noprogress", false, "Omit progress showing")
56                 debug     = flag.Bool("debug", false, "Print debug messages")
57                 version   = flag.Bool("version", false, "Print version information")
58                 warranty  = flag.Bool("warranty", false, "Print warranty information")
59         )
60         flag.Usage = usage
61         flag.Parse()
62         if *warranty {
63                 fmt.Println(nncp.Warranty)
64                 return
65         }
66         if *version {
67                 fmt.Println(nncp.VersionGet())
68                 return
69         }
70         if flag.NArg() != 1 {
71                 usage()
72                 os.Exit(1)
73         }
74         nice, err := nncp.NicenessParse(*niceRaw)
75         if err != nil {
76                 log.Fatalln(err)
77         }
78         if *rxOnly && *txOnly {
79                 log.Fatalln("-rx and -tx can not be set simultaneously")
80         }
81
82         ctx, err := nncp.CtxFromCmdline(
83                 *cfgPath,
84                 *spoolPath,
85                 *logPath,
86                 *quiet,
87                 *showPrgrs,
88                 *omitPrgrs,
89                 *debug,
90         )
91         if err != nil {
92                 log.Fatalln("Error during initialization:", err)
93         }
94
95         var nodeOnly *nncp.Node
96         if *nodeRaw != "" {
97                 nodeOnly, err = ctx.FindNode(*nodeRaw)
98                 if err != nil {
99                         log.Fatalln("Invalid -node specified:", err)
100                 }
101         }
102
103         ctx.Umask()
104         selfPath := filepath.Join(flag.Arg(0), ctx.SelfId.String())
105         isBad := false
106         var dir *os.File
107         var fis []os.FileInfo
108         sds := nncp.SDS{}
109         if *txOnly {
110                 goto Tx
111         }
112         sds["xx"] = string(nncp.TRx)
113         sds["dir"] = selfPath
114         ctx.LogD("nncp-xfer", sds, "self")
115         if _, err = os.Stat(selfPath); err != nil {
116                 if os.IsNotExist(err) {
117                         ctx.LogD("nncp-xfer", sds, "no dir")
118                         goto Tx
119                 }
120                 ctx.LogE("nncp-xfer", sds, err, "stat")
121                 isBad = true
122                 goto Tx
123         }
124         dir, err = os.Open(selfPath)
125         if err != nil {
126                 ctx.LogE("nncp-xfer", sds, err, "open")
127                 isBad = true
128                 goto Tx
129         }
130         fis, err = dir.Readdir(0)
131         dir.Close()
132         if err != nil {
133                 ctx.LogE("nncp-xfer", sds, err, "read")
134                 isBad = true
135                 goto Tx
136         }
137         for _, fi := range fis {
138                 if !fi.IsDir() {
139                         continue
140                 }
141                 nodeId, err := nncp.NodeIdFromString(fi.Name())
142                 sds["node"] = fi.Name()
143                 if err != nil {
144                         ctx.LogD("nncp-xfer", sds, "is not NodeId")
145                         continue
146                 }
147                 if nodeOnly != nil && *nodeId != *nodeOnly.Id {
148                         ctx.LogD("nncp-xfer", sds, "skip")
149                         continue
150                 }
151                 if _, known := ctx.Neigh[*nodeId]; !known {
152                         ctx.LogD("nncp-xfer", sds, "unknown")
153                         continue
154                 }
155                 dir, err = os.Open(filepath.Join(selfPath, fi.Name()))
156                 if err != nil {
157                         ctx.LogE("nncp-xfer", sds, err, "open")
158                         isBad = true
159                         continue
160                 }
161                 fisInt, err := dir.Readdir(0)
162                 dir.Close()
163                 if err != nil {
164                         ctx.LogE("nncp-xfer", sds, err, "read")
165                         isBad = true
166                         continue
167                 }
168                 for _, fiInt := range fisInt {
169                         if !fi.IsDir() {
170                                 continue
171                         }
172                         // Check that it is valid Base32 encoding
173                         if _, err = nncp.NodeIdFromString(fiInt.Name()); err != nil {
174                                 continue
175                         }
176                         filename := filepath.Join(dir.Name(), fiInt.Name())
177                         sds["file"] = filename
178                         delete(sds, "size")
179                         fd, err := os.Open(filename)
180                         if err != nil {
181                                 ctx.LogE("nncp-xfer", sds, err, "open")
182                                 isBad = true
183                                 continue
184                         }
185                         var pktEnc nncp.PktEnc
186                         _, err = xdr.Unmarshal(fd, &pktEnc)
187                         if err != nil || pktEnc.Magic != nncp.MagicNNCPEv4 {
188                                 ctx.LogD("nncp-xfer", sds, "is not a packet")
189                                 fd.Close()
190                                 continue
191                         }
192                         if pktEnc.Nice > nice {
193                                 ctx.LogD("nncp-xfer", sds, "too nice")
194                                 fd.Close()
195                                 continue
196                         }
197                         sds["size"] = fiInt.Size()
198                         if !ctx.IsEnoughSpace(fiInt.Size()) {
199                                 ctx.LogE("nncp-xfer", sds, errors.New("is not enough space"), "")
200                                 fd.Close()
201                                 continue
202                         }
203                         fd.Seek(0, 0)
204                         tmp, err := ctx.NewTmpFileWHash()
205                         if err != nil {
206                                 log.Fatalln(err)
207                         }
208                         r, w := io.Pipe()
209                         go func() {
210                                 _, err := io.CopyN(w, bufio.NewReader(fd), fiInt.Size())
211                                 if err == nil {
212                                         w.Close()
213                                         return
214                                 }
215                                 ctx.LogE("nncp-xfer", sds, err, "copy")
216                                 w.CloseWithError(err)
217                         }()
218                         if _, err = nncp.CopyProgressed(tmp.W, r, nncp.SdsAdd(sds, nncp.SDS{
219                                 "pkt":      filename,
220                                 "fullsize": sds["size"],
221                         }), ctx.ShowPrgrs); err != nil {
222                                 ctx.LogE("nncp-xfer", sds, err, "copy")
223                                 isBad = true
224                         }
225                         fd.Close()
226                         if isBad {
227                                 tmp.Cancel()
228                                 continue
229                         }
230                         if err = tmp.Commit(filepath.Join(
231                                 ctx.Spool,
232                                 nodeId.String(),
233                                 string(nncp.TRx),
234                         )); err != nil {
235                                 log.Fatalln(err)
236                         }
237                         ctx.LogI("nncp-xfer", sds, "")
238                         if !*keep {
239                                 if err = os.Remove(filename); err != nil {
240                                         ctx.LogE("nncp-xfer", sds, err, "remove")
241                                         isBad = true
242                                 }
243                         }
244                 }
245         }
246
247 Tx:
248         if *rxOnly {
249                 if isBad {
250                         os.Exit(1)
251                 }
252                 return
253         }
254         sds["xx"] = string(nncp.TTx)
255         for nodeId, _ := range ctx.Neigh {
256                 sds["node"] = nodeId
257                 if nodeOnly != nil && nodeId != *nodeOnly.Id {
258                         ctx.LogD("nncp-xfer", sds, "skip")
259                         continue
260                 }
261                 dirLock, err := ctx.LockDir(&nodeId, nncp.TTx)
262                 if err != nil {
263                         continue
264                 }
265                 nodePath := filepath.Join(flag.Arg(0), nodeId.String())
266                 sds["dir"] = nodePath
267                 _, err = os.Stat(nodePath)
268                 if err != nil {
269                         if os.IsNotExist(err) {
270                                 ctx.LogD("nncp-xfer", sds, "does not exist")
271                                 if !*mkdir {
272                                         ctx.UnlockDir(dirLock)
273                                         continue
274                                 }
275                                 if err = os.Mkdir(nodePath, os.FileMode(0777)); err != nil {
276                                         ctx.UnlockDir(dirLock)
277                                         ctx.LogE("nncp-xfer", sds, err, "mkdir")
278                                         isBad = true
279                                         continue
280                                 }
281                         } else {
282                                 ctx.UnlockDir(dirLock)
283                                 ctx.LogE("nncp-xfer", sds, err, "stat")
284                                 isBad = true
285                                 continue
286                         }
287                 }
288                 dstPath := filepath.Join(nodePath, ctx.SelfId.String())
289                 sds["dir"] = dstPath
290                 _, err = os.Stat(dstPath)
291                 if err != nil {
292                         if os.IsNotExist(err) {
293                                 if err = os.Mkdir(dstPath, os.FileMode(0777)); err != nil {
294                                         ctx.UnlockDir(dirLock)
295                                         ctx.LogE("nncp-xfer", sds, err, "mkdir")
296                                         isBad = true
297                                         continue
298                                 }
299                         } else {
300                                 ctx.UnlockDir(dirLock)
301                                 ctx.LogE("nncp-xfer", sds, err, "stat")
302                                 isBad = true
303                                 continue
304                         }
305                 }
306                 delete(sds, "dir")
307                 for job := range ctx.Jobs(&nodeId, nncp.TTx) {
308                         pktName := filepath.Base(job.Fd.Name())
309                         sds["pkt"] = pktName
310                         if job.PktEnc.Nice > nice {
311                                 ctx.LogD("nncp-xfer", sds, "too nice")
312                                 job.Fd.Close()
313                                 continue
314                         }
315                         if _, err = os.Stat(filepath.Join(dstPath, pktName)); err == nil || !os.IsNotExist(err) {
316                                 ctx.LogD("nncp-xfer", sds, "already exists")
317                                 job.Fd.Close()
318                                 continue
319                         }
320                         if _, err = os.Stat(filepath.Join(dstPath, pktName+nncp.SeenSuffix)); err == nil || !os.IsNotExist(err) {
321                                 ctx.LogD("nncp-xfer", sds, "already exists")
322                                 job.Fd.Close()
323                                 continue
324                         }
325                         tmp, err := nncp.TempFile(dstPath, "xfer")
326                         if err != nil {
327                                 ctx.LogE("nncp-xfer", sds, err, "mktemp")
328                                 job.Fd.Close()
329                                 isBad = true
330                                 break
331                         }
332                         sds["tmp"] = tmp.Name()
333                         ctx.LogD("nncp-xfer", sds, "created")
334                         bufW := bufio.NewWriter(tmp)
335                         copied, err := nncp.CopyProgressed(
336                                 bufW,
337                                 bufio.NewReader(job.Fd),
338                                 nncp.SdsAdd(sds, nncp.SDS{"fullsize": job.Size}),
339                                 ctx.ShowPrgrs,
340                         )
341                         job.Fd.Close()
342                         if err != nil {
343                                 ctx.LogE("nncp-xfer", sds, err, "copy")
344                                 tmp.Close()
345                                 isBad = true
346                                 continue
347                         }
348                         if err = bufW.Flush(); err != nil {
349                                 tmp.Close()
350                                 ctx.LogE("nncp-xfer", sds, err, "flush")
351                                 isBad = true
352                                 continue
353                         }
354                         if err = tmp.Sync(); err != nil {
355                                 tmp.Close()
356                                 ctx.LogE("nncp-xfer", sds, err, "sync")
357                                 isBad = true
358                                 continue
359                         }
360                         tmp.Close()
361                         if err = os.Rename(tmp.Name(), filepath.Join(dstPath, pktName)); err != nil {
362                                 ctx.LogE("nncp-xfer", sds, err, "rename")
363                                 isBad = true
364                                 continue
365                         }
366                         if err = nncp.DirSync(dstPath); err != nil {
367                                 ctx.LogE("nncp-xfer", sds, err, "sync")
368                                 isBad = true
369                                 continue
370                         }
371                         os.Remove(filepath.Join(dstPath, pktName+".part"))
372                         delete(sds, "tmp")
373                         ctx.LogI("nncp-xfer", nncp.SdsAdd(sds, nncp.SDS{"size": copied}), "")
374                         if !*keep {
375                                 if err = os.Remove(job.Fd.Name()); err != nil {
376                                         ctx.LogE("nncp-xfer", sds, err, "remove")
377                                         isBad = true
378                                 }
379                         }
380                 }
381                 ctx.UnlockDir(dirLock)
382         }
383         if isBad {
384                 os.Exit(1)
385         }
386 }