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.
37 "github.com/davecgh/go-xdr/xdr2"
38 "github.com/dustin/go-humanize"
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": err}, "bad meta file")
65 if metaPkt.Magic != nncp.MagicNNCPMv1 {
66 ctx.LogE("nncp-reass", nncp.SDS{"path": path, "err": nncp.BadMagic}, "")
70 metaName := filepath.Base(path)
71 if !strings.HasSuffix(metaName, nncp.ChunkedSuffixMeta) {
72 ctx.LogE("nncp-reass", nncp.SDS{
74 "err": "invalid filename suffix",
78 mainName := strings.TrimSuffix(metaName, nncp.ChunkedSuffixMeta)
80 fmt.Printf("Original filename: %s\n", mainName)
82 "File size: %s (%d bytes)\n",
83 humanize.IBytes(metaPkt.FileSize),
87 "Chunk size: %s (%d bytes)\n",
88 humanize.IBytes(metaPkt.ChunkSize),
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[:]))
98 mainDir := filepath.Dir(path)
100 chunksPaths := make([]string, 0, len(metaPkt.Checksums))
101 for i := 0; i < len(metaPkt.Checksums); i++ {
102 chunksPaths = append(
104 filepath.Join(mainDir, mainName+nncp.ChunkedSuffixPart+strconv.Itoa(i)),
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{
114 "chunk": strconv.Itoa(chunkNum),
116 allChunksExist = false
120 if chunkNum+1 == len(chunksPaths) {
121 badSize = uint64(fi.Size()) != metaPkt.FileSize%metaPkt.ChunkSize
123 badSize = uint64(fi.Size()) != metaPkt.ChunkSize
126 ctx.LogE("nncp-reass", nncp.SDS{
128 "chunk": strconv.Itoa(chunkNum),
130 allChunksExist = false
138 allChecksumsGood := true
139 for chunkNum, chunkPath := range chunksPaths {
140 fd, err = os.Open(chunkPath)
142 log.Fatalln("Can not open file:", err)
144 hsh, err = blake2b.New256(nil)
148 if _, err = io.Copy(hsh, bufio.NewReader(fd)); err != nil {
152 if bytes.Compare(hsh.Sum(nil), metaPkt.Checksums[chunkNum][:]) != 0 {
153 ctx.LogE("nncp-reass", nncp.SDS{
155 "chunk": strconv.Itoa(chunkNum),
156 }, "checksum is bad")
157 allChecksumsGood = false
160 if !allChecksumsGood {
164 ctx.LogI("nncp-reass", nncp.SDS{"path": path}, "ready")
173 sds = nncp.SDS{"path": path}
175 tmp, err = ioutil.TempFile(mainDir, "nncp-reass")
179 sds = nncp.SDS{"path": path, "tmp": tmp.Name()}
180 ctx.LogD("nncp-reass", sds, "created")
183 dstW := bufio.NewWriter(dst)
186 for chunkNum, chunkPath := range chunksPaths {
187 fd, err = os.Open(chunkPath)
189 log.Fatalln("Can not open file:", err)
191 if _, err = io.Copy(dstW, bufio.NewReader(fd)); err != nil {
196 if err = os.Remove(chunkPath); err != nil {
197 ctx.LogE("nncp-reass", nncp.SdsAdd(sds, nncp.SDS{
198 "chunk": strconv.Itoa(chunkNum),
205 if err = dstW.Flush(); err != nil {
206 log.Fatalln("Can not flush:", err)
209 if err = tmp.Sync(); err != nil {
210 log.Fatalln("Can not sync:", err)
214 ctx.LogD("nncp-reass", sds, "written")
216 if err = os.Remove(path); err != nil {
217 ctx.LogE("nncp-reass", nncp.SdsAdd(sds, nncp.SDS{"err": err}), "")
222 ctx.LogI("nncp-reass", nncp.SDS{"path": path}, "done")
226 dstPathOrig := filepath.Join(mainDir, mainName)
227 dstPath := dstPathOrig
230 if _, err = os.Stat(dstPath); err != nil {
231 if os.IsNotExist(err) {
236 dstPath = dstPathOrig + strconv.Itoa(dstPathCtr)
239 if err = os.Rename(tmp.Name(), dstPath); err != nil {
242 ctx.LogI("nncp-reass", nncp.SDS{"path": path}, "done")
246 func findMetas(ctx *nncp.Ctx, dirPath string) []string {
247 dir, err := os.Open(dirPath)
250 ctx.LogE("nncp-reass", nncp.SDS{"path": dirPath, "err": err}, "")
253 fis, err := dir.Readdir(0)
256 ctx.LogE("nncp-reass", nncp.SDS{"path": dirPath, "err": err}, "")
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()))
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")
287 fmt.Println(nncp.Warranty)
291 fmt.Println(nncp.VersionGet())
295 ctx, err := nncp.CtxFromCmdline(*cfgPath, *spoolPath, *logPath, *quiet, *debug)
297 log.Fatalln("Error during initialization:", err)
300 var nodeOnly *nncp.Node
302 nodeOnly, err = ctx.FindNode(*nodeRaw)
304 log.Fatalln("Invalid -node specified:", err)
308 if !(*allNodes || nodeOnly != nil || flag.NArg() > 0) {
312 if flag.NArg() > 0 && (*allNodes || nodeOnly != nil) {
316 if *allNodes && nodeOnly != nil {
322 if process(ctx, flag.Arg(0), *keep, *dryRun, *stdout, *dumpMeta) {
330 seenMetaPaths := make(map[string]struct{})
331 for _, node := range ctx.Neigh {
332 if node.Incoming == nil {
335 for _, metaPath := range findMetas(ctx, *node.Incoming) {
336 if _, seen := seenMetaPaths[metaPath]; seen {
339 if !process(ctx, metaPath, *keep, *dryRun, false, false) {
342 seenMetaPaths[metaPath] = struct{}{}
346 if nodeOnly.Incoming == nil {
347 log.Fatalln("Specified -node does not allow incoming")
349 for _, metaPath := range findMetas(ctx, *nodeOnly.Incoming) {
350 if !process(ctx, metaPath, *keep, *dryRun, false, false) {