]> Cypherpunks.ru repositories - nncp.git/blob - src/cfg.go
bb101cac2914c8af566e5dd7cbf0fe6b3c91da73
[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         WhenTxExists   *bool   `json:"when-tx-exists,omitempty"`
85         NoCK           *bool   `json:"nock"`
86         MCDIgnore      *bool   `json:"mcd-ignore"`
87
88         AutoToss       *bool `json:"autotoss,omitempty"`
89         AutoTossDoSeen *bool `json:"autotoss-doseen,omitempty"`
90         AutoTossNoFile *bool `json:"autotoss-nofile,omitempty"`
91         AutoTossNoFreq *bool `json:"autotoss-nofreq,omitempty"`
92         AutoTossNoExec *bool `json:"autotoss-noexec,omitempty"`
93         AutoTossNoTrns *bool `json:"autotoss-notrns,omitempty"`
94 }
95
96 type NodeOurJSON struct {
97         Id       string `json:"id"`
98         ExchPub  string `json:"exchpub"`
99         ExchPrv  string `json:"exchprv"`
100         SignPub  string `json:"signpub"`
101         SignPrv  string `json:"signprv"`
102         NoisePrv string `json:"noiseprv"`
103         NoisePub string `json:"noisepub"`
104 }
105
106 type FromToJSON struct {
107         From string
108         To   string
109 }
110
111 type NotifyJSON struct {
112         File *FromToJSON            `json:"file,omitempty"`
113         Freq *FromToJSON            `json:"freq,omitempty"`
114         Exec map[string]*FromToJSON `json:"exec,omitempty"`
115 }
116
117 type CfgJSON struct {
118         Spool string `json:"spool"`
119         Log   string `json:"log"`
120         Umask string `json:"umask,omitempty"`
121
122         OmitPrgrs bool `json:"noprogress,omitempty"`
123         NoHdr     bool `json:"nohdr,omitempty"`
124
125         Notify *NotifyJSON `json:"notify,omitempty"`
126
127         Self  *NodeOurJSON        `json:"self"`
128         Neigh map[string]NodeJSON `json:"neigh"`
129
130         MCDRxIfis []string       `json:"mcd-listen"`
131         MCDTxIfis map[string]int `json:"mcd-send"`
132 }
133
134 func NewNode(name string, cfg NodeJSON) (*Node, error) {
135         nodeId, err := NodeIdFromString(cfg.Id)
136         if err != nil {
137                 return nil, err
138         }
139
140         exchPub, err := Base32Codec.DecodeString(cfg.ExchPub)
141         if err != nil {
142                 return nil, err
143         }
144         if len(exchPub) != 32 {
145                 return nil, errors.New("Invalid exchPub size")
146         }
147
148         signPub, err := Base32Codec.DecodeString(cfg.SignPub)
149         if err != nil {
150                 return nil, err
151         }
152         if len(signPub) != ed25519.PublicKeySize {
153                 return nil, errors.New("Invalid signPub size")
154         }
155
156         var noisePub []byte
157         if cfg.NoisePub != nil {
158                 noisePub, err = Base32Codec.DecodeString(*cfg.NoisePub)
159                 if err != nil {
160                         return nil, err
161                 }
162                 if len(noisePub) != 32 {
163                         return nil, errors.New("Invalid noisePub size")
164                 }
165         }
166
167         var incoming *string
168         if cfg.Incoming != nil {
169                 inc := path.Clean(*cfg.Incoming)
170                 if !path.IsAbs(inc) {
171                         return nil, errors.New("Incoming path must be absolute")
172                 }
173                 incoming = &inc
174         }
175
176         var freqPath *string
177         freqChunked := int64(MaxFileSize)
178         var freqMinSize int64
179         freqMaxSize := int64(MaxFileSize)
180         if cfg.Freq != nil {
181                 f := cfg.Freq
182                 if f.Path != nil {
183                         fPath := path.Clean(*f.Path)
184                         if !path.IsAbs(fPath) {
185                                 return nil, errors.New("freq.path path must be absolute")
186                         }
187                         freqPath = &fPath
188                 }
189                 if f.Chunked != nil {
190                         if *f.Chunked == 0 {
191                                 return nil, errors.New("freq.chunked value must be greater than zero")
192                         }
193                         freqChunked = int64(*f.Chunked) * 1024
194                 }
195                 if f.MinSize != nil {
196                         freqMinSize = int64(*f.MinSize) * 1024
197                 }
198                 if f.MaxSize != nil {
199                         freqMaxSize = int64(*f.MaxSize) * 1024
200                 }
201         }
202
203         defRxRate := 0
204         if cfg.RxRate != nil && *cfg.RxRate > 0 {
205                 defRxRate = *cfg.RxRate
206         }
207         defTxRate := 0
208         if cfg.TxRate != nil && *cfg.TxRate > 0 {
209                 defTxRate = *cfg.TxRate
210         }
211
212         defOnlineDeadline := DefaultDeadline
213         if cfg.OnlineDeadline != nil {
214                 if *cfg.OnlineDeadline <= 0 {
215                         return nil, errors.New("OnlineDeadline must be at least 1 second")
216                 }
217                 defOnlineDeadline = time.Duration(*cfg.OnlineDeadline) * time.Second
218         }
219         var defMaxOnlineTime time.Duration
220         if cfg.MaxOnlineTime != nil {
221                 defMaxOnlineTime = time.Duration(*cfg.MaxOnlineTime) * time.Second
222         }
223
224         var calls []*Call
225         for _, callCfg := range cfg.Calls {
226                 expr, err := cronexpr.Parse(callCfg.Cron)
227                 if err != nil {
228                         return nil, err
229                 }
230
231                 nice := uint8(255)
232                 if callCfg.Nice != nil {
233                         nice, err = NicenessParse(*callCfg.Nice)
234                         if err != nil {
235                                 return nil, err
236                         }
237                 }
238
239                 var xx TRxTx
240                 if callCfg.Xx != nil {
241                         switch *callCfg.Xx {
242                         case "rx":
243                                 xx = TRx
244                         case "tx":
245                                 xx = TTx
246                         default:
247                                 return nil, errors.New("xx field must be either \"rx\" or \"tx\"")
248                         }
249                 }
250
251                 rxRate := defRxRate
252                 if callCfg.RxRate != nil {
253                         rxRate = *callCfg.RxRate
254                 }
255                 txRate := defTxRate
256                 if callCfg.TxRate != nil {
257                         txRate = *callCfg.TxRate
258                 }
259
260                 var addr *string
261                 if callCfg.Addr != nil {
262                         if a, exists := cfg.Addrs[*callCfg.Addr]; exists {
263                                 addr = &a
264                         } else {
265                                 addr = callCfg.Addr
266                         }
267                 }
268
269                 onlineDeadline := defOnlineDeadline
270                 if callCfg.OnlineDeadline != nil {
271                         if *callCfg.OnlineDeadline == 0 {
272                                 return nil, errors.New("OnlineDeadline must be at least 1 second")
273                         }
274                         onlineDeadline = time.Duration(*callCfg.OnlineDeadline) * time.Second
275                 }
276
277                 call := Call{
278                         Cron:           expr,
279                         Nice:           nice,
280                         Xx:             xx,
281                         RxRate:         rxRate,
282                         TxRate:         txRate,
283                         Addr:           addr,
284                         OnlineDeadline: onlineDeadline,
285                 }
286
287                 if callCfg.MaxOnlineTime != nil {
288                         call.MaxOnlineTime = time.Duration(*callCfg.MaxOnlineTime) * time.Second
289                 }
290                 if callCfg.WhenTxExists != nil {
291                         call.WhenTxExists = *callCfg.WhenTxExists
292                 }
293                 if callCfg.NoCK != nil {
294                         call.NoCK = *callCfg.NoCK
295                 }
296                 if callCfg.MCDIgnore != nil {
297                         call.MCDIgnore = *callCfg.MCDIgnore
298                 }
299                 if callCfg.AutoToss != nil {
300                         call.AutoToss = *callCfg.AutoToss
301                 }
302                 if callCfg.AutoTossDoSeen != nil {
303                         call.AutoTossDoSeen = *callCfg.AutoTossDoSeen
304                 }
305                 if callCfg.AutoTossNoFile != nil {
306                         call.AutoTossNoFile = *callCfg.AutoTossNoFile
307                 }
308                 if callCfg.AutoTossNoFreq != nil {
309                         call.AutoTossNoFreq = *callCfg.AutoTossNoFreq
310                 }
311                 if callCfg.AutoTossNoExec != nil {
312                         call.AutoTossNoExec = *callCfg.AutoTossNoExec
313                 }
314                 if callCfg.AutoTossNoTrns != nil {
315                         call.AutoTossNoTrns = *callCfg.AutoTossNoTrns
316                 }
317
318                 calls = append(calls, &call)
319         }
320
321         node := Node{
322                 Name:           name,
323                 Id:             nodeId,
324                 ExchPub:        new([32]byte),
325                 SignPub:        ed25519.PublicKey(signPub),
326                 Exec:           cfg.Exec,
327                 Incoming:       incoming,
328                 FreqPath:       freqPath,
329                 FreqChunked:    freqChunked,
330                 FreqMinSize:    freqMinSize,
331                 FreqMaxSize:    freqMaxSize,
332                 Calls:          calls,
333                 Addrs:          cfg.Addrs,
334                 RxRate:         defRxRate,
335                 TxRate:         defTxRate,
336                 OnlineDeadline: defOnlineDeadline,
337                 MaxOnlineTime:  defMaxOnlineTime,
338         }
339         copy(node.ExchPub[:], exchPub)
340         if len(noisePub) > 0 {
341                 node.NoisePub = new([32]byte)
342                 copy(node.NoisePub[:], noisePub)
343         }
344         return &node, nil
345 }
346
347 func NewNodeOur(cfg *NodeOurJSON) (*NodeOur, error) {
348         id, err := NodeIdFromString(cfg.Id)
349         if err != nil {
350                 return nil, err
351         }
352
353         exchPub, err := Base32Codec.DecodeString(cfg.ExchPub)
354         if err != nil {
355                 return nil, err
356         }
357         if len(exchPub) != 32 {
358                 return nil, errors.New("Invalid exchPub size")
359         }
360
361         exchPrv, err := Base32Codec.DecodeString(cfg.ExchPrv)
362         if err != nil {
363                 return nil, err
364         }
365         if len(exchPrv) != 32 {
366                 return nil, errors.New("Invalid exchPrv size")
367         }
368
369         signPub, err := Base32Codec.DecodeString(cfg.SignPub)
370         if err != nil {
371                 return nil, err
372         }
373         if len(signPub) != ed25519.PublicKeySize {
374                 return nil, errors.New("Invalid signPub size")
375         }
376
377         signPrv, err := Base32Codec.DecodeString(cfg.SignPrv)
378         if err != nil {
379                 return nil, err
380         }
381         if len(signPrv) != ed25519.PrivateKeySize {
382                 return nil, errors.New("Invalid signPrv size")
383         }
384
385         noisePub, err := Base32Codec.DecodeString(cfg.NoisePub)
386         if err != nil {
387                 return nil, err
388         }
389         if len(noisePub) != 32 {
390                 return nil, errors.New("Invalid noisePub size")
391         }
392
393         noisePrv, err := Base32Codec.DecodeString(cfg.NoisePrv)
394         if err != nil {
395                 return nil, err
396         }
397         if len(noisePrv) != 32 {
398                 return nil, errors.New("Invalid noisePrv size")
399         }
400
401         node := NodeOur{
402                 Id:       id,
403                 ExchPub:  new([32]byte),
404                 ExchPrv:  new([32]byte),
405                 SignPub:  ed25519.PublicKey(signPub),
406                 SignPrv:  ed25519.PrivateKey(signPrv),
407                 NoisePub: new([32]byte),
408                 NoisePrv: new([32]byte),
409         }
410         copy(node.ExchPub[:], exchPub)
411         copy(node.ExchPrv[:], exchPrv)
412         copy(node.NoisePub[:], noisePub)
413         copy(node.NoisePrv[:], noisePrv)
414         return &node, nil
415 }
416
417 func CfgParse(data []byte) (*Ctx, error) {
418         var err error
419         if bytes.Compare(data[:8], MagicNNCPBv3.B[:]) == 0 {
420                 os.Stderr.WriteString("Passphrase:") // #nosec G104
421                 password, err := term.ReadPassword(0)
422                 if err != nil {
423                         log.Fatalln(err)
424                 }
425                 os.Stderr.WriteString("\n") // #nosec G104
426                 data, err = DeEBlob(data, password)
427                 if err != nil {
428                         return nil, err
429                 }
430         } else if bytes.Compare(data[:8], MagicNNCPBv2.B[:]) == 0 {
431                 log.Fatalln(MagicNNCPBv2.TooOld())
432         } else if bytes.Compare(data[:8], MagicNNCPBv1.B[:]) == 0 {
433                 log.Fatalln(MagicNNCPBv1.TooOld())
434         }
435         var cfgGeneral map[string]interface{}
436         if err = hjson.Unmarshal(data, &cfgGeneral); err != nil {
437                 return nil, err
438         }
439         marshaled, err := json.Marshal(cfgGeneral)
440         if err != nil {
441                 return nil, err
442         }
443         var cfgJSON CfgJSON
444         if err = json.Unmarshal(marshaled, &cfgJSON); err != nil {
445                 return nil, err
446         }
447         if _, exists := cfgJSON.Neigh["self"]; !exists {
448                 return nil, errors.New("self neighbour missing")
449         }
450         var self *NodeOur
451         if cfgJSON.Self != nil {
452                 self, err = NewNodeOur(cfgJSON.Self)
453                 if err != nil {
454                         return nil, err
455                 }
456         }
457         spoolPath := path.Clean(cfgJSON.Spool)
458         if !path.IsAbs(spoolPath) {
459                 return nil, errors.New("Spool path must be absolute")
460         }
461         logPath := path.Clean(cfgJSON.Log)
462         if !path.IsAbs(logPath) {
463                 return nil, errors.New("Log path must be absolute")
464         }
465         var umaskForce *int
466         if cfgJSON.Umask != "" {
467                 r, err := strconv.ParseUint(cfgJSON.Umask, 8, 16)
468                 if err != nil {
469                         return nil, err
470                 }
471                 rInt := int(r)
472                 umaskForce = &rInt
473         }
474         showPrgrs := true
475         if cfgJSON.OmitPrgrs {
476                 showPrgrs = false
477         }
478         hdrUsage := true
479         if cfgJSON.NoHdr {
480                 hdrUsage = false
481         }
482         ctx := Ctx{
483                 Spool:      spoolPath,
484                 LogPath:    logPath,
485                 UmaskForce: umaskForce,
486                 ShowPrgrs:  showPrgrs,
487                 HdrUsage:   hdrUsage,
488                 Self:       self,
489                 Neigh:      make(map[NodeId]*Node, len(cfgJSON.Neigh)),
490                 Alias:      make(map[string]*NodeId),
491                 MCDRxIfis:  cfgJSON.MCDRxIfis,
492                 MCDTxIfis:  cfgJSON.MCDTxIfis,
493         }
494         if cfgJSON.Notify != nil {
495                 if cfgJSON.Notify.File != nil {
496                         ctx.NotifyFile = cfgJSON.Notify.File
497                 }
498                 if cfgJSON.Notify.Freq != nil {
499                         ctx.NotifyFreq = cfgJSON.Notify.Freq
500                 }
501                 if cfgJSON.Notify.Exec != nil {
502                         ctx.NotifyExec = cfgJSON.Notify.Exec
503                 }
504         }
505         vias := make(map[NodeId][]string)
506         for name, neighJSON := range cfgJSON.Neigh {
507                 neigh, err := NewNode(name, neighJSON)
508                 if err != nil {
509                         return nil, err
510                 }
511                 ctx.Neigh[*neigh.Id] = neigh
512                 if _, already := ctx.Alias[name]; already {
513                         return nil, errors.New("Node names conflict")
514                 }
515                 ctx.Alias[name] = neigh.Id
516                 vias[*neigh.Id] = neighJSON.Via
517         }
518         ctx.SelfId = ctx.Alias["self"]
519         for neighId, viasRaw := range vias {
520                 for _, viaRaw := range viasRaw {
521                         foundNodeId, err := ctx.FindNode(viaRaw)
522                         if err != nil {
523                                 return nil, err
524                         }
525                         ctx.Neigh[neighId].Via = append(
526                                 ctx.Neigh[neighId].Via,
527                                 foundNodeId.Id,
528                         )
529                 }
530         }
531         return &ctx, nil
532 }