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