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