]> Cypherpunks.ru repositories - nncp.git/blob - src/cypherpunks.ru/nncp/cmd/nncp-reass/main.go
Ability to dump chunked file's metainformation
[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-2017 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 // Send file via NNCP
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.Fprintln(os.Stderr, "nncp-reass -- reassemble chunked files\n")
46         fmt.Fprintf(os.Stderr, "Usage: %s [options] [FILE]\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                 if chunkNum+1 != len(chunksPaths) && uint64(fi.Size()) != metaPkt.ChunkSize {
121                         ctx.LogE("nncp-reass", nncp.SDS{
122                                 "path":  path,
123                                 "chunk": strconv.Itoa(chunkNum),
124                         }, "invalid size")
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                 hsh, err = blake2b.New256(nil)
140                 if err != nil {
141                         log.Fatalln(err)
142                 }
143                 if _, err = io.Copy(hsh, bufio.NewReader(fd)); err != nil {
144                         log.Fatalln(err)
145                 }
146                 fd.Close()
147                 if bytes.Compare(hsh.Sum(nil), metaPkt.Checksums[chunkNum][:]) != 0 {
148                         ctx.LogE("nncp-reass", nncp.SDS{
149                                 "path":  path,
150                                 "chunk": strconv.Itoa(chunkNum),
151                                 "err":   "checksum is bad",
152                         }, "")
153                         allChecksumsGood = false
154                 }
155         }
156         if !allChecksumsGood {
157                 return false
158         }
159         if dryRun {
160                 ctx.LogI("nncp-reass", nncp.SDS{"path": path}, "ready")
161                 return true
162         }
163
164         var dst io.Writer
165         var tmp *os.File
166         var sds nncp.SDS
167         if stdout {
168                 dst = os.Stdout
169                 sds = nncp.SDS{"path": path}
170         } else {
171                 tmp, err = ioutil.TempFile(mainDir, "nncp-reass")
172                 if err != nil {
173                         log.Fatalln(err)
174                 }
175                 sds = nncp.SDS{"path": path, "tmp": tmp.Name()}
176                 ctx.LogD("nncp-reass", sds, "created")
177                 dst = tmp
178         }
179         dstW := bufio.NewWriter(dst)
180
181         hasErrors := false
182         for chunkNum, chunkPath := range chunksPaths {
183                 fd, err = os.Open(chunkPath)
184                 if err != nil {
185                         log.Fatalln("Can not open file:", err)
186                 }
187                 if _, err = io.Copy(dstW, bufio.NewReader(fd)); err != nil {
188                         log.Fatalln(err)
189                 }
190                 fd.Close()
191                 if !keep {
192                         if err = os.Remove(chunkPath); err != nil {
193                                 ctx.LogE("nncp-reass", nncp.SdsAdd(sds, nncp.SDS{
194                                         "chunk": strconv.Itoa(chunkNum),
195                                         "err":   err,
196                                 }), "")
197                                 hasErrors = true
198                         }
199                 }
200         }
201         dstW.Flush()
202         if tmp != nil {
203                 tmp.Sync()
204                 tmp.Close()
205         }
206         ctx.LogD("nncp-reass", sds, "written")
207         if !keep {
208                 if err = os.Remove(path); err != nil {
209                         ctx.LogE("nncp-reass", nncp.SdsAdd(sds, nncp.SDS{"err": err}), "")
210                         hasErrors = true
211                 }
212         }
213         if stdout {
214                 ctx.LogI("nncp-reass", nncp.SDS{"path": path}, "done")
215                 return !hasErrors
216         }
217
218         dstPathOrig := filepath.Join(mainDir, mainName)
219         dstPath := dstPathOrig
220         dstPathCtr := 0
221         for {
222                 if _, err = os.Stat(dstPath); err != nil {
223                         if os.IsNotExist(err) {
224                                 break
225                         }
226                         log.Fatalln(err)
227                 }
228                 dstPath = dstPathOrig + strconv.Itoa(dstPathCtr)
229                 dstPathCtr++
230         }
231         if err = os.Rename(tmp.Name(), dstPath); err != nil {
232                 log.Fatalln(err)
233         }
234         ctx.LogI("nncp-reass", nncp.SDS{"path": path}, "done")
235         return !hasErrors
236 }
237
238 func findMetas(ctx *nncp.Ctx, dirPath string) []string {
239         dir, err := os.Open(dirPath)
240         defer dir.Close()
241         if err != nil {
242                 ctx.LogE("nncp-reass", nncp.SDS{"path": dirPath, "err": err}, "")
243                 return nil
244         }
245         fis, err := dir.Readdir(0)
246         dir.Close()
247         if err != nil {
248                 ctx.LogE("nncp-reass", nncp.SDS{"path": dirPath, "err": err}, "")
249                 return nil
250         }
251         metaPaths := make([]string, 0)
252         for _, fi := range fis {
253                 if strings.HasSuffix(fi.Name(), nncp.ChunkedSuffixMeta) {
254                         metaPaths = append(metaPaths, filepath.Join(dirPath, fi.Name()))
255                 }
256         }
257         return metaPaths
258 }
259
260 func main() {
261         var (
262                 cfgPath  = flag.String("cfg", nncp.DefaultCfgPath, "Path to configuration file")
263                 allNodes = flag.Bool("all", false, "Process all found chunked files for all nodes")
264                 nodeRaw  = flag.String("node", "", "Process all found chunked files for that node")
265                 keep     = flag.Bool("keep", false, "Do not remove chunks while assembling")
266                 dryRun   = flag.Bool("dryrun", false, "Do not assemble whole file")
267                 dumpMeta = flag.Bool("dump", false, "Print decoded human-readable meta FILE")
268                 stdout   = flag.Bool("stdout", false, "Output reassembled FILE to stdout")
269                 quiet    = flag.Bool("quiet", false, "Print only errors")
270                 debug    = flag.Bool("debug", false, "Print debug messages")
271                 version  = flag.Bool("version", false, "Print version information")
272                 warranty = flag.Bool("warranty", false, "Print warranty information")
273         )
274         flag.Usage = usage
275         flag.Parse()
276         if *warranty {
277                 fmt.Println(nncp.Warranty)
278                 return
279         }
280         if *version {
281                 fmt.Println(nncp.VersionGet())
282                 return
283         }
284
285         cfgRaw, err := ioutil.ReadFile(nncp.CfgPathFromEnv(cfgPath))
286         if err != nil {
287                 log.Fatalln("Can not read config:", err)
288         }
289         ctx, err := nncp.CfgParse(cfgRaw)
290         if err != nil {
291                 log.Fatalln("Can not parse config:", err)
292         }
293         ctx.Quiet = *quiet
294         ctx.Debug = *debug
295
296         var nodeOnly *nncp.Node
297         if *nodeRaw != "" {
298                 nodeOnly, err = ctx.FindNode(*nodeRaw)
299                 if err != nil {
300                         log.Fatalln("Invalid -node specified:", err)
301                 }
302         }
303
304         if !(*allNodes || nodeOnly != nil || flag.NArg() > 0) {
305                 usage()
306                 os.Exit(1)
307         }
308         if flag.NArg() > 0 && (*allNodes || nodeOnly != nil) {
309                 usage()
310                 os.Exit(1)
311         }
312         if *allNodes && nodeOnly != nil {
313                 usage()
314                 os.Exit(1)
315         }
316
317         if flag.NArg() > 0 {
318                 if !process(ctx, flag.Arg(0), *keep, *dryRun, *stdout, *dumpMeta) {
319                         os.Exit(1)
320                 }
321                 return
322         }
323
324         hasErrors := false
325         if nodeOnly == nil {
326                 seenMetaPaths := make(map[string]struct{})
327                 for _, node := range ctx.Neigh {
328                         if node.Incoming == nil {
329                                 continue
330                         }
331                         for _, metaPath := range findMetas(ctx, *node.Incoming) {
332                                 if _, seen := seenMetaPaths[metaPath]; seen {
333                                         continue
334                                 }
335                                 hasErrors = hasErrors || !process(ctx, metaPath, *keep, *dryRun, false, false)
336                                 seenMetaPaths[metaPath] = struct{}{}
337                         }
338                 }
339         } else {
340                 if nodeOnly.Incoming == nil {
341                         log.Fatalln("Specified -node does not allow incoming")
342                 }
343                 for _, metaPath := range findMetas(ctx, *nodeOnly.Incoming) {
344                         hasErrors = hasErrors || !process(ctx, metaPath, *keep, *dryRun, false, false)
345                 }
346         }
347         if hasErrors {
348                 os.Exit(1)
349         }
350 }