2 NNCP -- Node to Node copy, utilities for store-and-forward data exchange
3 Copyright (C) 2016-2022 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/v8"
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])
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.
52 func process(ctx *nncp.Ctx, path string, keep, dryRun, stdout, dumpMeta bool) bool {
53 fd, err := os.Open(path)
56 log.Fatalln("Can not open file:", err)
58 var metaPkt nncp.ChunkedMeta
59 les := nncp.LEs{{K: "Path", V: path}}
60 logMsg := func(les nncp.LEs) string {
61 return fmt.Sprintf("Reassembling chunked file \"%s\"", path)
63 if _, err = xdr.Unmarshal(fd, &metaPkt); err != nil {
64 ctx.LogE("reass-bad-meta", les, err, func(les nncp.LEs) string {
65 return logMsg(les) + ": bad meta"
70 if metaPkt.Magic == nncp.MagicNNCPMv1.B {
71 ctx.LogE("reass", les, nncp.MagicNNCPMv1.TooOld(), logMsg)
74 if metaPkt.Magic != nncp.MagicNNCPMv2.B {
75 ctx.LogE("reass", les, nncp.BadMagic, logMsg)
79 metaName := filepath.Base(path)
80 if !strings.HasSuffix(metaName, nncp.ChunkedSuffixMeta) {
81 ctx.LogE("reass", les, errors.New("invalid filename suffix"), logMsg)
84 mainName := strings.TrimSuffix(metaName, nncp.ChunkedSuffixMeta)
86 fmt.Printf("Original filename: %s\n", mainName)
88 "File size: %s (%d bytes)\n",
89 humanize.IBytes(metaPkt.FileSize),
93 "Chunk size: %s (%d bytes)\n",
94 humanize.IBytes(metaPkt.ChunkSize),
97 fmt.Printf("Number of chunks: %d\n", len(metaPkt.Checksums))
98 fmt.Println("Checksums:")
99 for chunkNum, checksum := range metaPkt.Checksums {
100 fmt.Printf("\t%d: %s\n", chunkNum, hex.EncodeToString(checksum[:]))
104 mainDir := filepath.Dir(path)
106 chunksPaths := make([]string, 0, len(metaPkt.Checksums))
107 for i := 0; i < len(metaPkt.Checksums); i++ {
108 chunksPaths = append(
110 filepath.Join(mainDir, mainName+nncp.ChunkedSuffixPart+strconv.Itoa(i)),
114 allChunksExist := true
115 for chunkNum, chunkPath := range chunksPaths {
116 fi, err := os.Stat(chunkPath)
117 lesChunk := append(les, nncp.LE{K: "Chunk", V: chunkNum})
118 if err != nil && os.IsNotExist(err) {
119 ctx.LogI("reass-chunk-miss", lesChunk, func(les nncp.LEs) string {
120 return fmt.Sprintf("%s: chunk %d missing", logMsg(les), chunkNum)
122 allChunksExist = false
126 if chunkNum+1 == len(chunksPaths) {
127 badSize = uint64(fi.Size()) != metaPkt.FileSize%metaPkt.ChunkSize
129 badSize = uint64(fi.Size()) != metaPkt.ChunkSize
135 errors.New("invalid size"),
136 func(les nncp.LEs) string {
137 return fmt.Sprintf("%s: chunk %d", logMsg(les), chunkNum)
140 allChunksExist = false
148 allChecksumsGood := true
149 for chunkNum, chunkPath := range chunksPaths {
150 fd, err = os.Open(chunkPath)
152 log.Fatalln("Can not open file:", err)
156 log.Fatalln("Can not stat file:", err)
158 hsh = nncp.MTHNew(fi.Size(), 0)
159 if _, err = nncp.CopyProgressed(
160 hsh, bufio.NewReader(fd), "check",
161 nncp.LEs{{K: "Pkt", V: chunkPath}, {K: "FullSize", V: fi.Size()}},
167 if bytes.Compare(hsh.Sum(nil), metaPkt.Checksums[chunkNum][:]) != 0 {
170 nncp.LEs{{K: "Path", V: path}, {K: "Chunk", V: chunkNum}},
171 errors.New("checksum is bad"),
172 func(les nncp.LEs) string {
173 return fmt.Sprintf("%s: chunk %d", logMsg(les), chunkNum)
176 allChecksumsGood = false
179 if !allChecksumsGood {
183 ctx.LogI("reass", nncp.LEs{{K: "path", V: path}}, logMsg)
191 les = nncp.LEs{{K: "path", V: path}}
193 tmp, err = nncp.TempFile(mainDir, "reass")
197 les = nncp.LEs{{K: "path", V: path}, {K: "Tmp", V: tmp.Name()}}
198 ctx.LogD("reass-tmp-created", les, func(les nncp.LEs) string {
199 return fmt.Sprintf("%s: temporary %s created", logMsg(les), tmp.Name())
203 dstW := bufio.NewWriter(dst)
206 for chunkNum, chunkPath := range chunksPaths {
207 fd, err = os.Open(chunkPath)
209 log.Fatalln("Can not open file:", err)
213 log.Fatalln("Can not stat file:", err)
215 if _, err = nncp.CopyProgressed(
216 dstW, bufio.NewReader(fd), "reass",
217 nncp.LEs{{K: "Pkt", V: chunkPath}, {K: "FullSize", V: fi.Size()}},
224 if err = os.Remove(chunkPath); err != nil {
227 append(les, nncp.LE{K: "Chunk", V: chunkNum}), err,
228 func(les nncp.LEs) string {
229 return fmt.Sprintf("%s: chunk %d", logMsg(les), chunkNum)
236 if err = dstW.Flush(); err != nil {
237 log.Fatalln("Can not flush:", err)
241 if err = tmp.Sync(); err != nil {
242 log.Fatalln("Can not sync:", err)
245 if err = tmp.Close(); err != nil {
246 log.Fatalln("Can not close:", err)
249 ctx.LogD("reass-written", les, func(les nncp.LEs) string {
250 return logMsg(les) + ": written"
253 if err = os.Remove(path); err != nil {
254 ctx.LogE("reass-removing", les, err, func(les nncp.LEs) string {
255 return logMsg(les) + ": removing"
261 ctx.LogI("reass", nncp.LEs{{K: "Path", V: path}}, func(les nncp.LEs) string {
262 return logMsg(les) + ": done"
267 dstPathOrig := filepath.Join(mainDir, mainName)
268 dstPath := dstPathOrig
271 if _, err = os.Stat(dstPath); err != nil {
272 if os.IsNotExist(err) {
277 dstPath = dstPathOrig + "." + strconv.Itoa(dstPathCtr)
280 if err = os.Rename(tmp.Name(), dstPath); err != nil {
283 if err = nncp.DirSync(mainDir); err != nil {
286 ctx.LogI("reass", nncp.LEs{{K: "Path", V: path}}, func(les nncp.LEs) string {
287 return logMsg(les) + ": done"
292 func findMetas(ctx *nncp.Ctx, dirPath string) []string {
293 dir, err := os.Open(dirPath)
295 logMsg := func(les nncp.LEs) string {
296 return "Finding .meta in " + dirPath
299 ctx.LogE("reass", nncp.LEs{{K: "Path", V: dirPath}}, err, logMsg)
302 fis, err := dir.Readdir(0)
305 ctx.LogE("reass", nncp.LEs{{K: "Path", V: dirPath}}, err, logMsg)
308 metaPaths := make([]string, 0)
309 for _, fi := range fis {
310 if strings.HasSuffix(fi.Name(), nncp.ChunkedSuffixMeta) {
311 metaPaths = append(metaPaths, filepath.Join(dirPath, fi.Name()))
319 cfgPath = flag.String("cfg", nncp.DefaultCfgPath, "Path to configuration file")
320 allNodes = flag.Bool("all", false, "Process all found chunked files for all nodes")
321 nodeRaw = flag.String("node", "", "Process all found chunked files for that node")
322 keep = flag.Bool("keep", false, "Do not remove chunks while assembling")
323 dryRun = flag.Bool("dryrun", false, "Do not assemble whole file")
324 dumpMeta = flag.Bool("dump", false, "Print decoded human-readable FILE.nncp.meta")
325 stdout = flag.Bool("stdout", false, "Output reassembled FILE to stdout")
326 spoolPath = flag.String("spool", "", "Override path to spool")
327 logPath = flag.String("log", "", "Override path to logfile")
328 quiet = flag.Bool("quiet", false, "Print only errors")
329 showPrgrs = flag.Bool("progress", false, "Force progress showing")
330 omitPrgrs = flag.Bool("noprogress", false, "Omit progress showing")
331 debug = flag.Bool("debug", false, "Print debug messages")
332 version = flag.Bool("version", false, "Print version information")
333 warranty = flag.Bool("warranty", false, "Print warranty information")
335 log.SetFlags(log.Lshortfile)
339 fmt.Println(nncp.Warranty)
343 fmt.Println(nncp.VersionGet())
347 ctx, err := nncp.CtxFromCmdline(
357 log.Fatalln("Error during initialization:", err)
360 var nodeOnly *nncp.Node
362 nodeOnly, err = ctx.FindNode(*nodeRaw)
364 log.Fatalln("Invalid -node specified:", err)
368 if !(*allNodes || nodeOnly != nil || flag.NArg() > 0) {
372 if flag.NArg() > 0 && (*allNodes || nodeOnly != nil) {
376 if *allNodes && nodeOnly != nil {
384 if process(ctx, flag.Arg(0), *keep, *dryRun, *stdout, *dumpMeta) {
392 seenMetaPaths := make(map[string]struct{})
393 for _, node := range ctx.Neigh {
394 if node.Incoming == nil {
397 for _, metaPath := range findMetas(ctx, *node.Incoming) {
398 if _, seen := seenMetaPaths[metaPath]; seen {
401 if !process(ctx, metaPath, *keep, *dryRun, false, false) {
404 seenMetaPaths[metaPath] = struct{}{}
408 if nodeOnly.Incoming == nil {
409 log.Fatalln("Specified -node does not allow incoming")
411 for _, metaPath := range findMetas(ctx, *nodeOnly.Incoming) {
412 if !process(ctx, metaPath, *keep, *dryRun, false, false) {