]> Cypherpunks.ru repositories - nncp.git/blob - src/cfg.go
Replace TxFile with TxFileChunked
[nncp.git] / src / cfg.go
1 /*
2 NNCP -- Node to Node copy, utilities for store-and-forward data exchange
3 Copyright (C) 2016-2019 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, version 3 of the License.
8
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.
13
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/>.
16 */
17
18 package nncp
19
20 import (
21         "bytes"
22         "encoding/json"
23         "errors"
24         "log"
25         "os"
26         "path"
27         "strconv"
28
29         "github.com/gorhill/cronexpr"
30         "github.com/hjson/hjson-go"
31         "golang.org/x/crypto/ed25519"
32         "golang.org/x/crypto/ssh/terminal"
33 )
34
35 const (
36         CfgPathEnv  = "NNCPCFG"
37         CfgSpoolEnv = "NNCPSPOOL"
38         CfgLogEnv   = "NNCPLOG"
39 )
40
41 var (
42         DefaultCfgPath      string = "/usr/local/etc/nncp.hjson"
43         DefaultSendmailPath string = "/usr/sbin/sendmail"
44         DefaultSpoolPath    string = "/var/spool/nncp"
45         DefaultLogPath      string = "/var/spool/nncp/log"
46 )
47
48 type NodeJSON struct {
49         Id       string              `json:"id"`
50         ExchPub  string              `json:"exchpub"`
51         SignPub  string              `json:"signpub"`
52         NoisePub *string             `json:"noisepub,omitempty"`
53         Exec     map[string][]string `json:"exec,omitempty"`
54         Incoming *string             `json:"incoming,omitempty"`
55         Freq     *NodeFreqJSON       `json:"freq,omitempty"`
56         Via      []string            `json:"via,omitempty"`
57         Calls    []CallJSON          `json:"calls,omitempty"`
58
59         Addrs map[string]string `json:"addrs,omitempty"`
60
61         RxRate         *int  `json:"rxrate,omitempty"`
62         TxRate         *int  `json:"txrate,omitempty"`
63         OnlineDeadline *uint `json:"onlinedeadline,omitempty"`
64         MaxOnlineTime  *uint `json:"maxonlinetime,omitempty"`
65 }
66
67 type NodeFreqJSON struct {
68         Path    *string `json:"path,omitempty"`
69         Chunked *uint64 `json:"chunked,omitempty"`
70         MinSize *uint64 `json:"minsize,omitempty"`
71 }
72
73 type CallJSON struct {
74         Cron           string
75         Nice           *string `json:"nice,omitempty"`
76         Xx             *string `json:"xx,omitempty"`
77         RxRate         *int    `json:"rxrate,omitempty"`
78         TxRate         *int    `json:"txrate,omitempty"`
79         Addr           *string `json:"addr,omitempty"`
80         OnlineDeadline *uint   `json:"onlinedeadline,omitempty"`
81         MaxOnlineTime  *uint   `json:"maxonlinetime,omitempty"`
82 }
83
84 type NodeOurJSON struct {
85         Id       string `json:"id"`
86         ExchPub  string `json:"exchpub"`
87         ExchPrv  string `json:"exchprv"`
88         SignPub  string `json:"signpub"`
89         SignPrv  string `json:"signprv"`
90         NoisePrv string `json:"noiseprv"`
91         NoisePub string `json:"noisepub"`
92 }
93
94 type FromToJSON struct {
95         From string
96         To   string
97 }
98
99 type NotifyJSON struct {
100         File *FromToJSON `json:"file,omitempty"`
101         Freq *FromToJSON `json:"freq,omitempty"`
102 }
103
104 type CfgJSON struct {
105         Spool string `json:"spool"`
106         Log   string `json:"log"`
107         Umask string `json:"umask",omitempty`
108
109         Notify *NotifyJSON `json:"notify,omitempty"`
110
111         Self  *NodeOurJSON        `json:"self"`
112         Neigh map[string]NodeJSON `json:"neigh"`
113 }
114
115 func NewNode(name string, yml NodeJSON) (*Node, error) {
116         nodeId, err := NodeIdFromString(yml.Id)
117         if err != nil {
118                 return nil, err
119         }
120
121         exchPub, err := FromBase32(yml.ExchPub)
122         if err != nil {
123                 return nil, err
124         }
125         if len(exchPub) != 32 {
126                 return nil, errors.New("Invalid exchPub size")
127         }
128
129         signPub, err := FromBase32(yml.SignPub)
130         if err != nil {
131                 return nil, err
132         }
133         if len(signPub) != ed25519.PublicKeySize {
134                 return nil, errors.New("Invalid signPub size")
135         }
136
137         var noisePub []byte
138         if yml.NoisePub != nil {
139                 noisePub, err = FromBase32(*yml.NoisePub)
140                 if err != nil {
141                         return nil, err
142                 }
143                 if len(noisePub) != 32 {
144                         return nil, errors.New("Invalid noisePub size")
145                 }
146         }
147
148         var incoming *string
149         if yml.Incoming != nil {
150                 inc := path.Clean(*yml.Incoming)
151                 if !path.IsAbs(inc) {
152                         return nil, errors.New("Incoming path must be absolute")
153                 }
154                 incoming = &inc
155         }
156
157         var freqPath *string
158         freqChunked := int64(MaxFileSize)
159         var freqMinSize int64
160         if yml.Freq != nil {
161                 f := yml.Freq
162                 if f.Path != nil {
163                         fPath := path.Clean(*f.Path)
164                         if !path.IsAbs(fPath) {
165                                 return nil, errors.New("freq.path path must be absolute")
166                         }
167                         freqPath = &fPath
168                 }
169                 if f.Chunked != nil {
170                         if *f.Chunked == 0 {
171                                 return nil, errors.New("freq.chunked value must be greater than zero")
172                         }
173                         freqChunked = int64(*f.Chunked) * 1024
174                 }
175                 if f.MinSize != nil {
176                         freqMinSize = int64(*f.MinSize) * 1024
177                 }
178         }
179
180         defRxRate := 0
181         if yml.RxRate != nil && *yml.RxRate > 0 {
182                 defRxRate = *yml.RxRate
183         }
184         defTxRate := 0
185         if yml.TxRate != nil && *yml.TxRate > 0 {
186                 defTxRate = *yml.TxRate
187         }
188
189         defOnlineDeadline := uint(DefaultDeadline)
190         if yml.OnlineDeadline != nil {
191                 if *yml.OnlineDeadline <= 0 {
192                         return nil, errors.New("OnlineDeadline must be at least 1 second")
193                 }
194                 defOnlineDeadline = *yml.OnlineDeadline
195         }
196         var defMaxOnlineTime uint
197         if yml.MaxOnlineTime != nil {
198                 defMaxOnlineTime = *yml.MaxOnlineTime
199         }
200
201         var calls []*Call
202         for _, callYml := range yml.Calls {
203                 expr, err := cronexpr.Parse(callYml.Cron)
204                 if err != nil {
205                         return nil, err
206                 }
207
208                 nice := uint8(255)
209                 if callYml.Nice != nil {
210                         nice, err = NicenessParse(*callYml.Nice)
211                         if err != nil {
212                                 return nil, err
213                         }
214                 }
215
216                 var xx TRxTx
217                 if callYml.Xx != nil {
218                         switch *callYml.Xx {
219                         case "rx":
220                                 xx = TRx
221                         case "tx":
222                                 xx = TTx
223                         default:
224                                 return nil, errors.New("xx field must be either \"rx\" or \"tx\"")
225                         }
226                 }
227
228                 rxRate := defRxRate
229                 if callYml.RxRate != nil {
230                         rxRate = *callYml.RxRate
231                 }
232                 txRate := defTxRate
233                 if callYml.TxRate != nil {
234                         txRate = *callYml.TxRate
235                 }
236
237                 var addr *string
238                 if callYml.Addr != nil {
239                         if a, exists := yml.Addrs[*callYml.Addr]; exists {
240                                 addr = &a
241                         } else {
242                                 addr = callYml.Addr
243                         }
244                 }
245
246                 onlineDeadline := defOnlineDeadline
247                 if callYml.OnlineDeadline != nil {
248                         if *callYml.OnlineDeadline == 0 {
249                                 return nil, errors.New("OnlineDeadline must be at least 1 second")
250                         }
251                         onlineDeadline = *callYml.OnlineDeadline
252                 }
253
254                 var maxOnlineTime uint
255                 if callYml.MaxOnlineTime != nil {
256                         maxOnlineTime = *callYml.MaxOnlineTime
257                 }
258
259                 calls = append(calls, &Call{
260                         Cron:           expr,
261                         Nice:           nice,
262                         Xx:             xx,
263                         RxRate:         rxRate,
264                         TxRate:         txRate,
265                         Addr:           addr,
266                         OnlineDeadline: onlineDeadline,
267                         MaxOnlineTime:  maxOnlineTime,
268                 })
269         }
270
271         node := Node{
272                 Name:           name,
273                 Id:             nodeId,
274                 ExchPub:        new([32]byte),
275                 SignPub:        ed25519.PublicKey(signPub),
276                 Exec:           yml.Exec,
277                 Incoming:       incoming,
278                 FreqPath:       freqPath,
279                 FreqChunked:    freqChunked,
280                 FreqMinSize:    freqMinSize,
281                 Calls:          calls,
282                 Addrs:          yml.Addrs,
283                 RxRate:         defRxRate,
284                 TxRate:         defTxRate,
285                 OnlineDeadline: defOnlineDeadline,
286                 MaxOnlineTime:  defMaxOnlineTime,
287         }
288         copy(node.ExchPub[:], exchPub)
289         if len(noisePub) > 0 {
290                 node.NoisePub = new([32]byte)
291                 copy(node.NoisePub[:], noisePub)
292         }
293         return &node, nil
294 }
295
296 func NewNodeOur(yml *NodeOurJSON) (*NodeOur, error) {
297         id, err := NodeIdFromString(yml.Id)
298         if err != nil {
299                 return nil, err
300         }
301
302         exchPub, err := FromBase32(yml.ExchPub)
303         if err != nil {
304                 return nil, err
305         }
306         if len(exchPub) != 32 {
307                 return nil, errors.New("Invalid exchPub size")
308         }
309
310         exchPrv, err := FromBase32(yml.ExchPrv)
311         if err != nil {
312                 return nil, err
313         }
314         if len(exchPrv) != 32 {
315                 return nil, errors.New("Invalid exchPrv size")
316         }
317
318         signPub, err := FromBase32(yml.SignPub)
319         if err != nil {
320                 return nil, err
321         }
322         if len(signPub) != ed25519.PublicKeySize {
323                 return nil, errors.New("Invalid signPub size")
324         }
325
326         signPrv, err := FromBase32(yml.SignPrv)
327         if err != nil {
328                 return nil, err
329         }
330         if len(signPrv) != ed25519.PrivateKeySize {
331                 return nil, errors.New("Invalid signPrv size")
332         }
333
334         noisePub, err := FromBase32(yml.NoisePub)
335         if err != nil {
336                 return nil, err
337         }
338         if len(noisePub) != 32 {
339                 return nil, errors.New("Invalid noisePub size")
340         }
341
342         noisePrv, err := FromBase32(yml.NoisePrv)
343         if err != nil {
344                 return nil, err
345         }
346         if len(noisePrv) != 32 {
347                 return nil, errors.New("Invalid noisePrv size")
348         }
349
350         node := NodeOur{
351                 Id:       id,
352                 ExchPub:  new([32]byte),
353                 ExchPrv:  new([32]byte),
354                 SignPub:  ed25519.PublicKey(signPub),
355                 SignPrv:  ed25519.PrivateKey(signPrv),
356                 NoisePub: new([32]byte),
357                 NoisePrv: new([32]byte),
358         }
359         copy(node.ExchPub[:], exchPub)
360         copy(node.ExchPrv[:], exchPrv)
361         copy(node.NoisePub[:], noisePub)
362         copy(node.NoisePrv[:], noisePrv)
363         return &node, nil
364 }
365
366 func CfgParse(data []byte) (*Ctx, error) {
367         var err error
368         if bytes.Compare(data[:8], MagicNNCPBv3[:]) == 0 {
369                 os.Stderr.WriteString("Passphrase:")
370                 password, err := terminal.ReadPassword(0)
371                 if err != nil {
372                         log.Fatalln(err)
373                 }
374                 os.Stderr.WriteString("\n")
375                 data, err = DeEBlob(data, password)
376                 if err != nil {
377                         return nil, err
378                 }
379         }
380         var cfgGeneral map[string]interface{}
381         if err = hjson.Unmarshal(data, &cfgGeneral); err != nil {
382                 return nil, err
383         }
384         marshaled, err := json.Marshal(cfgGeneral)
385         if err != nil {
386                 return nil, err
387         }
388         var cfgJSON CfgJSON
389         if err = json.Unmarshal(marshaled, &cfgJSON); err != nil {
390                 return nil, err
391         }
392         if _, exists := cfgJSON.Neigh["self"]; !exists {
393                 return nil, errors.New("self neighbour missing")
394         }
395         var self *NodeOur
396         if cfgJSON.Self != nil {
397                 self, err = NewNodeOur(cfgJSON.Self)
398                 if err != nil {
399                         return nil, err
400                 }
401         }
402         spoolPath := path.Clean(cfgJSON.Spool)
403         if !path.IsAbs(spoolPath) {
404                 return nil, errors.New("Spool path must be absolute")
405         }
406         logPath := path.Clean(cfgJSON.Log)
407         if !path.IsAbs(logPath) {
408                 return nil, errors.New("Log path must be absolute")
409         }
410         var umaskForce *int
411         if cfgJSON.Umask != "" {
412                 r, err := strconv.ParseUint(cfgJSON.Umask, 8, 16)
413                 if err != nil {
414                         return nil, err
415                 }
416                 rInt := int(r)
417                 umaskForce = &rInt
418         }
419         ctx := Ctx{
420                 Spool:      spoolPath,
421                 LogPath:    logPath,
422                 UmaskForce: umaskForce,
423                 Self:       self,
424                 Neigh:      make(map[NodeId]*Node, len(cfgJSON.Neigh)),
425                 Alias:      make(map[string]*NodeId),
426         }
427         if cfgJSON.Notify != nil {
428                 if cfgJSON.Notify.File != nil {
429                         ctx.NotifyFile = cfgJSON.Notify.File
430                 }
431                 if cfgJSON.Notify.Freq != nil {
432                         ctx.NotifyFreq = cfgJSON.Notify.Freq
433                 }
434         }
435         vias := make(map[NodeId][]string)
436         for name, neighJSON := range cfgJSON.Neigh {
437                 neigh, err := NewNode(name, neighJSON)
438                 if err != nil {
439                         return nil, err
440                 }
441                 ctx.Neigh[*neigh.Id] = neigh
442                 if _, already := ctx.Alias[name]; already {
443                         return nil, errors.New("Node names conflict")
444                 }
445                 ctx.Alias[name] = neigh.Id
446                 vias[*neigh.Id] = neighJSON.Via
447         }
448         ctx.SelfId = ctx.Alias["self"]
449         for neighId, viasRaw := range vias {
450                 for _, viaRaw := range viasRaw {
451                         foundNodeId, err := ctx.FindNode(viaRaw)
452                         if err != nil {
453                                 return nil, err
454                         }
455                         ctx.Neigh[neighId].Via = append(
456                                 ctx.Neigh[neighId].Via,
457                                 foundNodeId.Id,
458                         )
459                 }
460         }
461         return &ctx, nil
462 }