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