]> Cypherpunks.ru repositories - nncp.git/blob - src/cmd/nncp-reass/main.go
Raise copyright years
[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         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() // #nosec G104
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() // #nosec G104
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() // #nosec G104
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                 if err = tmp.Close(); err != nil {
228                         log.Fatalln("Can not close:", err)
229                 }
230         }
231         ctx.LogD("nncp-reass", sds, "written")
232         if !keep {
233                 if err = os.Remove(path); err != nil {
234                         ctx.LogE("nncp-reass", sds, err, "")
235                         hasErrors = true
236                 }
237         }
238         if stdout {
239                 ctx.LogI("nncp-reass", nncp.SDS{"path": path}, "done")
240                 return !hasErrors
241         }
242
243         dstPathOrig := filepath.Join(mainDir, mainName)
244         dstPath := dstPathOrig
245         dstPathCtr := 0
246         for {
247                 if _, err = os.Stat(dstPath); err != nil {
248                         if os.IsNotExist(err) {
249                                 break
250                         }
251                         log.Fatalln(err)
252                 }
253                 dstPath = dstPathOrig + "." + strconv.Itoa(dstPathCtr)
254                 dstPathCtr++
255         }
256         if err = os.Rename(tmp.Name(), dstPath); err != nil {
257                 log.Fatalln(err)
258         }
259         if err = nncp.DirSync(mainDir); err != nil {
260                 log.Fatalln(err)
261         }
262         ctx.LogI("nncp-reass", nncp.SDS{"path": path}, "done")
263         return !hasErrors
264 }
265
266 func findMetas(ctx *nncp.Ctx, dirPath string) []string {
267         dir, err := os.Open(dirPath)
268         defer dir.Close()
269         if err != nil {
270                 ctx.LogE("nncp-reass", nncp.SDS{"path": dirPath}, err, "")
271                 return nil
272         }
273         fis, err := dir.Readdir(0)
274         dir.Close() // #nosec G104
275         if err != nil {
276                 ctx.LogE("nncp-reass", nncp.SDS{"path": dirPath}, err, "")
277                 return nil
278         }
279         metaPaths := make([]string, 0)
280         for _, fi := range fis {
281                 if strings.HasSuffix(fi.Name(), nncp.ChunkedSuffixMeta) {
282                         metaPaths = append(metaPaths, filepath.Join(dirPath, fi.Name()))
283                 }
284         }
285         return metaPaths
286 }
287
288 func main() {
289         var (
290                 cfgPath   = flag.String("cfg", nncp.DefaultCfgPath, "Path to configuration file")
291                 allNodes  = flag.Bool("all", false, "Process all found chunked files for all nodes")
292                 nodeRaw   = flag.String("node", "", "Process all found chunked files for that node")
293                 keep      = flag.Bool("keep", false, "Do not remove chunks while assembling")
294                 dryRun    = flag.Bool("dryrun", false, "Do not assemble whole file")
295                 dumpMeta  = flag.Bool("dump", false, "Print decoded human-readable FILE.nncp.meta")
296                 stdout    = flag.Bool("stdout", false, "Output reassembled FILE to stdout")
297                 spoolPath = flag.String("spool", "", "Override path to spool")
298                 logPath   = flag.String("log", "", "Override path to logfile")
299                 quiet     = flag.Bool("quiet", false, "Print only errors")
300                 showPrgrs = flag.Bool("progress", false, "Force progress showing")
301                 omitPrgrs = flag.Bool("noprogress", false, "Omit progress showing")
302                 debug     = flag.Bool("debug", false, "Print debug messages")
303                 version   = flag.Bool("version", false, "Print version information")
304                 warranty  = flag.Bool("warranty", false, "Print warranty information")
305         )
306         flag.Usage = usage
307         flag.Parse()
308         if *warranty {
309                 fmt.Println(nncp.Warranty)
310                 return
311         }
312         if *version {
313                 fmt.Println(nncp.VersionGet())
314                 return
315         }
316
317         ctx, err := nncp.CtxFromCmdline(
318                 *cfgPath,
319                 *spoolPath,
320                 *logPath,
321                 *quiet,
322                 *showPrgrs,
323                 *omitPrgrs,
324                 *debug,
325         )
326         if err != nil {
327                 log.Fatalln("Error during initialization:", err)
328         }
329
330         var nodeOnly *nncp.Node
331         if *nodeRaw != "" {
332                 nodeOnly, err = ctx.FindNode(*nodeRaw)
333                 if err != nil {
334                         log.Fatalln("Invalid -node specified:", err)
335                 }
336         }
337
338         if !(*allNodes || nodeOnly != nil || flag.NArg() > 0) {
339                 usage()
340                 os.Exit(1)
341         }
342         if flag.NArg() > 0 && (*allNodes || nodeOnly != nil) {
343                 usage()
344                 os.Exit(1)
345         }
346         if *allNodes && nodeOnly != nil {
347                 usage()
348                 os.Exit(1)
349         }
350
351         ctx.Umask()
352
353         if flag.NArg() > 0 {
354                 if process(ctx, flag.Arg(0), *keep, *dryRun, *stdout, *dumpMeta) {
355                         return
356                 }
357                 os.Exit(1)
358         }
359
360         hasErrors := false
361         if nodeOnly == nil {
362                 seenMetaPaths := make(map[string]struct{})
363                 for _, node := range ctx.Neigh {
364                         if node.Incoming == nil {
365                                 continue
366                         }
367                         for _, metaPath := range findMetas(ctx, *node.Incoming) {
368                                 if _, seen := seenMetaPaths[metaPath]; seen {
369                                         continue
370                                 }
371                                 if !process(ctx, metaPath, *keep, *dryRun, false, false) {
372                                         hasErrors = true
373                                 }
374                                 seenMetaPaths[metaPath] = struct{}{}
375                         }
376                 }
377         } else {
378                 if nodeOnly.Incoming == nil {
379                         log.Fatalln("Specified -node does not allow incoming")
380                 }
381                 for _, metaPath := range findMetas(ctx, *nodeOnly.Incoming) {
382                         if !process(ctx, metaPath, *keep, *dryRun, false, false) {
383                                 hasErrors = true
384                         }
385                 }
386         }
387         if hasErrors {
388                 os.Exit(1)
389         }
390 }