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