]> Cypherpunks.ru repositories - nncp.git/blob - src/cfg.go
Unify copyright comment format
[nncp.git] / src / cfg.go
1 // NNCP -- Node to Node copy, utilities for store-and-forward data exchange
2 // Copyright (C) 2016-2024 Sergey Matveev <stargrave@stargrave.org>
3 //
4 // This program is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, version 3 of the License.
7 //
8 // This program is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11 // GNU General Public License for more details.
12 //
13 // You should have received a copy of the GNU General Public License
14 // along with this program.  If not, see <http://www.gnu.org/licenses/>.
15
16 package nncp
17
18 import (
19         "bytes"
20         "encoding/json"
21         "errors"
22         "fmt"
23         "log"
24         "os"
25         "path"
26         "strconv"
27         "time"
28
29         "github.com/gorhill/cronexpr"
30         "github.com/hjson/hjson-go/v4"
31         "golang.org/x/crypto/ed25519"
32         "golang.org/x/term"
33 )
34
35 const (
36         CfgPathEnv  = "NNCPCFG"
37         CfgSpoolEnv = "NNCPSPOOL"
38         CfgLogEnv   = "NNCPLOG"
39         CfgNoSync   = "NNCPNOSYNC"
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         Incoming *string             `json:"incoming,omitempty"`
55         Exec     map[string][]string `json:"exec,omitempty"`
56         Freq     *NodeFreqJSON       `json:"freq,omitempty"`
57         ACK      *NodeACKJSON        `json:"ack,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 NodeACKJSON struct {
77         MinSize *uint64 `json:"minsize,omitempty"`
78         Nice    *string `json:"nice,omitempty"`
79 }
80
81 type CallJSON struct {
82         Cron           string  `json:"cron"`
83         Nice           *string `json:"nice,omitempty"`
84         Xx             *string `json:"xx,omitempty"`
85         RxRate         *int    `json:"rxrate,omitempty"`
86         TxRate         *int    `json:"txrate,omitempty"`
87         Addr           *string `json:"addr,omitempty"`
88         OnlineDeadline *uint   `json:"onlinedeadline,omitempty"`
89         MaxOnlineTime  *uint   `json:"maxonlinetime,omitempty"`
90         WhenTxExists   bool    `json:"when-tx-exists,omitempty"`
91         NoCK           bool    `json:"nock,omitempty"`
92         MCDIgnore      bool    `json:"mcd-ignore,omitempty"`
93
94         AutoToss       bool `json:"autotoss,omitempty"`
95         AutoTossDoSeen bool `json:"autotoss-doseen,omitempty"`
96         AutoTossNoFile bool `json:"autotoss-nofile,omitempty"`
97         AutoTossNoFreq bool `json:"autotoss-nofreq,omitempty"`
98         AutoTossNoExec bool `json:"autotoss-noexec,omitempty"`
99         AutoTossNoTrns bool `json:"autotoss-notrns,omitempty"`
100         AutoTossNoArea bool `json:"autotoss-noarea,omitempty"`
101         AutoTossNoACK  bool `json:"autotoss-noack,omitempty"`
102         AutoTossGenACK bool `json:"autotoss-gen-ack,omitempty"`
103 }
104
105 type NodeOurJSON struct {
106         Id       string `json:"id"`
107         ExchPub  string `json:"exchpub"`
108         ExchPrv  string `json:"exchprv"`
109         SignPub  string `json:"signpub"`
110         SignPrv  string `json:"signprv"`
111         NoisePub string `json:"noisepub"`
112         NoisePrv string `json:"noiseprv"`
113 }
114
115 type FromToJSON struct {
116         From string `json:"from"`
117         To   string `json:"to"`
118 }
119
120 type NotifyJSON struct {
121         File *FromToJSON            `json:"file,omitempty"`
122         Freq *FromToJSON            `json:"freq,omitempty"`
123         Exec map[string]*FromToJSON `json:"exec,omitempty"`
124 }
125
126 type AreaJSON struct {
127         Id  string  `json:"id"`
128         Pub *string `json:"pub,omitempty"`
129         Prv *string `json:"prv,omitempty"`
130
131         Subs []string `json:"subs"`
132
133         Incoming *string             `json:"incoming,omitempty"`
134         Exec     map[string][]string `json:"exec,omitempty"`
135
136         AllowUnknown bool `json:"allow-unknown,omitempty"`
137 }
138
139 type CfgJSON struct {
140         Spool string  `json:"spool"`
141         Log   string  `json:"log"`
142         Umask *string `json:"umask,omitempty"`
143
144         OmitPrgrs bool `json:"noprogress,omitempty"`
145         NoHdr     bool `json:"nohdr,omitempty"`
146
147         MCDRxIfis []string       `json:"mcd-listen,omitempty"`
148         MCDTxIfis map[string]int `json:"mcd-send,omitempty"`
149
150         Notify *NotifyJSON `json:"notify,omitempty"`
151
152         Self  *NodeOurJSON        `json:"self"`
153         Neigh map[string]NodeJSON `json:"neigh"`
154
155         Areas map[string]AreaJSON `json:"areas,omitempty"`
156
157         YggdrasilAliases map[string]string `json:"yggdrasil-aliases,omitempty"`
158 }
159
160 func NewNode(name string, cfg NodeJSON) (*Node, error) {
161         nodeId, err := NodeIdFromString(cfg.Id)
162         if err != nil {
163                 return nil, err
164         }
165
166         exchPub, err := Base32Codec.DecodeString(cfg.ExchPub)
167         if err != nil {
168                 return nil, err
169         }
170         if len(exchPub) != 32 {
171                 return nil, errors.New("Invalid exchPub size")
172         }
173
174         signPub, err := Base32Codec.DecodeString(cfg.SignPub)
175         if err != nil {
176                 return nil, err
177         }
178         if len(signPub) != ed25519.PublicKeySize {
179                 return nil, errors.New("Invalid signPub size")
180         }
181
182         var noisePub []byte
183         if cfg.NoisePub != nil {
184                 noisePub, err = Base32Codec.DecodeString(*cfg.NoisePub)
185                 if err != nil {
186                         return nil, err
187                 }
188                 if len(noisePub) != 32 {
189                         return nil, errors.New("Invalid noisePub size")
190                 }
191         }
192
193         var incoming *string
194         if cfg.Incoming != nil {
195                 inc := path.Clean(*cfg.Incoming)
196                 if !path.IsAbs(inc) {
197                         return nil, errors.New("Incoming path must be absolute")
198                 }
199                 incoming = &inc
200         }
201
202         var freqPath *string
203         var freqChunked int64
204         var freqMinSize int64
205         freqMaxSize := int64(MaxFileSize)
206         if cfg.Freq != nil {
207                 f := cfg.Freq
208                 if f.Path != nil {
209                         fPath := path.Clean(*f.Path)
210                         if !path.IsAbs(fPath) {
211                                 return nil, errors.New("freq.path path must be absolute")
212                         }
213                         freqPath = &fPath
214                 }
215                 if f.Chunked != nil {
216                         if *f.Chunked == 0 {
217                                 return nil, errors.New("freq.chunked value must be greater than zero")
218                         }
219                         freqChunked = int64(*f.Chunked) * 1024
220                 }
221                 if f.MinSize != nil {
222                         freqMinSize = int64(*f.MinSize) * 1024
223                 }
224                 if f.MaxSize != nil {
225                         freqMaxSize = int64(*f.MaxSize) * 1024
226                 }
227         }
228
229         ackNice := uint8(255)
230         var ackMinSize int64
231         if cfg.ACK != nil {
232                 if cfg.ACK.Nice != nil {
233                         ackNice, err = NicenessParse(*cfg.ACK.Nice)
234                         if err != nil {
235                                 return nil, err
236                         }
237                 }
238                 if cfg.ACK.MinSize != nil {
239                         ackMinSize = int64(*cfg.ACK.MinSize) * 1024
240                 }
241         }
242
243         defRxRate := 0
244         if cfg.RxRate != nil && *cfg.RxRate > 0 {
245                 defRxRate = *cfg.RxRate
246         }
247         defTxRate := 0
248         if cfg.TxRate != nil && *cfg.TxRate > 0 {
249                 defTxRate = *cfg.TxRate
250         }
251
252         defOnlineDeadline := DefaultDeadline
253         if cfg.OnlineDeadline != nil {
254                 if *cfg.OnlineDeadline <= 0 {
255                         return nil, errors.New("OnlineDeadline must be at least 1 second")
256                 }
257                 defOnlineDeadline = time.Duration(*cfg.OnlineDeadline) * time.Second
258         }
259         var defMaxOnlineTime time.Duration
260         if cfg.MaxOnlineTime != nil {
261                 defMaxOnlineTime = time.Duration(*cfg.MaxOnlineTime) * time.Second
262         }
263
264         var calls []*Call
265         for _, callCfg := range cfg.Calls {
266                 expr, err := cronexpr.Parse(callCfg.Cron)
267                 if err != nil {
268                         return nil, err
269                 }
270
271                 nice := uint8(255)
272                 if callCfg.Nice != nil {
273                         nice, err = NicenessParse(*callCfg.Nice)
274                         if err != nil {
275                                 return nil, err
276                         }
277                 }
278
279                 var xx TRxTx
280                 if callCfg.Xx != nil {
281                         switch *callCfg.Xx {
282                         case "rx":
283                                 xx = TRx
284                         case "tx":
285                                 xx = TTx
286                         default:
287                                 return nil, errors.New("xx field must be either \"rx\" or \"tx\"")
288                         }
289                 }
290
291                 rxRate := defRxRate
292                 if callCfg.RxRate != nil {
293                         rxRate = *callCfg.RxRate
294                 }
295                 txRate := defTxRate
296                 if callCfg.TxRate != nil {
297                         txRate = *callCfg.TxRate
298                 }
299
300                 var addr *string
301                 if callCfg.Addr != nil {
302                         if a, exists := cfg.Addrs[*callCfg.Addr]; exists {
303                                 addr = &a
304                         } else {
305                                 addr = callCfg.Addr
306                         }
307                 }
308
309                 onlineDeadline := defOnlineDeadline
310                 if callCfg.OnlineDeadline != nil {
311                         if *callCfg.OnlineDeadline == 0 {
312                                 return nil, errors.New("OnlineDeadline must be at least 1 second")
313                         }
314                         onlineDeadline = time.Duration(*callCfg.OnlineDeadline) * time.Second
315                 }
316
317                 call := Call{
318                         Cron:           expr,
319                         Nice:           nice,
320                         Xx:             xx,
321                         RxRate:         rxRate,
322                         TxRate:         txRate,
323                         Addr:           addr,
324                         OnlineDeadline: onlineDeadline,
325                 }
326
327                 if callCfg.MaxOnlineTime != nil {
328                         call.MaxOnlineTime = time.Duration(*callCfg.MaxOnlineTime) * time.Second
329                 }
330                 call.WhenTxExists = callCfg.WhenTxExists
331                 call.NoCK = callCfg.NoCK
332                 call.MCDIgnore = callCfg.MCDIgnore
333                 call.AutoToss = callCfg.AutoToss
334                 call.AutoTossDoSeen = callCfg.AutoTossDoSeen
335                 call.AutoTossNoFile = callCfg.AutoTossNoFile
336                 call.AutoTossNoFreq = callCfg.AutoTossNoFreq
337                 call.AutoTossNoExec = callCfg.AutoTossNoExec
338                 call.AutoTossNoTrns = callCfg.AutoTossNoTrns
339                 call.AutoTossNoArea = callCfg.AutoTossNoArea
340                 call.AutoTossNoACK = callCfg.AutoTossNoACK
341                 call.AutoTossGenACK = callCfg.AutoTossGenACK
342
343                 calls = append(calls, &call)
344         }
345
346         node := Node{
347                 Name:           name,
348                 Id:             nodeId,
349                 ExchPub:        new([32]byte),
350                 SignPub:        ed25519.PublicKey(signPub),
351                 Exec:           cfg.Exec,
352                 Incoming:       incoming,
353                 FreqPath:       freqPath,
354                 FreqChunked:    freqChunked,
355                 FreqMinSize:    freqMinSize,
356                 FreqMaxSize:    freqMaxSize,
357                 ACKNice:        ackNice,
358                 ACKMinSize:     ackMinSize,
359                 Calls:          calls,
360                 Addrs:          cfg.Addrs,
361                 RxRate:         defRxRate,
362                 TxRate:         defTxRate,
363                 OnlineDeadline: defOnlineDeadline,
364                 MaxOnlineTime:  defMaxOnlineTime,
365         }
366         copy(node.ExchPub[:], exchPub)
367         if len(noisePub) > 0 {
368                 node.NoisePub = new([32]byte)
369                 copy(node.NoisePub[:], noisePub)
370         }
371         return &node, nil
372 }
373
374 func NewNodeOur(cfg *NodeOurJSON) (*NodeOur, error) {
375         id, err := NodeIdFromString(cfg.Id)
376         if err != nil {
377                 return nil, err
378         }
379
380         exchPub, err := Base32Codec.DecodeString(cfg.ExchPub)
381         if err != nil {
382                 return nil, err
383         }
384         if len(exchPub) != 32 {
385                 return nil, errors.New("Invalid exchPub size")
386         }
387
388         exchPrv, err := Base32Codec.DecodeString(cfg.ExchPrv)
389         if err != nil {
390                 return nil, err
391         }
392         if len(exchPrv) != 32 {
393                 return nil, errors.New("Invalid exchPrv size")
394         }
395
396         signPub, err := Base32Codec.DecodeString(cfg.SignPub)
397         if err != nil {
398                 return nil, err
399         }
400         if len(signPub) != ed25519.PublicKeySize {
401                 return nil, errors.New("Invalid signPub size")
402         }
403
404         signPrv, err := Base32Codec.DecodeString(cfg.SignPrv)
405         if err != nil {
406                 return nil, err
407         }
408         if len(signPrv) != ed25519.PrivateKeySize {
409                 return nil, errors.New("Invalid signPrv size")
410         }
411
412         noisePub, err := Base32Codec.DecodeString(cfg.NoisePub)
413         if err != nil {
414                 return nil, err
415         }
416         if len(noisePub) != 32 {
417                 return nil, errors.New("Invalid noisePub size")
418         }
419
420         noisePrv, err := Base32Codec.DecodeString(cfg.NoisePrv)
421         if err != nil {
422                 return nil, err
423         }
424         if len(noisePrv) != 32 {
425                 return nil, errors.New("Invalid noisePrv size")
426         }
427
428         node := NodeOur{
429                 Id:       id,
430                 ExchPub:  new([32]byte),
431                 ExchPrv:  new([32]byte),
432                 SignPub:  ed25519.PublicKey(signPub),
433                 SignPrv:  ed25519.PrivateKey(signPrv),
434                 NoisePub: new([32]byte),
435                 NoisePrv: new([32]byte),
436         }
437         copy(node.ExchPub[:], exchPub)
438         copy(node.ExchPrv[:], exchPrv)
439         copy(node.NoisePub[:], noisePub)
440         copy(node.NoisePrv[:], noisePrv)
441         return &node, nil
442 }
443
444 func NewArea(ctx *Ctx, name string, cfg *AreaJSON) (*Area, error) {
445         areaId, err := AreaIdFromString(cfg.Id)
446         if err != nil {
447                 return nil, err
448         }
449         subs := make([]*NodeId, 0, len(cfg.Subs))
450         for _, s := range cfg.Subs {
451                 node, err := ctx.FindNode(s)
452                 if err != nil {
453                         return nil, err
454                 }
455                 subs = append(subs, node.Id)
456         }
457         area := Area{
458                 Name:     name,
459                 Id:       areaId,
460                 Subs:     subs,
461                 Exec:     cfg.Exec,
462                 Incoming: cfg.Incoming,
463         }
464         if cfg.Pub != nil {
465                 pub, err := Base32Codec.DecodeString(*cfg.Pub)
466                 if err != nil {
467                         return nil, err
468                 }
469                 if len(pub) != 32 {
470                         return nil, errors.New("Invalid pub size")
471                 }
472                 area.Pub = new([32]byte)
473                 copy(area.Pub[:], pub)
474         }
475         if cfg.Prv != nil {
476                 if area.Pub == nil {
477                         return nil, fmt.Errorf("area %s: prv requires pub presence", name)
478                 }
479                 prv, err := Base32Codec.DecodeString(*cfg.Prv)
480                 if err != nil {
481                         return nil, err
482                 }
483                 if len(prv) != 32 {
484                         return nil, errors.New("Invalid prv size")
485                 }
486                 area.Prv = new([32]byte)
487                 copy(area.Prv[:], prv)
488         }
489         area.AllowUnknown = cfg.AllowUnknown
490         return &area, nil
491 }
492
493 func CfgParse(data []byte) (*CfgJSON, error) {
494         var err error
495         if bytes.Equal(data[:8], MagicNNCPBv3.B[:]) {
496                 os.Stderr.WriteString("Passphrase:")
497                 password, err := term.ReadPassword(0)
498                 if err != nil {
499                         log.Fatalln(err)
500                 }
501                 os.Stderr.WriteString("\n")
502                 data, err = DeEBlob(data, password)
503                 if err != nil {
504                         return nil, err
505                 }
506         } else if bytes.Equal(data[:8], MagicNNCPBv2.B[:]) {
507                 log.Fatalln(MagicNNCPBv2.TooOld())
508         } else if bytes.Equal(data[:8], MagicNNCPBv1.B[:]) {
509                 log.Fatalln(MagicNNCPBv1.TooOld())
510         }
511         var cfgGeneral map[string]interface{}
512         if err = hjson.Unmarshal(data, &cfgGeneral); err != nil {
513                 return nil, err
514         }
515         marshaled, err := json.Marshal(cfgGeneral)
516         if err != nil {
517                 return nil, err
518         }
519         var cfgJSON CfgJSON
520         err = json.Unmarshal(marshaled, &cfgJSON)
521         return &cfgJSON, err
522 }
523
524 func Cfg2Ctx(cfgJSON *CfgJSON) (*Ctx, error) {
525         if _, exists := cfgJSON.Neigh["self"]; !exists {
526                 return nil, errors.New("self neighbour missing")
527         }
528         var self *NodeOur
529         if cfgJSON.Self != nil {
530                 var err error
531                 self, err = NewNodeOur(cfgJSON.Self)
532                 if err != nil {
533                         return nil, err
534                 }
535         }
536         spoolPath := path.Clean(cfgJSON.Spool)
537         if !path.IsAbs(spoolPath) {
538                 return nil, errors.New("Spool path must be absolute")
539         }
540         logPath := path.Clean(cfgJSON.Log)
541         if !path.IsAbs(logPath) {
542                 return nil, errors.New("Log path must be absolute")
543         }
544         var umaskForce *int
545         if cfgJSON.Umask != nil {
546                 r, err := strconv.ParseUint(*cfgJSON.Umask, 8, 16)
547                 if err != nil {
548                         return nil, err
549                 }
550                 rInt := int(r)
551                 umaskForce = &rInt
552         }
553         showPrgrs := true
554         if cfgJSON.OmitPrgrs {
555                 showPrgrs = false
556         }
557         hdrUsage := true
558         if cfgJSON.NoHdr {
559                 hdrUsage = false
560         }
561         ctx := Ctx{
562                 Spool:      spoolPath,
563                 LogPath:    logPath,
564                 UmaskForce: umaskForce,
565                 ShowPrgrs:  showPrgrs,
566                 HdrUsage:   hdrUsage,
567                 Self:       self,
568                 Neigh:      make(map[NodeId]*Node, len(cfgJSON.Neigh)),
569                 Alias:      make(map[string]*NodeId),
570                 MCDRxIfis:  cfgJSON.MCDRxIfis,
571                 MCDTxIfis:  cfgJSON.MCDTxIfis,
572
573                 YggdrasilAliases: cfgJSON.YggdrasilAliases,
574         }
575         if cfgJSON.Notify != nil {
576                 if cfgJSON.Notify.File != nil {
577                         ctx.NotifyFile = cfgJSON.Notify.File
578                 }
579                 if cfgJSON.Notify.Freq != nil {
580                         ctx.NotifyFreq = cfgJSON.Notify.Freq
581                 }
582                 if cfgJSON.Notify.Exec != nil {
583                         ctx.NotifyExec = cfgJSON.Notify.Exec
584                 }
585         }
586         vias := make(map[NodeId][]string)
587         for name, neighJSON := range cfgJSON.Neigh {
588                 neigh, err := NewNode(name, neighJSON)
589                 if err != nil {
590                         return nil, err
591                 }
592                 ctx.Neigh[*neigh.Id] = neigh
593                 if _, already := ctx.Alias[name]; already {
594                         return nil, errors.New("Node names conflict")
595                 }
596                 ctx.Alias[name] = neigh.Id
597                 vias[*neigh.Id] = neighJSON.Via
598         }
599         ctx.SelfId = ctx.Alias["self"]
600         for neighId, viasRaw := range vias {
601                 for _, viaRaw := range viasRaw {
602                         foundNodeId, err := ctx.FindNode(viaRaw)
603                         if err != nil {
604                                 return nil, err
605                         }
606                         ctx.Neigh[neighId].Via = append(
607                                 ctx.Neigh[neighId].Via,
608                                 foundNodeId.Id,
609                         )
610                 }
611         }
612         ctx.AreaId2Area = make(map[AreaId]*Area, len(cfgJSON.Areas))
613         ctx.AreaName2Id = make(map[string]*AreaId, len(cfgJSON.Areas))
614         for name, areaJSON := range cfgJSON.Areas {
615                 area, err := NewArea(&ctx, name, &areaJSON)
616                 if err != nil {
617                         return nil, err
618                 }
619                 ctx.AreaId2Area[*area.Id] = area
620                 ctx.AreaName2Id[name] = area.Id
621         }
622         return &ctx, nil
623 }