2 NNCP -- Node to Node copy, utilities for store-and-forward data exchange
3 Copyright (C) 2016-2021 Sergey Matveev <stargrave@stargrave.org>
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.
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.
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/>.
18 // Reassembly chunked file.
36 xdr "github.com/davecgh/go-xdr/xdr2"
37 "github.com/dustin/go-humanize"
38 "go.cypherpunks.ru/nncp/v6"
39 "golang.org/x/crypto/blake2b"
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])
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.
53 func process(ctx *nncp.Ctx, path string, keep, dryRun, stdout, dumpMeta bool) bool {
54 fd, err := os.Open(path)
57 log.Fatalln("Can not open file:", err)
59 var metaPkt nncp.ChunkedMeta
60 les := nncp.LEs{{K: "Path", V: path}}
61 if _, err = xdr.Unmarshal(fd, &metaPkt); err != nil {
62 ctx.LogE("nncp-reass", les, err, "bad meta file")
65 fd.Close() // #nosec G104
66 if metaPkt.Magic != nncp.MagicNNCPMv1 {
67 ctx.LogE("nncp-reass", les, nncp.BadMagic, "")
71 metaName := filepath.Base(path)
72 if !strings.HasSuffix(metaName, nncp.ChunkedSuffixMeta) {
73 ctx.LogE("nncp-reass", les, errors.New("invalid filename suffix"), "")
76 mainName := strings.TrimSuffix(metaName, nncp.ChunkedSuffixMeta)
78 fmt.Printf("Original filename: %s\n", mainName)
80 "File size: %s (%d bytes)\n",
81 humanize.IBytes(metaPkt.FileSize),
85 "Chunk size: %s (%d bytes)\n",
86 humanize.IBytes(metaPkt.ChunkSize),
89 fmt.Printf("Number of chunks: %d\n", len(metaPkt.Checksums))
90 fmt.Println("Checksums:")
91 for chunkNum, checksum := range metaPkt.Checksums {
92 fmt.Printf("\t%d: %s\n", chunkNum, hex.EncodeToString(checksum[:]))
96 mainDir := filepath.Dir(path)
98 chunksPaths := make([]string, 0, len(metaPkt.Checksums))
99 for i := 0; i < len(metaPkt.Checksums); i++ {
100 chunksPaths = append(
102 filepath.Join(mainDir, mainName+nncp.ChunkedSuffixPart+strconv.Itoa(i)),
106 allChunksExist := true
107 for chunkNum, chunkPath := range chunksPaths {
108 fi, err := os.Stat(chunkPath)
109 lesChunk := append(les, nncp.LE{K: "Chunk", V: chunkNum})
110 if err != nil && os.IsNotExist(err) {
111 ctx.LogI("nncp-reass", lesChunk, "missing")
112 allChunksExist = false
116 if chunkNum+1 == len(chunksPaths) {
117 badSize = uint64(fi.Size()) != metaPkt.FileSize%metaPkt.ChunkSize
119 badSize = uint64(fi.Size()) != metaPkt.ChunkSize
122 ctx.LogE("nncp-reass", lesChunk, errors.New("invalid size"), "")
123 allChunksExist = false
131 allChecksumsGood := true
132 for chunkNum, chunkPath := range chunksPaths {
133 fd, err = os.Open(chunkPath)
135 log.Fatalln("Can not open file:", err)
139 log.Fatalln("Can not stat file:", err)
141 hsh, err = blake2b.New256(nil)
145 if _, err = nncp.CopyProgressed(
146 hsh, bufio.NewReader(fd), "check",
148 {K: "Pkt", V: chunkPath},
149 {K: "FullSize", V: fi.Size()},
155 fd.Close() // #nosec G104
156 if bytes.Compare(hsh.Sum(nil), metaPkt.Checksums[chunkNum][:]) != 0 {
159 nncp.LEs{{K: "Path", V: path}, {K: "Chunk", V: chunkNum}},
160 errors.New("checksum is bad"), "",
162 allChecksumsGood = false
165 if !allChecksumsGood {
169 ctx.LogI("nncp-reass", nncp.LEs{{K: "path", V: path}}, "ready")
177 les = nncp.LEs{{K: "path", V: path}}
179 tmp, err = nncp.TempFile(mainDir, "reass")
183 les = nncp.LEs{{K: "path", V: path}, {K: "Tmp", V: tmp.Name()}}
184 ctx.LogD("nncp-reass", les, "created")
187 dstW := bufio.NewWriter(dst)
190 for chunkNum, chunkPath := range chunksPaths {
191 fd, err = os.Open(chunkPath)
193 log.Fatalln("Can not open file:", err)
197 log.Fatalln("Can not stat file:", err)
199 if _, err = nncp.CopyProgressed(
200 dstW, bufio.NewReader(fd), "reass",
202 {K: "Pkt", V: chunkPath},
203 {K: "FullSize", V: fi.Size()},
209 fd.Close() // #nosec G104
211 if err = os.Remove(chunkPath); err != nil {
212 ctx.LogE("nncp-reass", append(les, nncp.LE{K: "Chunk", V: chunkNum}), err, "")
217 if err = dstW.Flush(); err != nil {
218 log.Fatalln("Can not flush:", err)
221 if err = tmp.Sync(); err != nil {
222 log.Fatalln("Can not sync:", err)
224 if err = tmp.Close(); err != nil {
225 log.Fatalln("Can not close:", err)
228 ctx.LogD("nncp-reass", les, "written")
230 if err = os.Remove(path); err != nil {
231 ctx.LogE("nncp-reass", les, err, "")
236 ctx.LogI("nncp-reass", nncp.LEs{{K: "Path", V: path}}, "done")
240 dstPathOrig := filepath.Join(mainDir, mainName)
241 dstPath := dstPathOrig
244 if _, err = os.Stat(dstPath); err != nil {
245 if os.IsNotExist(err) {
250 dstPath = dstPathOrig + "." + strconv.Itoa(dstPathCtr)
253 if err = os.Rename(tmp.Name(), dstPath); err != nil {
256 if err = nncp.DirSync(mainDir); err != nil {
259 ctx.LogI("nncp-reass", nncp.LEs{{K: "Path", V: path}}, "done")
263 func findMetas(ctx *nncp.Ctx, dirPath string) []string {
264 dir, err := os.Open(dirPath)
267 ctx.LogE("nncp-reass", nncp.LEs{{K: "Path", V: dirPath}}, err, "")
270 fis, err := dir.Readdir(0)
271 dir.Close() // #nosec G104
273 ctx.LogE("nncp-reass", nncp.LEs{{K: "Path", V: dirPath}}, err, "")
276 metaPaths := make([]string, 0)
277 for _, fi := range fis {
278 if strings.HasSuffix(fi.Name(), nncp.ChunkedSuffixMeta) {
279 metaPaths = append(metaPaths, filepath.Join(dirPath, fi.Name()))
287 cfgPath = flag.String("cfg", nncp.DefaultCfgPath, "Path to configuration file")
288 allNodes = flag.Bool("all", false, "Process all found chunked files for all nodes")
289 nodeRaw = flag.String("node", "", "Process all found chunked files for that node")
290 keep = flag.Bool("keep", false, "Do not remove chunks while assembling")
291 dryRun = flag.Bool("dryrun", false, "Do not assemble whole file")
292 dumpMeta = flag.Bool("dump", false, "Print decoded human-readable FILE.nncp.meta")
293 stdout = flag.Bool("stdout", false, "Output reassembled FILE to stdout")
294 spoolPath = flag.String("spool", "", "Override path to spool")
295 logPath = flag.String("log", "", "Override path to logfile")
296 quiet = flag.Bool("quiet", false, "Print only errors")
297 showPrgrs = flag.Bool("progress", false, "Force progress showing")
298 omitPrgrs = flag.Bool("noprogress", false, "Omit progress showing")
299 debug = flag.Bool("debug", false, "Print debug messages")
300 version = flag.Bool("version", false, "Print version information")
301 warranty = flag.Bool("warranty", false, "Print warranty information")
306 fmt.Println(nncp.Warranty)
310 fmt.Println(nncp.VersionGet())
314 ctx, err := nncp.CtxFromCmdline(
324 log.Fatalln("Error during initialization:", err)
327 var nodeOnly *nncp.Node
329 nodeOnly, err = ctx.FindNode(*nodeRaw)
331 log.Fatalln("Invalid -node specified:", err)
335 if !(*allNodes || nodeOnly != nil || flag.NArg() > 0) {
339 if flag.NArg() > 0 && (*allNodes || nodeOnly != nil) {
343 if *allNodes && nodeOnly != nil {
351 if process(ctx, flag.Arg(0), *keep, *dryRun, *stdout, *dumpMeta) {
359 seenMetaPaths := make(map[string]struct{})
360 for _, node := range ctx.Neigh {
361 if node.Incoming == nil {
364 for _, metaPath := range findMetas(ctx, *node.Incoming) {
365 if _, seen := seenMetaPaths[metaPath]; seen {
368 if !process(ctx, metaPath, *keep, *dryRun, false, false) {
371 seenMetaPaths[metaPath] = struct{}{}
375 if nodeOnly.Incoming == nil {
376 log.Fatalln("Specified -node does not allow incoming")
378 for _, metaPath := range findMetas(ctx, *nodeOnly.Incoming) {
379 if !process(ctx, metaPath, *keep, *dryRun, false, false) {