]> Cypherpunks.ru repositories - nncp.git/blob - src/cmd/nncp-reass/main.go
Operations progress
[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(hsh, bufio.NewReader(fd), nncp.SDS{
148                         "pkt":      chunkPath,
149                         "fullsize": fi.Size(),
150                 }, ctx.ShowPrgrs); err != nil {
151                         log.Fatalln(err)
152                 }
153                 fd.Close()
154                 if bytes.Compare(hsh.Sum(nil), metaPkt.Checksums[chunkNum][:]) != 0 {
155                         ctx.LogE(
156                                 "nncp-reass",
157                                 nncp.SDS{"path": path, "chunk": chunkNum},
158                                 errors.New("checksum is bad"), "",
159                         )
160                         allChecksumsGood = false
161                 }
162         }
163         if !allChecksumsGood {
164                 return false
165         }
166         if dryRun {
167                 ctx.LogI("nncp-reass", nncp.SDS{"path": path}, "ready")
168                 return true
169         }
170
171         var dst io.Writer
172         var tmp *os.File
173         var sds nncp.SDS
174         if stdout {
175                 dst = os.Stdout
176                 sds = nncp.SDS{"path": path}
177         } else {
178                 tmp, err = nncp.TempFile(mainDir, "reass")
179                 if err != nil {
180                         log.Fatalln(err)
181                 }
182                 sds = nncp.SDS{"path": path, "tmp": tmp.Name()}
183                 ctx.LogD("nncp-reass", sds, "created")
184                 dst = tmp
185         }
186         dstW := bufio.NewWriter(dst)
187
188         hasErrors := false
189         for chunkNum, chunkPath := range chunksPaths {
190                 fd, err = os.Open(chunkPath)
191                 if err != nil {
192                         log.Fatalln("Can not open file:", err)
193                 }
194                 fi, err := fd.Stat()
195                 if err != nil {
196                         log.Fatalln("Can not stat file:", err)
197                 }
198                 if _, err = nncp.CopyProgressed(dstW, bufio.NewReader(fd), nncp.SDS{
199                         "pkt":      chunkPath,
200                         "fullsize": fi.Size(),
201                 }, ctx.ShowPrgrs); err != nil {
202                         log.Fatalln(err)
203                 }
204                 fd.Close()
205                 if !keep {
206                         if err = os.Remove(chunkPath); err != nil {
207                                 ctx.LogE("nncp-reass", nncp.SdsAdd(sds, nncp.SDS{"chunk": chunkNum}), err, "")
208                                 hasErrors = true
209                         }
210                 }
211         }
212         if err = dstW.Flush(); err != nil {
213                 log.Fatalln("Can not flush:", err)
214         }
215         if tmp != nil {
216                 if err = tmp.Sync(); err != nil {
217                         log.Fatalln("Can not sync:", err)
218                 }
219                 tmp.Close()
220         }
221         ctx.LogD("nncp-reass", sds, "written")
222         if !keep {
223                 if err = os.Remove(path); err != nil {
224                         ctx.LogE("nncp-reass", sds, err, "")
225                         hasErrors = true
226                 }
227         }
228         if stdout {
229                 ctx.LogI("nncp-reass", nncp.SDS{"path": path}, "done")
230                 return !hasErrors
231         }
232
233         dstPathOrig := filepath.Join(mainDir, mainName)
234         dstPath := dstPathOrig
235         dstPathCtr := 0
236         for {
237                 if _, err = os.Stat(dstPath); err != nil {
238                         if os.IsNotExist(err) {
239                                 break
240                         }
241                         log.Fatalln(err)
242                 }
243                 dstPath = dstPathOrig + "." + strconv.Itoa(dstPathCtr)
244                 dstPathCtr++
245         }
246         if err = os.Rename(tmp.Name(), dstPath); err != nil {
247                 log.Fatalln(err)
248         }
249         if err = nncp.DirSync(mainDir); err != nil {
250                 log.Fatalln(err)
251         }
252         ctx.LogI("nncp-reass", nncp.SDS{"path": path}, "done")
253         return !hasErrors
254 }
255
256 func findMetas(ctx *nncp.Ctx, dirPath string) []string {
257         dir, err := os.Open(dirPath)
258         defer dir.Close()
259         if err != nil {
260                 ctx.LogE("nncp-reass", nncp.SDS{"path": dirPath}, err, "")
261                 return nil
262         }
263         fis, err := dir.Readdir(0)
264         dir.Close()
265         if err != nil {
266                 ctx.LogE("nncp-reass", nncp.SDS{"path": dirPath}, err, "")
267                 return nil
268         }
269         metaPaths := make([]string, 0)
270         for _, fi := range fis {
271                 if strings.HasSuffix(fi.Name(), nncp.ChunkedSuffixMeta) {
272                         metaPaths = append(metaPaths, filepath.Join(dirPath, fi.Name()))
273                 }
274         }
275         return metaPaths
276 }
277
278 func main() {
279         var (
280                 cfgPath   = flag.String("cfg", nncp.DefaultCfgPath, "Path to configuration file")
281                 allNodes  = flag.Bool("all", false, "Process all found chunked files for all nodes")
282                 nodeRaw   = flag.String("node", "", "Process all found chunked files for that node")
283                 keep      = flag.Bool("keep", false, "Do not remove chunks while assembling")
284                 dryRun    = flag.Bool("dryrun", false, "Do not assemble whole file")
285                 dumpMeta  = flag.Bool("dump", false, "Print decoded human-readable FILE.nncp.meta")
286                 stdout    = flag.Bool("stdout", false, "Output reassembled FILE to stdout")
287                 spoolPath = flag.String("spool", "", "Override path to spool")
288                 logPath   = flag.String("log", "", "Override path to logfile")
289                 quiet     = flag.Bool("quiet", false, "Print only errors")
290                 showPrgrs = flag.Bool("progress", false, "Force progress showing")
291                 omitPrgrs = flag.Bool("noprogress", false, "Omit progress showing")
292                 debug     = flag.Bool("debug", false, "Print debug messages")
293                 version   = flag.Bool("version", false, "Print version information")
294                 warranty  = flag.Bool("warranty", false, "Print warranty information")
295         )
296         flag.Usage = usage
297         flag.Parse()
298         if *warranty {
299                 fmt.Println(nncp.Warranty)
300                 return
301         }
302         if *version {
303                 fmt.Println(nncp.VersionGet())
304                 return
305         }
306
307         ctx, err := nncp.CtxFromCmdline(
308                 *cfgPath,
309                 *spoolPath,
310                 *logPath,
311                 *quiet,
312                 *showPrgrs,
313                 *omitPrgrs,
314                 *debug,
315         )
316         if err != nil {
317                 log.Fatalln("Error during initialization:", err)
318         }
319
320         var nodeOnly *nncp.Node
321         if *nodeRaw != "" {
322                 nodeOnly, err = ctx.FindNode(*nodeRaw)
323                 if err != nil {
324                         log.Fatalln("Invalid -node specified:", err)
325                 }
326         }
327
328         if !(*allNodes || nodeOnly != nil || flag.NArg() > 0) {
329                 usage()
330                 os.Exit(1)
331         }
332         if flag.NArg() > 0 && (*allNodes || nodeOnly != nil) {
333                 usage()
334                 os.Exit(1)
335         }
336         if *allNodes && nodeOnly != nil {
337                 usage()
338                 os.Exit(1)
339         }
340
341         ctx.Umask()
342
343         if flag.NArg() > 0 {
344                 if process(ctx, flag.Arg(0), *keep, *dryRun, *stdout, *dumpMeta) {
345                         return
346                 }
347                 os.Exit(1)
348         }
349
350         hasErrors := false
351         if nodeOnly == nil {
352                 seenMetaPaths := make(map[string]struct{})
353                 for _, node := range ctx.Neigh {
354                         if node.Incoming == nil {
355                                 continue
356                         }
357                         for _, metaPath := range findMetas(ctx, *node.Incoming) {
358                                 if _, seen := seenMetaPaths[metaPath]; seen {
359                                         continue
360                                 }
361                                 if !process(ctx, metaPath, *keep, *dryRun, false, false) {
362                                         hasErrors = true
363                                 }
364                                 seenMetaPaths[metaPath] = struct{}{}
365                         }
366                 }
367         } else {
368                 if nodeOnly.Incoming == nil {
369                         log.Fatalln("Specified -node does not allow incoming")
370                 }
371                 for _, metaPath := range findMetas(ctx, *nodeOnly.Incoming) {
372                         if !process(ctx, metaPath, *keep, *dryRun, false, false) {
373                                 hasErrors = true
374                         }
375                 }
376         }
377         if hasErrors {
378                 os.Exit(1)
379         }
380 }