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.
35 xdr "github.com/davecgh/go-xdr/xdr2"
36 "github.com/dustin/go-humanize"
37 "go.cypherpunks.ru/nncp/v5"
38 "golang.org/x/crypto/blake2b"
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 if _, err = xdr.Unmarshal(fd, &metaPkt); err != nil {
60 ctx.LogE("nncp-reass", nncp.SDS{"path": path, "err": err}, "bad meta file")
64 if metaPkt.Magic != nncp.MagicNNCPMv1 {
65 ctx.LogE("nncp-reass", nncp.SDS{"path": path, "err": nncp.BadMagic}, "")
69 metaName := filepath.Base(path)
70 if !strings.HasSuffix(metaName, nncp.ChunkedSuffixMeta) {
71 ctx.LogE("nncp-reass", nncp.SDS{
73 "err": "invalid filename suffix",
77 mainName := strings.TrimSuffix(metaName, nncp.ChunkedSuffixMeta)
79 fmt.Printf("Original filename: %s\n", mainName)
81 "File size: %s (%d bytes)\n",
82 humanize.IBytes(metaPkt.FileSize),
86 "Chunk size: %s (%d bytes)\n",
87 humanize.IBytes(metaPkt.ChunkSize),
90 fmt.Printf("Number of chunks: %d\n", len(metaPkt.Checksums))
91 fmt.Println("Checksums:")
92 for chunkNum, checksum := range metaPkt.Checksums {
93 fmt.Printf("\t%d: %s\n", chunkNum, hex.EncodeToString(checksum[:]))
97 mainDir := filepath.Dir(path)
99 chunksPaths := make([]string, 0, len(metaPkt.Checksums))
100 for i := 0; i < len(metaPkt.Checksums); i++ {
101 chunksPaths = append(
103 filepath.Join(mainDir, mainName+nncp.ChunkedSuffixPart+strconv.Itoa(i)),
107 allChunksExist := true
108 for chunkNum, chunkPath := range chunksPaths {
109 fi, err := os.Stat(chunkPath)
110 if err != nil && os.IsNotExist(err) {
111 ctx.LogI("nncp-reass", nncp.SDS{
113 "chunk": strconv.Itoa(chunkNum),
115 allChunksExist = false
119 if chunkNum+1 == len(chunksPaths) {
120 badSize = uint64(fi.Size()) != metaPkt.FileSize%metaPkt.ChunkSize
122 badSize = uint64(fi.Size()) != metaPkt.ChunkSize
125 ctx.LogE("nncp-reass", nncp.SDS{
127 "chunk": strconv.Itoa(chunkNum),
129 allChunksExist = false
137 allChecksumsGood := true
138 for chunkNum, chunkPath := range chunksPaths {
139 fd, err = os.Open(chunkPath)
141 log.Fatalln("Can not open file:", err)
143 hsh, err = blake2b.New256(nil)
147 if _, err = io.Copy(hsh, bufio.NewReader(fd)); err != nil {
151 if bytes.Compare(hsh.Sum(nil), metaPkt.Checksums[chunkNum][:]) != 0 {
152 ctx.LogE("nncp-reass", nncp.SDS{
154 "chunk": strconv.Itoa(chunkNum),
155 }, "checksum is bad")
156 allChecksumsGood = false
159 if !allChecksumsGood {
163 ctx.LogI("nncp-reass", nncp.SDS{"path": path}, "ready")
172 sds = nncp.SDS{"path": path}
174 tmp, err = nncp.TempFile(mainDir, "reass")
178 sds = nncp.SDS{"path": path, "tmp": tmp.Name()}
179 ctx.LogD("nncp-reass", sds, "created")
182 dstW := bufio.NewWriter(dst)
185 for chunkNum, chunkPath := range chunksPaths {
186 fd, err = os.Open(chunkPath)
188 log.Fatalln("Can not open file:", err)
190 if _, err = io.Copy(dstW, bufio.NewReader(fd)); err != nil {
195 if err = os.Remove(chunkPath); err != nil {
196 ctx.LogE("nncp-reass", nncp.SdsAdd(sds, nncp.SDS{
197 "chunk": strconv.Itoa(chunkNum),
204 if err = dstW.Flush(); err != nil {
205 log.Fatalln("Can not flush:", err)
208 if err = tmp.Sync(); err != nil {
209 log.Fatalln("Can not sync:", err)
213 ctx.LogD("nncp-reass", sds, "written")
215 if err = os.Remove(path); err != nil {
216 ctx.LogE("nncp-reass", nncp.SdsAdd(sds, nncp.SDS{"err": err}), "")
221 ctx.LogI("nncp-reass", nncp.SDS{"path": path}, "done")
225 dstPathOrig := filepath.Join(mainDir, mainName)
226 dstPath := dstPathOrig
229 if _, err = os.Stat(dstPath); err != nil {
230 if os.IsNotExist(err) {
235 dstPath = dstPathOrig + "." + strconv.Itoa(dstPathCtr)
238 if err = os.Rename(tmp.Name(), dstPath); err != nil {
241 if err = nncp.DirSync(mainDir); err != nil {
244 ctx.LogI("nncp-reass", nncp.SDS{"path": path}, "done")
248 func findMetas(ctx *nncp.Ctx, dirPath string) []string {
249 dir, err := os.Open(dirPath)
252 ctx.LogE("nncp-reass", nncp.SDS{"path": dirPath, "err": err}, "")
255 fis, err := dir.Readdir(0)
258 ctx.LogE("nncp-reass", nncp.SDS{"path": dirPath, "err": err}, "")
261 metaPaths := make([]string, 0)
262 for _, fi := range fis {
263 if strings.HasSuffix(fi.Name(), nncp.ChunkedSuffixMeta) {
264 metaPaths = append(metaPaths, filepath.Join(dirPath, fi.Name()))
272 cfgPath = flag.String("cfg", nncp.DefaultCfgPath, "Path to configuration file")
273 allNodes = flag.Bool("all", false, "Process all found chunked files for all nodes")
274 nodeRaw = flag.String("node", "", "Process all found chunked files for that node")
275 keep = flag.Bool("keep", false, "Do not remove chunks while assembling")
276 dryRun = flag.Bool("dryrun", false, "Do not assemble whole file")
277 dumpMeta = flag.Bool("dump", false, "Print decoded human-readable FILE.nncp.meta")
278 stdout = flag.Bool("stdout", false, "Output reassembled FILE to stdout")
279 spoolPath = flag.String("spool", "", "Override path to spool")
280 logPath = flag.String("log", "", "Override path to logfile")
281 quiet = flag.Bool("quiet", false, "Print only errors")
282 debug = flag.Bool("debug", false, "Print debug messages")
283 version = flag.Bool("version", false, "Print version information")
284 warranty = flag.Bool("warranty", false, "Print warranty information")
289 fmt.Println(nncp.Warranty)
293 fmt.Println(nncp.VersionGet())
297 ctx, err := nncp.CtxFromCmdline(*cfgPath, *spoolPath, *logPath, *quiet, *debug)
299 log.Fatalln("Error during initialization:", err)
302 var nodeOnly *nncp.Node
304 nodeOnly, err = ctx.FindNode(*nodeRaw)
306 log.Fatalln("Invalid -node specified:", err)
310 if !(*allNodes || nodeOnly != nil || flag.NArg() > 0) {
314 if flag.NArg() > 0 && (*allNodes || nodeOnly != nil) {
318 if *allNodes && nodeOnly != nil {
326 if process(ctx, flag.Arg(0), *keep, *dryRun, *stdout, *dumpMeta) {
334 seenMetaPaths := make(map[string]struct{})
335 for _, node := range ctx.Neigh {
336 if node.Incoming == nil {
339 for _, metaPath := range findMetas(ctx, *node.Incoming) {
340 if _, seen := seenMetaPaths[metaPath]; seen {
343 if !process(ctx, metaPath, *keep, *dryRun, false, false) {
346 seenMetaPaths[metaPath] = struct{}{}
350 if nodeOnly.Incoming == nil {
351 log.Fatalln("Specified -node does not allow incoming")
353 for _, metaPath := range findMetas(ctx, *nodeOnly.Incoming) {
354 if !process(ctx, metaPath, *keep, *dryRun, false, false) {