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