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