]> Cypherpunks.ru repositories - nncp.git/blob - src/cmd/nncp-reass/main.go
Prefixed progress messages
[nncp.git] / src / cmd / nncp-reass / 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 // Reassembly chunked file.
19 package main
20
21 import (
22         "bufio"
23         "bytes"
24         "encoding/hex"
25         "errors"
26         "flag"
27         "fmt"
28         "hash"
29         "io"
30         "log"
31         "os"
32         "path/filepath"
33         "strconv"
34         "strings"
35
36         xdr "github.com/davecgh/go-xdr/xdr2"
37         "github.com/dustin/go-humanize"
38         "go.cypherpunks.ru/nncp/v5"
39         "golang.org/x/crypto/blake2b"
40 )
41
42 func usage() {
43         fmt.Fprintf(os.Stderr, nncp.UsageHeader())
44         fmt.Fprintf(os.Stderr, "nncp-reass -- reassemble chunked files\n\n")
45         fmt.Fprintf(os.Stderr, "Usage: %s [options] [FILE.nncp.meta]\nOptions:\n", os.Args[0])
46         flag.PrintDefaults()
47         fmt.Fprint(os.Stderr, `
48 Neither FILE, nor -node nor -all can be set simultaneously,
49 but at least one of them must be specified.
50 `)
51 }
52
53 func process(ctx *nncp.Ctx, path string, keep, dryRun, stdout, dumpMeta bool) bool {
54         fd, err := os.Open(path)
55         defer fd.Close()
56         if err != nil {
57                 log.Fatalln("Can not open file:", err)
58         }
59         var metaPkt nncp.ChunkedMeta
60         if _, err = xdr.Unmarshal(fd, &metaPkt); err != nil {
61                 ctx.LogE("nncp-reass", nncp.SDS{"path": path}, err, "bad meta file")
62                 return false
63         }
64         fd.Close()
65         if metaPkt.Magic != nncp.MagicNNCPMv1 {
66                 ctx.LogE("nncp-reass", nncp.SDS{"path": path}, nncp.BadMagic, "")
67                 return false
68         }
69
70         metaName := filepath.Base(path)
71         if !strings.HasSuffix(metaName, nncp.ChunkedSuffixMeta) {
72                 ctx.LogE("nncp-reass", nncp.SDS{"path": path}, errors.New("invalid filename suffix"), "")
73                 return false
74         }
75         mainName := strings.TrimSuffix(metaName, nncp.ChunkedSuffixMeta)
76         if dumpMeta {
77                 fmt.Printf("Original filename: %s\n", mainName)
78                 fmt.Printf(
79                         "File size: %s (%d bytes)\n",
80                         humanize.IBytes(metaPkt.FileSize),
81                         metaPkt.FileSize,
82                 )
83                 fmt.Printf(
84                         "Chunk size: %s (%d bytes)\n",
85                         humanize.IBytes(metaPkt.ChunkSize),
86                         metaPkt.ChunkSize,
87                 )
88                 fmt.Printf("Number of chunks: %d\n", len(metaPkt.Checksums))
89                 fmt.Println("Checksums:")
90                 for chunkNum, checksum := range metaPkt.Checksums {
91                         fmt.Printf("\t%d: %s\n", chunkNum, hex.EncodeToString(checksum[:]))
92                 }
93                 return true
94         }
95         mainDir := filepath.Dir(path)
96
97         chunksPaths := make([]string, 0, len(metaPkt.Checksums))
98         for i := 0; i < len(metaPkt.Checksums); i++ {
99                 chunksPaths = append(
100                         chunksPaths,
101                         filepath.Join(mainDir, mainName+nncp.ChunkedSuffixPart+strconv.Itoa(i)),
102                 )
103         }
104
105         allChunksExist := true
106         for chunkNum, chunkPath := range chunksPaths {
107                 fi, err := os.Stat(chunkPath)
108                 if err != nil && os.IsNotExist(err) {
109                         ctx.LogI("nncp-reass", nncp.SDS{"path": path, "chunk": chunkNum}, "missing")
110                         allChunksExist = false
111                         continue
112                 }
113                 var badSize bool
114                 if chunkNum+1 == len(chunksPaths) {
115                         badSize = uint64(fi.Size()) != metaPkt.FileSize%metaPkt.ChunkSize
116                 } else {
117                         badSize = uint64(fi.Size()) != metaPkt.ChunkSize
118                 }
119                 if badSize {
120                         ctx.LogE(
121                                 "nncp-reass",
122                                 nncp.SDS{"path": path, "chunk": chunkNum},
123                                 errors.New("invalid size"), "",
124                         )
125                         allChunksExist = false
126                 }
127         }
128         if !allChunksExist {
129                 return false
130         }
131
132         var hsh hash.Hash
133         allChecksumsGood := true
134         for chunkNum, chunkPath := range chunksPaths {
135                 fd, err = os.Open(chunkPath)
136                 if err != nil {
137                         log.Fatalln("Can not open file:", err)
138                 }
139                 fi, err := fd.Stat()
140                 if err != nil {
141                         log.Fatalln("Can not stat file:", err)
142                 }
143                 hsh, err = blake2b.New256(nil)
144                 if err != nil {
145                         log.Fatalln(err)
146                 }
147                 if _, err = nncp.CopyProgressed(
148                         hsh, bufio.NewReader(fd), "check",
149                         nncp.SDS{
150                                 "pkt":      chunkPath,
151                                 "fullsize": fi.Size(),
152                         },
153                         ctx.ShowPrgrs,
154                 ); err != nil {
155                         log.Fatalln(err)
156                 }
157                 fd.Close()
158                 if bytes.Compare(hsh.Sum(nil), metaPkt.Checksums[chunkNum][:]) != 0 {
159                         ctx.LogE(
160                                 "nncp-reass",
161                                 nncp.SDS{"path": path, "chunk": chunkNum},
162                                 errors.New("checksum is bad"), "",
163                         )
164                         allChecksumsGood = false
165                 }
166         }
167         if !allChecksumsGood {
168                 return false
169         }
170         if dryRun {
171                 ctx.LogI("nncp-reass", nncp.SDS{"path": path}, "ready")
172                 return true
173         }
174
175         var dst io.Writer
176         var tmp *os.File
177         var sds nncp.SDS
178         if stdout {
179                 dst = os.Stdout
180                 sds = nncp.SDS{"path": path}
181         } else {
182                 tmp, err = nncp.TempFile(mainDir, "reass")
183                 if err != nil {
184                         log.Fatalln(err)
185                 }
186                 sds = nncp.SDS{"path": path, "tmp": tmp.Name()}
187                 ctx.LogD("nncp-reass", sds, "created")
188                 dst = tmp
189         }
190         dstW := bufio.NewWriter(dst)
191
192         hasErrors := false
193         for chunkNum, chunkPath := range chunksPaths {
194                 fd, err = os.Open(chunkPath)
195                 if err != nil {
196                         log.Fatalln("Can not open file:", err)
197                 }
198                 fi, err := fd.Stat()
199                 if err != nil {
200                         log.Fatalln("Can not stat file:", err)
201                 }
202                 if _, err = nncp.CopyProgressed(
203                         dstW, bufio.NewReader(fd), "reass",
204                         nncp.SDS{
205                                 "pkt":      chunkPath,
206                                 "fullsize": fi.Size(),
207                         },
208                         ctx.ShowPrgrs,
209                 ); err != nil {
210                         log.Fatalln(err)
211                 }
212                 fd.Close()
213                 if !keep {
214                         if err = os.Remove(chunkPath); err != nil {
215                                 ctx.LogE("nncp-reass", nncp.SdsAdd(sds, nncp.SDS{"chunk": chunkNum}), err, "")
216                                 hasErrors = true
217                         }
218                 }
219         }
220         if err = dstW.Flush(); err != nil {
221                 log.Fatalln("Can not flush:", err)
222         }
223         if tmp != nil {
224                 if err = tmp.Sync(); err != nil {
225                         log.Fatalln("Can not sync:", err)
226                 }
227                 tmp.Close()
228         }
229         ctx.LogD("nncp-reass", sds, "written")
230         if !keep {
231                 if err = os.Remove(path); err != nil {
232                         ctx.LogE("nncp-reass", sds, err, "")
233                         hasErrors = true
234                 }
235         }
236         if stdout {
237                 ctx.LogI("nncp-reass", nncp.SDS{"path": path}, "done")
238                 return !hasErrors
239         }
240
241         dstPathOrig := filepath.Join(mainDir, mainName)
242         dstPath := dstPathOrig
243         dstPathCtr := 0
244         for {
245                 if _, err = os.Stat(dstPath); err != nil {
246                         if os.IsNotExist(err) {
247                                 break
248                         }
249                         log.Fatalln(err)
250                 }
251                 dstPath = dstPathOrig + "." + strconv.Itoa(dstPathCtr)
252                 dstPathCtr++
253         }
254         if err = os.Rename(tmp.Name(), dstPath); err != nil {
255                 log.Fatalln(err)
256         }
257         if err = nncp.DirSync(mainDir); err != nil {
258                 log.Fatalln(err)
259         }
260         ctx.LogI("nncp-reass", nncp.SDS{"path": path}, "done")
261         return !hasErrors
262 }
263
264 func findMetas(ctx *nncp.Ctx, dirPath string) []string {
265         dir, err := os.Open(dirPath)
266         defer dir.Close()
267         if err != nil {
268                 ctx.LogE("nncp-reass", nncp.SDS{"path": dirPath}, err, "")
269                 return nil
270         }
271         fis, err := dir.Readdir(0)
272         dir.Close()
273         if err != nil {
274                 ctx.LogE("nncp-reass", nncp.SDS{"path": dirPath}, err, "")
275                 return nil
276         }
277         metaPaths := make([]string, 0)
278         for _, fi := range fis {
279                 if strings.HasSuffix(fi.Name(), nncp.ChunkedSuffixMeta) {
280                         metaPaths = append(metaPaths, filepath.Join(dirPath, fi.Name()))
281                 }
282         }
283         return metaPaths
284 }
285
286 func main() {
287         var (
288                 cfgPath   = flag.String("cfg", nncp.DefaultCfgPath, "Path to configuration file")
289                 allNodes  = flag.Bool("all", false, "Process all found chunked files for all nodes")
290                 nodeRaw   = flag.String("node", "", "Process all found chunked files for that node")
291                 keep      = flag.Bool("keep", false, "Do not remove chunks while assembling")
292                 dryRun    = flag.Bool("dryrun", false, "Do not assemble whole file")
293                 dumpMeta  = flag.Bool("dump", false, "Print decoded human-readable FILE.nncp.meta")
294                 stdout    = flag.Bool("stdout", false, "Output reassembled FILE to stdout")
295                 spoolPath = flag.String("spool", "", "Override path to spool")
296                 logPath   = flag.String("log", "", "Override path to logfile")
297                 quiet     = flag.Bool("quiet", false, "Print only errors")
298                 showPrgrs = flag.Bool("progress", false, "Force progress showing")
299                 omitPrgrs = flag.Bool("noprogress", false, "Omit progress showing")
300                 debug     = flag.Bool("debug", false, "Print debug messages")
301                 version   = flag.Bool("version", false, "Print version information")
302                 warranty  = flag.Bool("warranty", false, "Print warranty information")
303         )
304         flag.Usage = usage
305         flag.Parse()
306         if *warranty {
307                 fmt.Println(nncp.Warranty)
308                 return
309         }
310         if *version {
311                 fmt.Println(nncp.VersionGet())
312                 return
313         }
314
315         ctx, err := nncp.CtxFromCmdline(
316                 *cfgPath,
317                 *spoolPath,
318                 *logPath,
319                 *quiet,
320                 *showPrgrs,
321                 *omitPrgrs,
322                 *debug,
323         )
324         if err != nil {
325                 log.Fatalln("Error during initialization:", err)
326         }
327
328         var nodeOnly *nncp.Node
329         if *nodeRaw != "" {
330                 nodeOnly, err = ctx.FindNode(*nodeRaw)
331                 if err != nil {
332                         log.Fatalln("Invalid -node specified:", err)
333                 }
334         }
335
336         if !(*allNodes || nodeOnly != nil || flag.NArg() > 0) {
337                 usage()
338                 os.Exit(1)
339         }
340         if flag.NArg() > 0 && (*allNodes || nodeOnly != nil) {
341                 usage()
342                 os.Exit(1)
343         }
344         if *allNodes && nodeOnly != nil {
345                 usage()
346                 os.Exit(1)
347         }
348
349         ctx.Umask()
350
351         if flag.NArg() > 0 {
352                 if process(ctx, flag.Arg(0), *keep, *dryRun, *stdout, *dumpMeta) {
353                         return
354                 }
355                 os.Exit(1)
356         }
357
358         hasErrors := false
359         if nodeOnly == nil {
360                 seenMetaPaths := make(map[string]struct{})
361                 for _, node := range ctx.Neigh {
362                         if node.Incoming == nil {
363                                 continue
364                         }
365                         for _, metaPath := range findMetas(ctx, *node.Incoming) {
366                                 if _, seen := seenMetaPaths[metaPath]; seen {
367                                         continue
368                                 }
369                                 if !process(ctx, metaPath, *keep, *dryRun, false, false) {
370                                         hasErrors = true
371                                 }
372                                 seenMetaPaths[metaPath] = struct{}{}
373                         }
374                 }
375         } else {
376                 if nodeOnly.Incoming == nil {
377                         log.Fatalln("Specified -node does not allow incoming")
378                 }
379                 for _, metaPath := range findMetas(ctx, *nodeOnly.Incoming) {
380                         if !process(ctx, metaPath, *keep, *dryRun, false, false) {
381                                 hasErrors = true
382                         }
383                 }
384         }
385         if hasErrors {
386                 os.Exit(1)
387         }
388 }