]> Cypherpunks.ru repositories - nncp.git/blob - src/cypherpunks.ru/nncp/cmd/nncp-bundle/main.go
Bundles feature
[nncp.git] / src / cypherpunks.ru / nncp / cmd / nncp-bundle / 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 // Create/digest stream of NNCP encrypted packets
20 package main
21
22 import (
23         "archive/tar"
24         "bufio"
25         "bytes"
26         "flag"
27         "fmt"
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 const (
42         CopyBufSize = 1 << 17
43 )
44
45 func usage() {
46         fmt.Fprintf(os.Stderr, nncp.UsageHeader())
47         fmt.Fprintln(os.Stderr, "nncp-bundle -- Create/digest stream of NNCP encrypted packets\n")
48         fmt.Fprintf(os.Stderr, "Usage: %s [options] -tx [-delete] NODE [NODE ...] > ...\n", os.Args[0])
49         fmt.Fprintf(os.Stderr, "       %s [options] -rx -delete [NODE ...] < ...\n", os.Args[0])
50         fmt.Fprintf(os.Stderr, "       %s [options] -rx [-check] [NODE ...] < ...\n", os.Args[0])
51         fmt.Fprintln(os.Stderr, "Options:")
52         flag.PrintDefaults()
53 }
54
55 func main() {
56         var (
57                 cfgPath  = flag.String("cfg", nncp.DefaultCfgPath, "Path to configuration file")
58                 niceRaw  = flag.Int("nice", 255, "Minimal required niceness")
59                 doRx     = flag.Bool("rx", false, "Receive packets")
60                 doTx     = flag.Bool("tx", false, "Transfer packets")
61                 doDelete = flag.Bool("delete", false, "Delete transferred packets")
62                 doCheck  = flag.Bool("check", false, "Check integrity while receiving")
63                 quiet    = flag.Bool("quiet", false, "Print only errors")
64                 debug    = flag.Bool("debug", false, "Print debug messages")
65                 version  = flag.Bool("version", false, "Print version information")
66                 warranty = flag.Bool("warranty", false, "Print warranty information")
67         )
68         flag.Usage = usage
69         flag.Parse()
70         if *warranty {
71                 fmt.Println(nncp.Warranty)
72                 return
73         }
74         if *version {
75                 fmt.Println(nncp.VersionGet())
76                 return
77         }
78         if *niceRaw < 1 || *niceRaw > 255 {
79                 log.Fatalln("-nice must be between 1 and 255")
80         }
81         nice := uint8(*niceRaw)
82         if *doRx && *doTx {
83                 log.Fatalln("-rx and -tx can not be set simultaneously")
84         }
85         if !*doRx && !*doTx {
86                 log.Fatalln("At least one of -rx and -tx must be specified")
87         }
88
89         cfgRaw, err := ioutil.ReadFile(nncp.CfgPathFromEnv(cfgPath))
90         if err != nil {
91                 log.Fatalln("Can not read config:", err)
92         }
93         ctx, err := nncp.CfgParse(cfgRaw)
94         if err != nil {
95                 log.Fatalln("Can not parse config:", err)
96         }
97         ctx.Quiet = *quiet
98         ctx.Debug = *debug
99
100         nodeIds := make(map[nncp.NodeId]struct{}, flag.NArg())
101         for i := 0; i < flag.NArg(); i++ {
102                 node, err := ctx.FindNode(flag.Arg(i))
103                 if err != nil {
104                         log.Fatalln("Invalid specified:", err)
105                 }
106                 nodeIds[*node.Id] = struct{}{}
107         }
108
109         sds := nncp.SDS{}
110         if *doTx {
111                 sds["xx"] = string(nncp.TTx)
112                 var pktName string
113                 bufStdout := bufio.NewWriter(os.Stdout)
114                 tarWr := tar.NewWriter(bufStdout)
115                 for nodeId, _ := range nodeIds {
116                         sds["node"] = nodeId.String()
117                         for job := range ctx.Jobs(&nodeId, nncp.TTx) {
118                                 pktName = filepath.Base(job.Fd.Name())
119                                 sds["pkt"] = pktName
120                                 if job.PktEnc.Nice > nice {
121                                         ctx.LogD("nncp-bundle", sds, "too nice")
122                                         job.Fd.Close()
123                                         continue
124                                 }
125                                 if err = tarWr.WriteHeader(&tar.Header{
126                                         Name: strings.Join([]string{
127                                                 nodeId.String(),
128                                                 ctx.SelfId.String(),
129                                                 pktName,
130                                         }, "/"),
131                                         Mode:     0440,
132                                         Size:     job.Size,
133                                         Typeflag: tar.TypeReg,
134                                 }); err != nil {
135                                         log.Fatalln("Error writing tar header:", err)
136                                 }
137                                 if _, err = io.Copy(tarWr, job.Fd); err != nil {
138                                         log.Fatalln("Error during copying to tar:", err)
139                                 }
140                                 job.Fd.Close()
141                                 if err = tarWr.Flush(); err != nil {
142                                         log.Fatalln("Error during tar flushing:", err)
143                                 }
144                                 if err = bufStdout.Flush(); err != nil {
145                                         log.Fatalln("Error during stdout flushing:", err)
146                                 }
147                                 if *doDelete {
148                                         if err = os.Remove(job.Fd.Name()); err != nil {
149                                                 log.Fatalln("Error during deletion:", err)
150                                         }
151                                 }
152                                 ctx.LogI("nncp-bundle", nncp.SdsAdd(sds, nncp.SDS{
153                                         "size": strconv.FormatInt(job.Size, 10),
154                                 }), "")
155                         }
156                 }
157                 if err = tarWr.Close(); err != nil {
158                         log.Fatalln("Error during tar closing:", err)
159                 }
160         } else {
161                 tarR := tar.NewReader(bufio.NewReaderSize(os.Stdin, CopyBufSize))
162                 var entry *tar.Header
163                 var sepIndex int
164                 var exists bool
165                 pktEncBuf := make([]byte, nncp.PktEncOverhead)
166                 var pktEnc *nncp.PktEnc
167                 var pktName string
168                 var selfPath string
169                 var dstPath string
170                 for {
171                         sds["xx"] = string(nncp.TRx)
172                         entry, err = tarR.Next()
173                         if err != nil {
174                                 if err == io.EOF {
175                                         break
176                                 }
177                                 log.Fatalln("Error during tar reading:", err)
178                         }
179                         sds["pkt"] = entry.Name
180                         if entry.Size < nncp.PktEncOverhead {
181                                 ctx.LogD("nncp-bundle", sds, "Too small packet")
182                                 continue
183                         }
184                         sepIndex = strings.LastIndex(entry.Name, "/")
185                         if sepIndex == -1 {
186                                 ctx.LogD("nncp-bundle", sds, "Bad packet name")
187                                 continue
188                         }
189                         pktName = entry.Name[sepIndex+1:]
190                         if _, err = nncp.FromBase32(pktName); err != nil {
191                                 ctx.LogD("nncp-bundle", sds, "Bad packet name")
192                                 continue
193                         }
194                         if _, err = io.ReadFull(tarR, pktEncBuf); err != nil {
195                                 ctx.LogD("nncp-bundle", nncp.SdsAdd(sds, nncp.SDS{"err": err}), "read")
196                                 continue
197                         }
198                         if _, err = xdr.Unmarshal(bytes.NewBuffer(pktEncBuf), &pktEnc); err != nil {
199                                 ctx.LogD("nncp-bundle", sds, "Bad packet structure")
200                                 continue
201                         }
202                         if pktEnc.Magic != nncp.MagicNNCPEv2 {
203                                 ctx.LogD("nncp-bundle", sds, "Bad packet magic number")
204                                 continue
205                         }
206                         if pktEnc.Nice > nice {
207                                 ctx.LogD("nncp-bundle", sds, "too nice")
208                                 continue
209                         }
210                         if *pktEnc.Sender == *ctx.SelfId && *doDelete {
211                                 if len(nodeIds) > 0 {
212                                         if _, exists = nodeIds[*pktEnc.Recipient]; !exists {
213                                                 ctx.LogD("nncp-bundle", sds, "Recipient is not requested")
214                                                 continue
215                                         }
216                                 }
217                                 nodeId32 := nncp.ToBase32(pktEnc.Recipient[:])
218                                 sds["xx"] = string(nncp.TTx)
219                                 sds["node"] = nodeId32
220                                 sds["pkt"] = pktName
221                                 dstPath = filepath.Join(
222                                         ctx.Spool,
223                                         nodeId32,
224                                         string(nncp.TTx),
225                                         pktName,
226                                 )
227                                 if _, err = os.Stat(dstPath); err != nil {
228                                         ctx.LogD("nncp-bundle", sds, "Packet is already missing")
229                                         continue
230                                 }
231                                 hsh, err := blake2b.New256(nil)
232                                 if err != nil {
233                                         log.Fatalln("Error during hasher creation:", err)
234                                 }
235                                 if _, err = hsh.Write(pktEncBuf); err != nil {
236                                         log.Fatalln("Error during writing:", err)
237                                 }
238                                 if _, err = io.Copy(hsh, tarR); err != nil {
239                                         log.Fatalln("Error during copying:", err)
240                                 }
241                                 if nncp.ToBase32(hsh.Sum(nil)) == pktName {
242                                         ctx.LogI("nncp-bundle", sds, "removed")
243                                         os.Remove(dstPath)
244                                 } else {
245                                         ctx.LogE("nncp-bundle", sds, "bad checksum")
246                                 }
247                                 continue
248                         }
249                         if *pktEnc.Recipient != *ctx.SelfId {
250                                 ctx.LogD("nncp-bundle", sds, "Unknown recipient")
251                                 continue
252                         }
253                         if len(nodeIds) > 0 {
254                                 if _, exists = nodeIds[*pktEnc.Sender]; !exists {
255                                         ctx.LogD("nncp-bundle", sds, "Sender is not requested")
256                                         continue
257                                 }
258                         }
259                         sds["node"] = nncp.ToBase32(pktEnc.Recipient[:])
260                         sds["pkt"] = pktName
261                         selfPath = filepath.Join(ctx.Spool, ctx.SelfId.String(), string(nncp.TRx))
262                         dstPath = filepath.Join(selfPath, pktName)
263                         if _, err = os.Stat(dstPath); err == nil || !os.IsNotExist(err) {
264                                 ctx.LogD("nncp-bundle", sds, "Packet already exists")
265                                 continue
266                         }
267                         if *doCheck {
268                                 tmp, err := ctx.NewTmpFileWHash()
269                                 if err != nil {
270                                         log.Fatalln("Error during temporary file creation:", err)
271                                 }
272                                 if _, err = tmp.W.Write(pktEncBuf); err != nil {
273                                         log.Fatalln("Error during writing:", err)
274                                 }
275                                 if _, err = io.Copy(tmp.W, tarR); err != nil {
276                                         log.Fatalln("Error during copying:", err)
277                                 }
278                                 if err = tmp.W.Flush(); err != nil {
279                                         log.Fatalln("Error during flusing:", err)
280                                 }
281                                 if nncp.ToBase32(tmp.Hsh.Sum(nil)) == pktName {
282                                         if err = tmp.Commit(selfPath); err != nil {
283                                                 log.Fatalln("Error during commiting:", err)
284                                         }
285                                 } else {
286                                         ctx.LogE("nncp-bundle", sds, "bad checksum")
287                                         tmp.Cancel()
288                                         continue
289                                 }
290                         } else {
291                                 tmp, err := ctx.NewTmpFile()
292                                 if err != nil {
293                                         log.Fatalln("Error during temporary file creation:", err)
294                                 }
295                                 bufTmp := bufio.NewWriterSize(tmp, CopyBufSize)
296                                 if _, err = bufTmp.Write(pktEncBuf); err != nil {
297                                         log.Fatalln("Error during writing:", err)
298                                 }
299                                 if _, err = io.Copy(bufTmp, tarR); err != nil {
300                                         log.Fatalln("Error during copying:", err)
301                                 }
302                                 if err = bufTmp.Flush(); err != nil {
303                                         log.Fatalln("Error during flushing:", err)
304                                 }
305                                 tmp.Sync()
306                                 tmp.Close()
307                                 if err = os.MkdirAll(selfPath, os.FileMode(0700)); err != nil {
308                                         log.Fatalln("Error during mkdir:", err)
309                                 }
310                                 if err = os.Rename(tmp.Name(), dstPath); err != nil {
311                                         log.Fatalln("Error during renaming:", err)
312                                 }
313                         }
314                         ctx.LogI("nncp-bundle", nncp.SdsAdd(sds, nncp.SDS{
315                                 "size": strconv.FormatInt(entry.Size, 10),
316                         }), "")
317                 }
318         }
319 }