]> Cypherpunks.ru repositories - nncp.git/blob - src/cfg.go
Raise copyright years
[nncp.git] / src / cfg.go
1 /*
2 NNCP -- Node to Node copy, utilities for store-and-forward data exchange
3 Copyright (C) 2016-2022 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         "fmt"
25         "log"
26         "os"
27         "path"
28         "strconv"
29         "time"
30
31         "github.com/gorhill/cronexpr"
32         "github.com/hjson/hjson-go"
33         "golang.org/x/crypto/ed25519"
34         "golang.org/x/term"
35 )
36
37 const (
38         CfgPathEnv  = "NNCPCFG"
39         CfgSpoolEnv = "NNCPSPOOL"
40         CfgLogEnv   = "NNCPLOG"
41 )
42
43 var (
44         DefaultCfgPath      string = "/usr/local/etc/nncp.hjson"
45         DefaultSendmailPath string = "/usr/sbin/sendmail"
46         DefaultSpoolPath    string = "/var/spool/nncp"
47         DefaultLogPath      string = "/var/spool/nncp/log"
48 )
49
50 type NodeJSON struct {
51         Id       string              `json:"id"`
52         ExchPub  string              `json:"exchpub"`
53         SignPub  string              `json:"signpub"`
54         NoisePub *string             `json:"noisepub,omitempty"`
55         Incoming *string             `json:"incoming,omitempty"`
56         Exec     map[string][]string `json:"exec,omitempty"`
57         Freq     *NodeFreqJSON       `json:"freq,omitempty"`
58         Via      []string            `json:"via,omitempty"`
59         Calls    []CallJSON          `json:"calls,omitempty"`
60
61         Addrs map[string]string `json:"addrs,omitempty"`
62
63         RxRate         *int  `json:"rxrate,omitempty"`
64         TxRate         *int  `json:"txrate,omitempty"`
65         OnlineDeadline *uint `json:"onlinedeadline,omitempty"`
66         MaxOnlineTime  *uint `json:"maxonlinetime,omitempty"`
67 }
68
69 type NodeFreqJSON struct {
70         Path    *string `json:"path,omitempty"`
71         Chunked *uint64 `json:"chunked,omitempty"`
72         MinSize *uint64 `json:"minsize,omitempty"`
73         MaxSize *uint64 `json:"maxsize,omitempty"`
74 }
75
76 type CallJSON struct {
77         Cron           string  `json:"cron"`
78         Nice           *string `json:"nice,omitempty"`
79         Xx             *string `json:"xx,omitempty"`
80         RxRate         *int    `json:"rxrate,omitempty"`
81         TxRate         *int    `json:"txrate,omitempty"`
82         Addr           *string `json:"addr,omitempty"`
83         OnlineDeadline *uint   `json:"onlinedeadline,omitempty"`
84         MaxOnlineTime  *uint   `json:"maxonlinetime,omitempty"`
85         WhenTxExists   bool    `json:"when-tx-exists,omitempty"`
86         NoCK           bool    `json:"nock,omitempty"`
87         MCDIgnore      bool    `json:"mcd-ignore,omitempty"`
88
89         AutoToss       bool `json:"autotoss,omitempty"`
90         AutoTossDoSeen bool `json:"autotoss-doseen,omitempty"`
91         AutoTossNoFile bool `json:"autotoss-nofile,omitempty"`
92         AutoTossNoFreq bool `json:"autotoss-nofreq,omitempty"`
93         AutoTossNoExec bool `json:"autotoss-noexec,omitempty"`
94         AutoTossNoTrns bool `json:"autotoss-notrns,omitempty"`
95         AutoTossNoArea bool `json:"autotoss-noarea,omitempty"`
96 }
97
98 type NodeOurJSON struct {
99         Id       string `json:"id"`
100         ExchPub  string `json:"exchpub"`
101         ExchPrv  string `json:"exchprv"`
102         SignPub  string `json:"signpub"`
103         SignPrv  string `json:"signprv"`
104         NoisePub string `json:"noisepub"`
105         NoisePrv string `json:"noiseprv"`
106 }
107
108 type FromToJSON struct {
109         From string `json:"from"`
110         To   string `json:"to"`
111 }
112
113 type NotifyJSON struct {
114         File *FromToJSON            `json:"file,omitempty"`
115         Freq *FromToJSON            `json:"freq,omitempty"`
116         Exec map[string]*FromToJSON `json:"exec,omitempty"`
117 }
118
119 type AreaJSON struct {
120         Id  string  `json:"id"`
121         Pub *string `json:"pub,omitempty"`
122         Prv *string `json:"prv,omitempty"`
123
124         Subs []string `json:"subs"`
125
126         Incoming *string             `json:"incoming,omitempty"`
127         Exec     map[string][]string `json:"exec,omitempty"`
128
129         AllowUnknown bool `json:"allow-unknown,omitempty"`
130 }
131
132 type CfgJSON struct {
133         Spool string  `json:"spool"`
134         Log   string  `json:"log"`
135         Umask *string `json:"umask,omitempty"`
136
137         OmitPrgrs bool `json:"noprogress,omitempty"`
138         NoHdr     bool `json:"nohdr,omitempty"`
139
140         MCDRxIfis []string       `json:"mcd-listen,omitempty"`
141         MCDTxIfis map[string]int `json:"mcd-send,omitempty"`
142
143         Notify *NotifyJSON `json:"notify,omitempty"`
144
145         Self  *NodeOurJSON        `json:"self"`
146         Neigh map[string]NodeJSON `json:"neigh"`
147
148         Areas map[string]AreaJSON `json:"areas,omitempty"`
149 }
150
151 func NewNode(name string, cfg NodeJSON) (*Node, error) {
152         nodeId, err := NodeIdFromString(cfg.Id)
153         if err != nil {
154                 return nil, err
155         }
156
157         exchPub, err := Base32Codec.DecodeString(cfg.ExchPub)
158         if err != nil {
159                 return nil, err
160         }
161         if len(exchPub) != 32 {
162                 return nil, errors.New("Invalid exchPub size")
163         }
164
165         signPub, err := Base32Codec.DecodeString(cfg.SignPub)
166         if err != nil {
167                 return nil, err
168         }
169         if len(signPub) != ed25519.PublicKeySize {
170                 return nil, errors.New("Invalid signPub size")
171         }
172
173         var noisePub []byte
174         if cfg.NoisePub != nil {
175                 noisePub, err = Base32Codec.DecodeString(*cfg.NoisePub)
176                 if err != nil {
177                         return nil, err
178                 }
179                 if len(noisePub) != 32 {
180                         return nil, errors.New("Invalid noisePub size")
181                 }
182         }
183
184         var incoming *string
185         if cfg.Incoming != nil {
186                 inc := path.Clean(*cfg.Incoming)
187                 if !path.IsAbs(inc) {
188                         return nil, errors.New("Incoming path must be absolute")
189                 }
190                 incoming = &inc
191         }
192
193         var freqPath *string
194         var freqChunked int64
195         var freqMinSize int64
196         freqMaxSize := int64(MaxFileSize)
197         if cfg.Freq != nil {
198                 f := cfg.Freq
199                 if f.Path != nil {
200                         fPath := path.Clean(*f.Path)
201                         if !path.IsAbs(fPath) {
202                                 return nil, errors.New("freq.path path must be absolute")
203                         }
204                         freqPath = &fPath
205                 }
206                 if f.Chunked != nil {
207                         if *f.Chunked == 0 {
208                                 return nil, errors.New("freq.chunked value must be greater than zero")
209                         }
210                         freqChunked = int64(*f.Chunked) * 1024
211                 }
212                 if f.MinSize != nil {
213                         freqMinSize = int64(*f.MinSize) * 1024
214                 }
215                 if f.MaxSize != nil {
216                         freqMaxSize = int64(*f.MaxSize) * 1024
217                 }
218         }
219
220         defRxRate := 0
221         if cfg.RxRate != nil && *cfg.RxRate > 0 {
222                 defRxRate = *cfg.RxRate
223         }
224         defTxRate := 0
225         if cfg.TxRate != nil && *cfg.TxRate > 0 {
226                 defTxRate = *cfg.TxRate
227         }
228
229         defOnlineDeadline := DefaultDeadline
230         if cfg.OnlineDeadline != nil {
231                 if *cfg.OnlineDeadline <= 0 {
232                         return nil, errors.New("OnlineDeadline must be at least 1 second")
233                 }
234                 defOnlineDeadline = time.Duration(*cfg.OnlineDeadline) * time.Second
235         }
236         var defMaxOnlineTime time.Duration
237         if cfg.MaxOnlineTime != nil {
238                 defMaxOnlineTime = time.Duration(*cfg.MaxOnlineTime) * time.Second
239         }
240
241         var calls []*Call
242         for _, callCfg := range cfg.Calls {
243                 expr, err := cronexpr.Parse(callCfg.Cron)
244                 if err != nil {
245                         return nil, err
246                 }
247
248                 nice := uint8(255)
249                 if callCfg.Nice != nil {
250                         nice, err = NicenessParse(*callCfg.Nice)
251                         if err != nil {
252                                 return nil, err
253                         }
254                 }
255
256                 var xx TRxTx
257                 if callCfg.Xx != nil {
258                         switch *callCfg.Xx {
259                         case "rx":
260                                 xx = TRx
261                         case "tx":
262                                 xx = TTx
263                         default:
264                                 return nil, errors.New("xx field must be either \"rx\" or \"tx\"")
265                         }
266                 }
267
268                 rxRate := defRxRate
269                 if callCfg.RxRate != nil {
270                         rxRate = *callCfg.RxRate
271                 }
272                 txRate := defTxRate
273                 if callCfg.TxRate != nil {
274                         txRate = *callCfg.TxRate
275                 }
276
277                 var addr *string
278                 if callCfg.Addr != nil {
279                         if a, exists := cfg.Addrs[*callCfg.Addr]; exists {
280                                 addr = &a
281                         } else {
282                                 addr = callCfg.Addr
283                         }
284                 }
285
286                 onlineDeadline := defOnlineDeadline
287                 if callCfg.OnlineDeadline != nil {
288                         if *callCfg.OnlineDeadline == 0 {
289                                 return nil, errors.New("OnlineDeadline must be at least 1 second")
290                         }
291                         onlineDeadline = time.Duration(*callCfg.OnlineDeadline) * time.Second
292                 }
293
294                 call := Call{
295                         Cron:           expr,
296                         Nice:           nice,
297                         Xx:             xx,
298                         RxRate:         rxRate,
299                         TxRate:         txRate,
300                         Addr:           addr,
301                         OnlineDeadline: onlineDeadline,
302                 }
303
304                 if callCfg.MaxOnlineTime != nil {
305                         call.MaxOnlineTime = time.Duration(*callCfg.MaxOnlineTime) * time.Second
306                 }
307                 call.WhenTxExists = callCfg.WhenTxExists
308                 call.NoCK = callCfg.NoCK
309                 call.MCDIgnore = callCfg.MCDIgnore
310                 call.AutoToss = callCfg.AutoToss
311                 call.AutoTossDoSeen = callCfg.AutoTossDoSeen
312                 call.AutoTossNoFile = callCfg.AutoTossNoFile
313                 call.AutoTossNoFreq = callCfg.AutoTossNoFreq
314                 call.AutoTossNoExec = callCfg.AutoTossNoExec
315                 call.AutoTossNoTrns = callCfg.AutoTossNoTrns
316                 call.AutoTossNoArea = callCfg.AutoTossNoArea
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 NewArea(ctx *Ctx, name string, cfg *AreaJSON) (*Area, error) {
418         areaId, err := AreaIdFromString(cfg.Id)
419         if err != nil {
420                 return nil, err
421         }
422         subs := make([]*NodeId, 0, len(cfg.Subs))
423         for _, s := range cfg.Subs {
424                 node, err := ctx.FindNode(s)
425                 if err != nil {
426                         return nil, err
427                 }
428                 subs = append(subs, node.Id)
429         }
430         area := Area{
431                 Name:     name,
432                 Id:       areaId,
433                 Subs:     subs,
434                 Exec:     cfg.Exec,
435                 Incoming: cfg.Incoming,
436         }
437         if cfg.Pub != nil {
438                 pub, err := Base32Codec.DecodeString(*cfg.Pub)
439                 if err != nil {
440                         return nil, err
441                 }
442                 if len(pub) != 32 {
443                         return nil, errors.New("Invalid pub size")
444                 }
445                 area.Pub = new([32]byte)
446                 copy(area.Pub[:], pub)
447         }
448         if cfg.Prv != nil {
449                 if area.Pub == nil {
450                         return nil, fmt.Errorf("area %s: prv requires pub presence", name)
451                 }
452                 prv, err := Base32Codec.DecodeString(*cfg.Prv)
453                 if err != nil {
454                         return nil, err
455                 }
456                 if len(prv) != 32 {
457                         return nil, errors.New("Invalid prv size")
458                 }
459                 area.Prv = new([32]byte)
460                 copy(area.Prv[:], prv)
461         }
462         area.AllowUnknown = cfg.AllowUnknown
463         return &area, nil
464 }
465
466 func CfgParse(data []byte) (*CfgJSON, error) {
467         var err error
468         if bytes.Compare(data[:8], MagicNNCPBv3.B[:]) == 0 {
469                 os.Stderr.WriteString("Passphrase:")
470                 password, err := term.ReadPassword(0)
471                 if err != nil {
472                         log.Fatalln(err)
473                 }
474                 os.Stderr.WriteString("\n")
475                 data, err = DeEBlob(data, password)
476                 if err != nil {
477                         return nil, err
478                 }
479         } else if bytes.Compare(data[:8], MagicNNCPBv2.B[:]) == 0 {
480                 log.Fatalln(MagicNNCPBv2.TooOld())
481         } else if bytes.Compare(data[:8], MagicNNCPBv1.B[:]) == 0 {
482                 log.Fatalln(MagicNNCPBv1.TooOld())
483         }
484         var cfgGeneral map[string]interface{}
485         if err = hjson.Unmarshal(data, &cfgGeneral); err != nil {
486                 return nil, err
487         }
488         marshaled, err := json.Marshal(cfgGeneral)
489         if err != nil {
490                 return nil, err
491         }
492         var cfgJSON CfgJSON
493         err = json.Unmarshal(marshaled, &cfgJSON)
494         return &cfgJSON, err
495 }
496
497 func Cfg2Ctx(cfgJSON *CfgJSON) (*Ctx, error) {
498         if _, exists := cfgJSON.Neigh["self"]; !exists {
499                 return nil, errors.New("self neighbour missing")
500         }
501         var self *NodeOur
502         if cfgJSON.Self != nil {
503                 var err error
504                 self, err = NewNodeOur(cfgJSON.Self)
505                 if err != nil {
506                         return nil, err
507                 }
508         }
509         spoolPath := path.Clean(cfgJSON.Spool)
510         if !path.IsAbs(spoolPath) {
511                 return nil, errors.New("Spool path must be absolute")
512         }
513         logPath := path.Clean(cfgJSON.Log)
514         if !path.IsAbs(logPath) {
515                 return nil, errors.New("Log path must be absolute")
516         }
517         var umaskForce *int
518         if cfgJSON.Umask != nil {
519                 r, err := strconv.ParseUint(*cfgJSON.Umask, 8, 16)
520                 if err != nil {
521                         return nil, err
522                 }
523                 rInt := int(r)
524                 umaskForce = &rInt
525         }
526         showPrgrs := true
527         if cfgJSON.OmitPrgrs {
528                 showPrgrs = false
529         }
530         hdrUsage := true
531         if cfgJSON.NoHdr {
532                 hdrUsage = false
533         }
534         ctx := Ctx{
535                 Spool:      spoolPath,
536                 LogPath:    logPath,
537                 UmaskForce: umaskForce,
538                 ShowPrgrs:  showPrgrs,
539                 HdrUsage:   hdrUsage,
540                 Self:       self,
541                 Neigh:      make(map[NodeId]*Node, len(cfgJSON.Neigh)),
542                 Alias:      make(map[string]*NodeId),
543                 MCDRxIfis:  cfgJSON.MCDRxIfis,
544                 MCDTxIfis:  cfgJSON.MCDTxIfis,
545         }
546         if cfgJSON.Notify != nil {
547                 if cfgJSON.Notify.File != nil {
548                         ctx.NotifyFile = cfgJSON.Notify.File
549                 }
550                 if cfgJSON.Notify.Freq != nil {
551                         ctx.NotifyFreq = cfgJSON.Notify.Freq
552                 }
553                 if cfgJSON.Notify.Exec != nil {
554                         ctx.NotifyExec = cfgJSON.Notify.Exec
555                 }
556         }
557         vias := make(map[NodeId][]string)
558         for name, neighJSON := range cfgJSON.Neigh {
559                 neigh, err := NewNode(name, neighJSON)
560                 if err != nil {
561                         return nil, err
562                 }
563                 ctx.Neigh[*neigh.Id] = neigh
564                 if _, already := ctx.Alias[name]; already {
565                         return nil, errors.New("Node names conflict")
566                 }
567                 ctx.Alias[name] = neigh.Id
568                 vias[*neigh.Id] = neighJSON.Via
569         }
570         ctx.SelfId = ctx.Alias["self"]
571         for neighId, viasRaw := range vias {
572                 for _, viaRaw := range viasRaw {
573                         foundNodeId, err := ctx.FindNode(viaRaw)
574                         if err != nil {
575                                 return nil, err
576                         }
577                         ctx.Neigh[neighId].Via = append(
578                                 ctx.Neigh[neighId].Via,
579                                 foundNodeId.Id,
580                         )
581                 }
582         }
583         ctx.AreaId2Area = make(map[AreaId]*Area, len(cfgJSON.Areas))
584         ctx.AreaName2Id = make(map[string]*AreaId, len(cfgJSON.Areas))
585         for name, areaJSON := range cfgJSON.Areas {
586                 area, err := NewArea(&ctx, name, &areaJSON)
587                 if err != nil {
588                         return nil, err
589                 }
590                 ctx.AreaId2Area[*area.Id] = area
591                 ctx.AreaName2Id[name] = area.Id
592         }
593         return &ctx, nil
594 }