]> Cypherpunks.ru repositories - nncp.git/blob - src/cypherpunks.ru/nncp/cmd/nncp-reass/main.go
Initial nncp-reass utility
[nncp.git] / src / cypherpunks.ru / nncp / cmd / nncp-reass / main.go
1 /*
2 NNCP -- Node to Node copy, utilities for store-and-forward data exchange
3 Copyright (C) 2016-2017 Sergey Matveev <stargrave@stargrave.org>
4
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, either version 3 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program.  If not, see <http://www.gnu.org/licenses/>.
17 */
18
19 // Send file via NNCP
20 package main
21
22 import (
23         "bufio"
24         "bytes"
25         "flag"
26         "fmt"
27         "hash"
28         "io"
29         "io/ioutil"
30         "log"
31         "os"
32         "path/filepath"
33         "strconv"
34         "strings"
35
36         "cypherpunks.ru/nncp"
37         "github.com/davecgh/go-xdr/xdr2"
38         "golang.org/x/crypto/blake2b"
39 )
40
41 func usage() {
42         fmt.Fprintf(os.Stderr, nncp.UsageHeader())
43         fmt.Fprintln(os.Stderr, "nncp-reass -- reassemble chunked files\n")
44         fmt.Fprintf(os.Stderr, "Usage: %s [options] [FILE]\nOptions:\n", os.Args[0])
45         flag.PrintDefaults()
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.
49 `)
50 }
51
52 func process(ctx *nncp.Ctx, path string, keep, dryRun bool) bool {
53         fd, err := os.Open(path)
54         defer fd.Close()
55         if err != nil {
56                 log.Fatalln("Can not open file:", err)
57         }
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")
61                 return false
62         }
63         fd.Close()
64         if metaPkt.Magic != nncp.MagicNNCPMv1 {
65                 ctx.LogE("nncp-reass", nncp.SDS{"path": path, "err": nncp.BadMagic}, "")
66                 return false
67         }
68         metaName := filepath.Base(path)
69         if !strings.HasSuffix(metaName, nncp.ChunkedSuffixMeta) {
70                 ctx.LogE("nncp-reass", nncp.SDS{
71                         "path": path,
72                         "err":  "invalid filename suffix",
73                 }, "")
74                 return false
75         }
76         mainName := strings.TrimSuffix(metaName, nncp.ChunkedSuffixMeta)
77         mainDir := filepath.Dir(path)
78
79         chunksPaths := make([]string, 0, len(metaPkt.Checksums))
80         for i := 0; i < len(metaPkt.Checksums); i++ {
81                 chunksPaths = append(
82                         chunksPaths,
83                         filepath.Join(mainDir, mainName+nncp.ChunkedSuffixPart+strconv.Itoa(i)),
84                 )
85         }
86
87         allChunksExist := true
88         for chunkNum, chunkPath := range chunksPaths {
89                 fi, err := os.Stat(chunkPath)
90                 if err != nil && os.IsNotExist(err) {
91                         ctx.LogI("nncp-reass", nncp.SDS{
92                                 "path":  path,
93                                 "chunk": strconv.Itoa(chunkNum),
94                         }, "missing")
95                         allChunksExist = false
96                         continue
97                 }
98                 if chunkNum+1 != len(chunksPaths) && uint64(fi.Size()) != metaPkt.ChunkSize {
99                         ctx.LogE("nncp-reass", nncp.SDS{
100                                 "path":  path,
101                                 "chunk": strconv.Itoa(chunkNum),
102                         }, "invalid size")
103                         allChunksExist = false
104                 }
105         }
106         if !allChunksExist {
107                 return false
108         }
109
110         var hsh hash.Hash
111         allChecksumsGood := true
112         for chunkNum, chunkPath := range chunksPaths {
113                 fd, err = os.Open(chunkPath)
114                 if err != nil {
115                         log.Fatalln("Can not open file:", err)
116                 }
117                 hsh, err = blake2b.New256(nil)
118                 if err != nil {
119                         log.Fatalln(err)
120                 }
121                 if _, err = io.Copy(hsh, bufio.NewReader(fd)); err != nil {
122                         log.Fatalln(err)
123                 }
124                 fd.Close()
125                 if bytes.Compare(hsh.Sum(nil), metaPkt.Checksums[chunkNum][:]) != 0 {
126                         ctx.LogE("nncp-reass", nncp.SDS{
127                                 "path":  path,
128                                 "chunk": strconv.Itoa(chunkNum),
129                                 "err":   "checksum is bad",
130                         }, "")
131                         allChecksumsGood = false
132                 }
133         }
134         if !allChecksumsGood {
135                 return false
136         }
137         if dryRun {
138                 ctx.LogI("nncp-reass", nncp.SDS{"path": path}, "ready")
139                 return true
140         }
141
142         tmp, err := ioutil.TempFile(mainDir, "nncp-reass")
143         if err != nil {
144                 log.Fatalln(err)
145         }
146         sds := nncp.SDS{"path": path, "tmp": tmp.Name()}
147         ctx.LogD("nncp-reass", sds, "created")
148         tmpW := bufio.NewWriter(tmp)
149
150         hasErrors := false
151         for chunkNum, chunkPath := range chunksPaths {
152                 fd, err = os.Open(chunkPath)
153                 if err != nil {
154                         log.Fatalln("Can not open file:", err)
155                 }
156                 if _, err = io.Copy(tmpW, bufio.NewReader(fd)); err != nil {
157                         log.Fatalln(err)
158                 }
159                 fd.Close()
160                 if !keep {
161                         if err = os.Remove(chunkPath); err != nil {
162                                 ctx.LogE("nncp-reass", nncp.SdsAdd(sds, nncp.SDS{
163                                         "chunk": strconv.Itoa(chunkNum),
164                                         "err":   err,
165                                 }), "")
166                                 hasErrors = true
167                         }
168                 }
169         }
170         tmpW.Flush()
171         tmp.Sync()
172         tmp.Close()
173         ctx.LogD("nncp-reass", sds, "written")
174         if !keep {
175                 if err = os.Remove(path); err != nil {
176                         ctx.LogE("nncp-reass", nncp.SdsAdd(sds, nncp.SDS{"err": err}), "")
177                         hasErrors = true
178                 }
179         }
180
181         dstPathOrig := filepath.Join(mainDir, mainName)
182         dstPath := dstPathOrig
183         dstPathCtr := 0
184         for {
185                 if _, err = os.Stat(dstPath); err != nil {
186                         if os.IsNotExist(err) {
187                                 break
188                         }
189                         log.Fatalln(err)
190                 }
191                 dstPath = dstPathOrig + strconv.Itoa(dstPathCtr)
192                 dstPathCtr++
193         }
194         if err = os.Rename(tmp.Name(), dstPath); err != nil {
195                 log.Fatalln(err)
196         }
197         ctx.LogI("nncp-reass", nncp.SDS{"path": path}, "done")
198         return !hasErrors
199 }
200
201 func findMetas(ctx *nncp.Ctx, dirPath string) []string {
202         dir, err := os.Open(dirPath)
203         defer dir.Close()
204         if err != nil {
205                 ctx.LogE("nncp-reass", nncp.SDS{"path": dirPath, "err": err}, "")
206                 return nil
207         }
208         fis, err := dir.Readdir(0)
209         dir.Close()
210         if err != nil {
211                 ctx.LogE("nncp-reass", nncp.SDS{"path": dirPath, "err": err}, "")
212                 return nil
213         }
214         metaPaths := make([]string, 0)
215         for _, fi := range fis {
216                 if strings.HasSuffix(fi.Name(), nncp.ChunkedSuffixMeta) {
217                         metaPaths = append(metaPaths, filepath.Join(dirPath, fi.Name()))
218                 }
219         }
220         return metaPaths
221 }
222
223 func main() {
224         var (
225                 cfgPath  = flag.String("cfg", nncp.DefaultCfgPath, "Path to configuration file")
226                 allNodes = flag.Bool("all", false, "Process all found chunked files for all nodes")
227                 nodeRaw  = flag.String("node", "", "Process all found chunked files for that node")
228                 keep     = flag.Bool("keep", false, "Do not remove chunks while assembling")
229                 dryRun   = flag.Bool("dryrun", false, "Do not assemble whole file")
230                 quiet    = flag.Bool("quiet", false, "Print only errors")
231                 debug    = flag.Bool("debug", false, "Print debug messages")
232                 version  = flag.Bool("version", false, "Print version information")
233                 warranty = flag.Bool("warranty", false, "Print warranty information")
234         )
235         flag.Usage = usage
236         flag.Parse()
237         if *warranty {
238                 fmt.Println(nncp.Warranty)
239                 return
240         }
241         if *version {
242                 fmt.Println(nncp.VersionGet())
243                 return
244         }
245
246         cfgRaw, err := ioutil.ReadFile(nncp.CfgPathFromEnv(cfgPath))
247         if err != nil {
248                 log.Fatalln("Can not read config:", err)
249         }
250         ctx, err := nncp.CfgParse(cfgRaw)
251         if err != nil {
252                 log.Fatalln("Can not parse config:", err)
253         }
254         ctx.Quiet = *quiet
255         ctx.Debug = *debug
256
257         var nodeOnly *nncp.Node
258         if *nodeRaw != "" {
259                 nodeOnly, err = ctx.FindNode(*nodeRaw)
260                 if err != nil {
261                         log.Fatalln("Invalid -node specified:", err)
262                 }
263         }
264
265         if !(*allNodes || nodeOnly != nil || flag.NArg() > 0) {
266                 usage()
267                 os.Exit(1)
268         }
269         if flag.NArg() > 0 && (*allNodes || nodeOnly != nil) {
270                 usage()
271                 os.Exit(1)
272         }
273         if *allNodes && nodeOnly != nil {
274                 usage()
275                 os.Exit(1)
276         }
277
278         if flag.NArg() > 0 {
279                 if !process(ctx, flag.Arg(0), *keep, *dryRun) {
280                         os.Exit(1)
281                 }
282                 return
283         }
284
285         hasErrors := false
286         if nodeOnly == nil {
287                 seenMetaPaths := make(map[string]struct{})
288                 for _, node := range ctx.Neigh {
289                         if node.Incoming == nil {
290                                 continue
291                         }
292                         for _, metaPath := range findMetas(ctx, *node.Incoming) {
293                                 if _, seen := seenMetaPaths[metaPath]; seen {
294                                         continue
295                                 }
296                                 hasErrors = hasErrors || !process(ctx, metaPath, *keep, *dryRun)
297                                 seenMetaPaths[metaPath] = struct{}{}
298                         }
299                 }
300         } else {
301                 if nodeOnly.Incoming == nil {
302                         log.Fatalln("Specified -node does not allow incoming")
303                 }
304                 for _, metaPath := range findMetas(ctx, *nodeOnly.Incoming) {
305                         hasErrors = hasErrors || !process(ctx, metaPath, *keep, *dryRun)
306                 }
307         }
308         if hasErrors {
309                 os.Exit(1)
310         }
311 }