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/v5"
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 if _, err = xdr.Unmarshal(fd, &metaPkt); err != nil {
61 ctx.LogE("nncp-reass", nncp.SDS{"path": path}, err, "bad meta file")
64 fd.Close() // #nosec G104
65 if metaPkt.Magic != nncp.MagicNNCPMv1 {
66 ctx.LogE("nncp-reass", nncp.SDS{"path": path}, nncp.BadMagic, "")
70 metaName := filepath.Base(path)
71 if !strings.HasSuffix(metaName, nncp.ChunkedSuffixMeta) {
72 ctx.LogE("nncp-reass", nncp.SDS{"path": path}, errors.New("invalid filename suffix"), "")
75 mainName := strings.TrimSuffix(metaName, nncp.ChunkedSuffixMeta)
77 fmt.Printf("Original filename: %s\n", mainName)
79 "File size: %s (%d bytes)\n",
80 humanize.IBytes(metaPkt.FileSize),
84 "Chunk size: %s (%d bytes)\n",
85 humanize.IBytes(metaPkt.ChunkSize),
88 fmt.Printf("Number of chunks: %d\n", len(metaPkt.Checksums))
89 fmt.Println("Checksums:")
90 for chunkNum, checksum := range metaPkt.Checksums {
91 fmt.Printf("\t%d: %s\n", chunkNum, hex.EncodeToString(checksum[:]))
95 mainDir := filepath.Dir(path)
97 chunksPaths := make([]string, 0, len(metaPkt.Checksums))
98 for i := 0; i < len(metaPkt.Checksums); i++ {
101 filepath.Join(mainDir, mainName+nncp.ChunkedSuffixPart+strconv.Itoa(i)),
105 allChunksExist := true
106 for chunkNum, chunkPath := range chunksPaths {
107 fi, err := os.Stat(chunkPath)
108 if err != nil && os.IsNotExist(err) {
109 ctx.LogI("nncp-reass", nncp.SDS{"path": path, "chunk": chunkNum}, "missing")
110 allChunksExist = false
114 if chunkNum+1 == len(chunksPaths) {
115 badSize = uint64(fi.Size()) != metaPkt.FileSize%metaPkt.ChunkSize
117 badSize = uint64(fi.Size()) != metaPkt.ChunkSize
122 nncp.SDS{"path": path, "chunk": chunkNum},
123 errors.New("invalid size"), "",
125 allChunksExist = false
133 allChecksumsGood := true
134 for chunkNum, chunkPath := range chunksPaths {
135 fd, err = os.Open(chunkPath)
137 log.Fatalln("Can not open file:", err)
141 log.Fatalln("Can not stat file:", err)
143 hsh, err = blake2b.New256(nil)
147 if _, err = nncp.CopyProgressed(
148 hsh, bufio.NewReader(fd), "check",
151 "fullsize": fi.Size(),
157 fd.Close() // #nosec G104
158 if bytes.Compare(hsh.Sum(nil), metaPkt.Checksums[chunkNum][:]) != 0 {
161 nncp.SDS{"path": path, "chunk": chunkNum},
162 errors.New("checksum is bad"), "",
164 allChecksumsGood = false
167 if !allChecksumsGood {
171 ctx.LogI("nncp-reass", nncp.SDS{"path": path}, "ready")
180 sds = nncp.SDS{"path": path}
182 tmp, err = nncp.TempFile(mainDir, "reass")
186 sds = nncp.SDS{"path": path, "tmp": tmp.Name()}
187 ctx.LogD("nncp-reass", sds, "created")
190 dstW := bufio.NewWriter(dst)
193 for chunkNum, chunkPath := range chunksPaths {
194 fd, err = os.Open(chunkPath)
196 log.Fatalln("Can not open file:", err)
200 log.Fatalln("Can not stat file:", err)
202 if _, err = nncp.CopyProgressed(
203 dstW, bufio.NewReader(fd), "reass",
206 "fullsize": fi.Size(),
212 fd.Close() // #nosec G104
214 if err = os.Remove(chunkPath); err != nil {
215 ctx.LogE("nncp-reass", nncp.SdsAdd(sds, nncp.SDS{"chunk": chunkNum}), err, "")
220 if err = dstW.Flush(); err != nil {
221 log.Fatalln("Can not flush:", err)
224 if err = tmp.Sync(); err != nil {
225 log.Fatalln("Can not sync:", err)
227 if err = tmp.Close(); err != nil {
228 log.Fatalln("Can not close:", err)
231 ctx.LogD("nncp-reass", sds, "written")
233 if err = os.Remove(path); err != nil {
234 ctx.LogE("nncp-reass", sds, err, "")
239 ctx.LogI("nncp-reass", nncp.SDS{"path": path}, "done")
243 dstPathOrig := filepath.Join(mainDir, mainName)
244 dstPath := dstPathOrig
247 if _, err = os.Stat(dstPath); err != nil {
248 if os.IsNotExist(err) {
253 dstPath = dstPathOrig + "." + strconv.Itoa(dstPathCtr)
256 if err = os.Rename(tmp.Name(), dstPath); err != nil {
259 if err = nncp.DirSync(mainDir); err != nil {
262 ctx.LogI("nncp-reass", nncp.SDS{"path": path}, "done")
266 func findMetas(ctx *nncp.Ctx, dirPath string) []string {
267 dir, err := os.Open(dirPath)
270 ctx.LogE("nncp-reass", nncp.SDS{"path": dirPath}, err, "")
273 fis, err := dir.Readdir(0)
274 dir.Close() // #nosec G104
276 ctx.LogE("nncp-reass", nncp.SDS{"path": dirPath}, err, "")
279 metaPaths := make([]string, 0)
280 for _, fi := range fis {
281 if strings.HasSuffix(fi.Name(), nncp.ChunkedSuffixMeta) {
282 metaPaths = append(metaPaths, filepath.Join(dirPath, fi.Name()))
290 cfgPath = flag.String("cfg", nncp.DefaultCfgPath, "Path to configuration file")
291 allNodes = flag.Bool("all", false, "Process all found chunked files for all nodes")
292 nodeRaw = flag.String("node", "", "Process all found chunked files for that node")
293 keep = flag.Bool("keep", false, "Do not remove chunks while assembling")
294 dryRun = flag.Bool("dryrun", false, "Do not assemble whole file")
295 dumpMeta = flag.Bool("dump", false, "Print decoded human-readable FILE.nncp.meta")
296 stdout = flag.Bool("stdout", false, "Output reassembled FILE to stdout")
297 spoolPath = flag.String("spool", "", "Override path to spool")
298 logPath = flag.String("log", "", "Override path to logfile")
299 quiet = flag.Bool("quiet", false, "Print only errors")
300 showPrgrs = flag.Bool("progress", false, "Force progress showing")
301 omitPrgrs = flag.Bool("noprogress", false, "Omit progress showing")
302 debug = flag.Bool("debug", false, "Print debug messages")
303 version = flag.Bool("version", false, "Print version information")
304 warranty = flag.Bool("warranty", false, "Print warranty information")
309 fmt.Println(nncp.Warranty)
313 fmt.Println(nncp.VersionGet())
317 ctx, err := nncp.CtxFromCmdline(
327 log.Fatalln("Error during initialization:", err)
330 var nodeOnly *nncp.Node
332 nodeOnly, err = ctx.FindNode(*nodeRaw)
334 log.Fatalln("Invalid -node specified:", err)
338 if !(*allNodes || nodeOnly != nil || flag.NArg() > 0) {
342 if flag.NArg() > 0 && (*allNodes || nodeOnly != nil) {
346 if *allNodes && nodeOnly != nil {
354 if process(ctx, flag.Arg(0), *keep, *dryRun, *stdout, *dumpMeta) {
362 seenMetaPaths := make(map[string]struct{})
363 for _, node := range ctx.Neigh {
364 if node.Incoming == nil {
367 for _, metaPath := range findMetas(ctx, *node.Incoming) {
368 if _, seen := seenMetaPaths[metaPath]; seen {
371 if !process(ctx, metaPath, *keep, *dryRun, false, false) {
374 seenMetaPaths[metaPath] = struct{}{}
378 if nodeOnly.Incoming == nil {
379 log.Fatalln("Specified -node does not allow incoming")
381 for _, metaPath := range findMetas(ctx, *nodeOnly.Incoming) {
382 if !process(ctx, metaPath, *keep, *dryRun, false, false) {