2 NNCP -- Node to Node copy, utilities for store-and-forward data exchange
3 Copyright (C) 2016-2019 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")
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(hsh, bufio.NewReader(fd), nncp.SDS{
149 "fullsize": fi.Size(),
150 }, ctx.ShowPrgrs); err != nil {
154 if bytes.Compare(hsh.Sum(nil), metaPkt.Checksums[chunkNum][:]) != 0 {
157 nncp.SDS{"path": path, "chunk": chunkNum},
158 errors.New("checksum is bad"), "",
160 allChecksumsGood = false
163 if !allChecksumsGood {
167 ctx.LogI("nncp-reass", nncp.SDS{"path": path}, "ready")
176 sds = nncp.SDS{"path": path}
178 tmp, err = nncp.TempFile(mainDir, "reass")
182 sds = nncp.SDS{"path": path, "tmp": tmp.Name()}
183 ctx.LogD("nncp-reass", sds, "created")
186 dstW := bufio.NewWriter(dst)
189 for chunkNum, chunkPath := range chunksPaths {
190 fd, err = os.Open(chunkPath)
192 log.Fatalln("Can not open file:", err)
196 log.Fatalln("Can not stat file:", err)
198 if _, err = nncp.CopyProgressed(dstW, bufio.NewReader(fd), nncp.SDS{
200 "fullsize": fi.Size(),
201 }, ctx.ShowPrgrs); err != nil {
206 if err = os.Remove(chunkPath); err != nil {
207 ctx.LogE("nncp-reass", nncp.SdsAdd(sds, nncp.SDS{"chunk": chunkNum}), err, "")
212 if err = dstW.Flush(); err != nil {
213 log.Fatalln("Can not flush:", err)
216 if err = tmp.Sync(); err != nil {
217 log.Fatalln("Can not sync:", err)
221 ctx.LogD("nncp-reass", sds, "written")
223 if err = os.Remove(path); err != nil {
224 ctx.LogE("nncp-reass", sds, err, "")
229 ctx.LogI("nncp-reass", nncp.SDS{"path": path}, "done")
233 dstPathOrig := filepath.Join(mainDir, mainName)
234 dstPath := dstPathOrig
237 if _, err = os.Stat(dstPath); err != nil {
238 if os.IsNotExist(err) {
243 dstPath = dstPathOrig + "." + strconv.Itoa(dstPathCtr)
246 if err = os.Rename(tmp.Name(), dstPath); err != nil {
249 if err = nncp.DirSync(mainDir); err != nil {
252 ctx.LogI("nncp-reass", nncp.SDS{"path": path}, "done")
256 func findMetas(ctx *nncp.Ctx, dirPath string) []string {
257 dir, err := os.Open(dirPath)
260 ctx.LogE("nncp-reass", nncp.SDS{"path": dirPath}, err, "")
263 fis, err := dir.Readdir(0)
266 ctx.LogE("nncp-reass", nncp.SDS{"path": dirPath}, err, "")
269 metaPaths := make([]string, 0)
270 for _, fi := range fis {
271 if strings.HasSuffix(fi.Name(), nncp.ChunkedSuffixMeta) {
272 metaPaths = append(metaPaths, filepath.Join(dirPath, fi.Name()))
280 cfgPath = flag.String("cfg", nncp.DefaultCfgPath, "Path to configuration file")
281 allNodes = flag.Bool("all", false, "Process all found chunked files for all nodes")
282 nodeRaw = flag.String("node", "", "Process all found chunked files for that node")
283 keep = flag.Bool("keep", false, "Do not remove chunks while assembling")
284 dryRun = flag.Bool("dryrun", false, "Do not assemble whole file")
285 dumpMeta = flag.Bool("dump", false, "Print decoded human-readable FILE.nncp.meta")
286 stdout = flag.Bool("stdout", false, "Output reassembled FILE to stdout")
287 spoolPath = flag.String("spool", "", "Override path to spool")
288 logPath = flag.String("log", "", "Override path to logfile")
289 quiet = flag.Bool("quiet", false, "Print only errors")
290 showPrgrs = flag.Bool("progress", false, "Force progress showing")
291 omitPrgrs = flag.Bool("noprogress", false, "Omit progress showing")
292 debug = flag.Bool("debug", false, "Print debug messages")
293 version = flag.Bool("version", false, "Print version information")
294 warranty = flag.Bool("warranty", false, "Print warranty information")
299 fmt.Println(nncp.Warranty)
303 fmt.Println(nncp.VersionGet())
307 ctx, err := nncp.CtxFromCmdline(
317 log.Fatalln("Error during initialization:", err)
320 var nodeOnly *nncp.Node
322 nodeOnly, err = ctx.FindNode(*nodeRaw)
324 log.Fatalln("Invalid -node specified:", err)
328 if !(*allNodes || nodeOnly != nil || flag.NArg() > 0) {
332 if flag.NArg() > 0 && (*allNodes || nodeOnly != nil) {
336 if *allNodes && nodeOnly != nil {
344 if process(ctx, flag.Arg(0), *keep, *dryRun, *stdout, *dumpMeta) {
352 seenMetaPaths := make(map[string]struct{})
353 for _, node := range ctx.Neigh {
354 if node.Incoming == nil {
357 for _, metaPath := range findMetas(ctx, *node.Incoming) {
358 if _, seen := seenMetaPaths[metaPath]; seen {
361 if !process(ctx, metaPath, *keep, *dryRun, false, false) {
364 seenMetaPaths[metaPath] = struct{}{}
368 if nodeOnly.Incoming == nil {
369 log.Fatalln("Specified -node does not allow incoming")
371 for _, metaPath := range findMetas(ctx, *nodeOnly.Incoming) {
372 if !process(ctx, metaPath, *keep, *dryRun, false, false) {