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