]> Cypherpunks.ru repositories - nncp.git/blob - src/cmd/nncp-reass/main.go
161e86f602ad53961ac2167d503b121f71e0960a
[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         xdr "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         if err = nncp.DirSync(mainDir); err != nil {
242                 log.Fatalln(err)
243         }
244         ctx.LogI("nncp-reass", nncp.SDS{"path": path}, "done")
245         return !hasErrors
246 }
247
248 func findMetas(ctx *nncp.Ctx, dirPath string) []string {
249         dir, err := os.Open(dirPath)
250         defer dir.Close()
251         if err != nil {
252                 ctx.LogE("nncp-reass", nncp.SDS{"path": dirPath, "err": err}, "")
253                 return nil
254         }
255         fis, err := dir.Readdir(0)
256         dir.Close()
257         if err != nil {
258                 ctx.LogE("nncp-reass", nncp.SDS{"path": dirPath, "err": err}, "")
259                 return nil
260         }
261         metaPaths := make([]string, 0)
262         for _, fi := range fis {
263                 if strings.HasSuffix(fi.Name(), nncp.ChunkedSuffixMeta) {
264                         metaPaths = append(metaPaths, filepath.Join(dirPath, fi.Name()))
265                 }
266         }
267         return metaPaths
268 }
269
270 func main() {
271         var (
272                 cfgPath   = flag.String("cfg", nncp.DefaultCfgPath, "Path to configuration file")
273                 allNodes  = flag.Bool("all", false, "Process all found chunked files for all nodes")
274                 nodeRaw   = flag.String("node", "", "Process all found chunked files for that node")
275                 keep      = flag.Bool("keep", false, "Do not remove chunks while assembling")
276                 dryRun    = flag.Bool("dryrun", false, "Do not assemble whole file")
277                 dumpMeta  = flag.Bool("dump", false, "Print decoded human-readable FILE.nncp.meta")
278                 stdout    = flag.Bool("stdout", false, "Output reassembled FILE to stdout")
279                 spoolPath = flag.String("spool", "", "Override path to spool")
280                 logPath   = flag.String("log", "", "Override path to logfile")
281                 quiet     = flag.Bool("quiet", false, "Print only errors")
282                 debug     = flag.Bool("debug", false, "Print debug messages")
283                 version   = flag.Bool("version", false, "Print version information")
284                 warranty  = flag.Bool("warranty", false, "Print warranty information")
285         )
286         flag.Usage = usage
287         flag.Parse()
288         if *warranty {
289                 fmt.Println(nncp.Warranty)
290                 return
291         }
292         if *version {
293                 fmt.Println(nncp.VersionGet())
294                 return
295         }
296
297         ctx, err := nncp.CtxFromCmdline(*cfgPath, *spoolPath, *logPath, *quiet, *debug)
298         if err != nil {
299                 log.Fatalln("Error during initialization:", err)
300         }
301
302         var nodeOnly *nncp.Node
303         if *nodeRaw != "" {
304                 nodeOnly, err = ctx.FindNode(*nodeRaw)
305                 if err != nil {
306                         log.Fatalln("Invalid -node specified:", err)
307                 }
308         }
309
310         if !(*allNodes || nodeOnly != nil || flag.NArg() > 0) {
311                 usage()
312                 os.Exit(1)
313         }
314         if flag.NArg() > 0 && (*allNodes || nodeOnly != nil) {
315                 usage()
316                 os.Exit(1)
317         }
318         if *allNodes && nodeOnly != nil {
319                 usage()
320                 os.Exit(1)
321         }
322
323         ctx.Umask()
324
325         if flag.NArg() > 0 {
326                 if process(ctx, flag.Arg(0), *keep, *dryRun, *stdout, *dumpMeta) {
327                         return
328                 }
329                 os.Exit(1)
330         }
331
332         hasErrors := false
333         if nodeOnly == nil {
334                 seenMetaPaths := make(map[string]struct{})
335                 for _, node := range ctx.Neigh {
336                         if node.Incoming == nil {
337                                 continue
338                         }
339                         for _, metaPath := range findMetas(ctx, *node.Incoming) {
340                                 if _, seen := seenMetaPaths[metaPath]; seen {
341                                         continue
342                                 }
343                                 if !process(ctx, metaPath, *keep, *dryRun, false, false) {
344                                         hasErrors = true
345                                 }
346                                 seenMetaPaths[metaPath] = struct{}{}
347                         }
348                 }
349         } else {
350                 if nodeOnly.Incoming == nil {
351                         log.Fatalln("Specified -node does not allow incoming")
352                 }
353                 for _, metaPath := range findMetas(ctx, *nodeOnly.Incoming) {
354                         if !process(ctx, metaPath, *keep, *dryRun, false, false) {
355                                 hasErrors = true
356                         }
357                 }
358         }
359         if hasErrors {
360                 os.Exit(1)
361         }
362 }