]> Cypherpunks.ru repositories - nncp.git/blob - src/cfg.go
Yggdrasil overlay transport
[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         YggdrasilAliases map[string]string `json:"yggdrasil-aliases,omitempty"`
151 }
152
153 func NewNode(name string, cfg NodeJSON) (*Node, error) {
154         nodeId, err := NodeIdFromString(cfg.Id)
155         if err != nil {
156                 return nil, err
157         }
158
159         exchPub, err := Base32Codec.DecodeString(cfg.ExchPub)
160         if err != nil {
161                 return nil, err
162         }
163         if len(exchPub) != 32 {
164                 return nil, errors.New("Invalid exchPub size")
165         }
166
167         signPub, err := Base32Codec.DecodeString(cfg.SignPub)
168         if err != nil {
169                 return nil, err
170         }
171         if len(signPub) != ed25519.PublicKeySize {
172                 return nil, errors.New("Invalid signPub size")
173         }
174
175         var noisePub []byte
176         if cfg.NoisePub != nil {
177                 noisePub, err = Base32Codec.DecodeString(*cfg.NoisePub)
178                 if err != nil {
179                         return nil, err
180                 }
181                 if len(noisePub) != 32 {
182                         return nil, errors.New("Invalid noisePub size")
183                 }
184         }
185
186         var incoming *string
187         if cfg.Incoming != nil {
188                 inc := path.Clean(*cfg.Incoming)
189                 if !path.IsAbs(inc) {
190                         return nil, errors.New("Incoming path must be absolute")
191                 }
192                 incoming = &inc
193         }
194
195         var freqPath *string
196         var freqChunked int64
197         var freqMinSize int64
198         freqMaxSize := int64(MaxFileSize)
199         if cfg.Freq != nil {
200                 f := cfg.Freq
201                 if f.Path != nil {
202                         fPath := path.Clean(*f.Path)
203                         if !path.IsAbs(fPath) {
204                                 return nil, errors.New("freq.path path must be absolute")
205                         }
206                         freqPath = &fPath
207                 }
208                 if f.Chunked != nil {
209                         if *f.Chunked == 0 {
210                                 return nil, errors.New("freq.chunked value must be greater than zero")
211                         }
212                         freqChunked = int64(*f.Chunked) * 1024
213                 }
214                 if f.MinSize != nil {
215                         freqMinSize = int64(*f.MinSize) * 1024
216                 }
217                 if f.MaxSize != nil {
218                         freqMaxSize = int64(*f.MaxSize) * 1024
219                 }
220         }
221
222         defRxRate := 0
223         if cfg.RxRate != nil && *cfg.RxRate > 0 {
224                 defRxRate = *cfg.RxRate
225         }
226         defTxRate := 0
227         if cfg.TxRate != nil && *cfg.TxRate > 0 {
228                 defTxRate = *cfg.TxRate
229         }
230
231         defOnlineDeadline := DefaultDeadline
232         if cfg.OnlineDeadline != nil {
233                 if *cfg.OnlineDeadline <= 0 {
234                         return nil, errors.New("OnlineDeadline must be at least 1 second")
235                 }
236                 defOnlineDeadline = time.Duration(*cfg.OnlineDeadline) * time.Second
237         }
238         var defMaxOnlineTime time.Duration
239         if cfg.MaxOnlineTime != nil {
240                 defMaxOnlineTime = time.Duration(*cfg.MaxOnlineTime) * time.Second
241         }
242
243         var calls []*Call
244         for _, callCfg := range cfg.Calls {
245                 expr, err := cronexpr.Parse(callCfg.Cron)
246                 if err != nil {
247                         return nil, err
248                 }
249
250                 nice := uint8(255)
251                 if callCfg.Nice != nil {
252                         nice, err = NicenessParse(*callCfg.Nice)
253                         if err != nil {
254                                 return nil, err
255                         }
256                 }
257
258                 var xx TRxTx
259                 if callCfg.Xx != nil {
260                         switch *callCfg.Xx {
261                         case "rx":
262                                 xx = TRx
263                         case "tx":
264                                 xx = TTx
265                         default:
266                                 return nil, errors.New("xx field must be either \"rx\" or \"tx\"")
267                         }
268                 }
269
270                 rxRate := defRxRate
271                 if callCfg.RxRate != nil {
272                         rxRate = *callCfg.RxRate
273                 }
274                 txRate := defTxRate
275                 if callCfg.TxRate != nil {
276                         txRate = *callCfg.TxRate
277                 }
278
279                 var addr *string
280                 if callCfg.Addr != nil {
281                         if a, exists := cfg.Addrs[*callCfg.Addr]; exists {
282                                 addr = &a
283                         } else {
284                                 addr = callCfg.Addr
285                         }
286                 }
287
288                 onlineDeadline := defOnlineDeadline
289                 if callCfg.OnlineDeadline != nil {
290                         if *callCfg.OnlineDeadline == 0 {
291                                 return nil, errors.New("OnlineDeadline must be at least 1 second")
292                         }
293                         onlineDeadline = time.Duration(*callCfg.OnlineDeadline) * time.Second
294                 }
295
296                 call := Call{
297                         Cron:           expr,
298                         Nice:           nice,
299                         Xx:             xx,
300                         RxRate:         rxRate,
301                         TxRate:         txRate,
302                         Addr:           addr,
303                         OnlineDeadline: onlineDeadline,
304                 }
305
306                 if callCfg.MaxOnlineTime != nil {
307                         call.MaxOnlineTime = time.Duration(*callCfg.MaxOnlineTime) * time.Second
308                 }
309                 call.WhenTxExists = callCfg.WhenTxExists
310                 call.NoCK = callCfg.NoCK
311                 call.MCDIgnore = callCfg.MCDIgnore
312                 call.AutoToss = callCfg.AutoToss
313                 call.AutoTossDoSeen = callCfg.AutoTossDoSeen
314                 call.AutoTossNoFile = callCfg.AutoTossNoFile
315                 call.AutoTossNoFreq = callCfg.AutoTossNoFreq
316                 call.AutoTossNoExec = callCfg.AutoTossNoExec
317                 call.AutoTossNoTrns = callCfg.AutoTossNoTrns
318                 call.AutoTossNoArea = callCfg.AutoTossNoArea
319
320                 calls = append(calls, &call)
321         }
322
323         node := Node{
324                 Name:           name,
325                 Id:             nodeId,
326                 ExchPub:        new([32]byte),
327                 SignPub:        ed25519.PublicKey(signPub),
328                 Exec:           cfg.Exec,
329                 Incoming:       incoming,
330                 FreqPath:       freqPath,
331                 FreqChunked:    freqChunked,
332                 FreqMinSize:    freqMinSize,
333                 FreqMaxSize:    freqMaxSize,
334                 Calls:          calls,
335                 Addrs:          cfg.Addrs,
336                 RxRate:         defRxRate,
337                 TxRate:         defTxRate,
338                 OnlineDeadline: defOnlineDeadline,
339                 MaxOnlineTime:  defMaxOnlineTime,
340         }
341         copy(node.ExchPub[:], exchPub)
342         if len(noisePub) > 0 {
343                 node.NoisePub = new([32]byte)
344                 copy(node.NoisePub[:], noisePub)
345         }
346         return &node, nil
347 }
348
349 func NewNodeOur(cfg *NodeOurJSON) (*NodeOur, error) {
350         id, err := NodeIdFromString(cfg.Id)
351         if err != nil {
352                 return nil, err
353         }
354
355         exchPub, err := Base32Codec.DecodeString(cfg.ExchPub)
356         if err != nil {
357                 return nil, err
358         }
359         if len(exchPub) != 32 {
360                 return nil, errors.New("Invalid exchPub size")
361         }
362
363         exchPrv, err := Base32Codec.DecodeString(cfg.ExchPrv)
364         if err != nil {
365                 return nil, err
366         }
367         if len(exchPrv) != 32 {
368                 return nil, errors.New("Invalid exchPrv size")
369         }
370
371         signPub, err := Base32Codec.DecodeString(cfg.SignPub)
372         if err != nil {
373                 return nil, err
374         }
375         if len(signPub) != ed25519.PublicKeySize {
376                 return nil, errors.New("Invalid signPub size")
377         }
378
379         signPrv, err := Base32Codec.DecodeString(cfg.SignPrv)
380         if err != nil {
381                 return nil, err
382         }
383         if len(signPrv) != ed25519.PrivateKeySize {
384                 return nil, errors.New("Invalid signPrv size")
385         }
386
387         noisePub, err := Base32Codec.DecodeString(cfg.NoisePub)
388         if err != nil {
389                 return nil, err
390         }
391         if len(noisePub) != 32 {
392                 return nil, errors.New("Invalid noisePub size")
393         }
394
395         noisePrv, err := Base32Codec.DecodeString(cfg.NoisePrv)
396         if err != nil {
397                 return nil, err
398         }
399         if len(noisePrv) != 32 {
400                 return nil, errors.New("Invalid noisePrv size")
401         }
402
403         node := NodeOur{
404                 Id:       id,
405                 ExchPub:  new([32]byte),
406                 ExchPrv:  new([32]byte),
407                 SignPub:  ed25519.PublicKey(signPub),
408                 SignPrv:  ed25519.PrivateKey(signPrv),
409                 NoisePub: new([32]byte),
410                 NoisePrv: new([32]byte),
411         }
412         copy(node.ExchPub[:], exchPub)
413         copy(node.ExchPrv[:], exchPrv)
414         copy(node.NoisePub[:], noisePub)
415         copy(node.NoisePrv[:], noisePrv)
416         return &node, nil
417 }
418
419 func NewArea(ctx *Ctx, name string, cfg *AreaJSON) (*Area, error) {
420         areaId, err := AreaIdFromString(cfg.Id)
421         if err != nil {
422                 return nil, err
423         }
424         subs := make([]*NodeId, 0, len(cfg.Subs))
425         for _, s := range cfg.Subs {
426                 node, err := ctx.FindNode(s)
427                 if err != nil {
428                         return nil, err
429                 }
430                 subs = append(subs, node.Id)
431         }
432         area := Area{
433                 Name:     name,
434                 Id:       areaId,
435                 Subs:     subs,
436                 Exec:     cfg.Exec,
437                 Incoming: cfg.Incoming,
438         }
439         if cfg.Pub != nil {
440                 pub, err := Base32Codec.DecodeString(*cfg.Pub)
441                 if err != nil {
442                         return nil, err
443                 }
444                 if len(pub) != 32 {
445                         return nil, errors.New("Invalid pub size")
446                 }
447                 area.Pub = new([32]byte)
448                 copy(area.Pub[:], pub)
449         }
450         if cfg.Prv != nil {
451                 if area.Pub == nil {
452                         return nil, fmt.Errorf("area %s: prv requires pub presence", name)
453                 }
454                 prv, err := Base32Codec.DecodeString(*cfg.Prv)
455                 if err != nil {
456                         return nil, err
457                 }
458                 if len(prv) != 32 {
459                         return nil, errors.New("Invalid prv size")
460                 }
461                 area.Prv = new([32]byte)
462                 copy(area.Prv[:], prv)
463         }
464         area.AllowUnknown = cfg.AllowUnknown
465         return &area, nil
466 }
467
468 func CfgParse(data []byte) (*CfgJSON, error) {
469         var err error
470         if bytes.Compare(data[:8], MagicNNCPBv3.B[:]) == 0 {
471                 os.Stderr.WriteString("Passphrase:")
472                 password, err := term.ReadPassword(0)
473                 if err != nil {
474                         log.Fatalln(err)
475                 }
476                 os.Stderr.WriteString("\n")
477                 data, err = DeEBlob(data, password)
478                 if err != nil {
479                         return nil, err
480                 }
481         } else if bytes.Compare(data[:8], MagicNNCPBv2.B[:]) == 0 {
482                 log.Fatalln(MagicNNCPBv2.TooOld())
483         } else if bytes.Compare(data[:8], MagicNNCPBv1.B[:]) == 0 {
484                 log.Fatalln(MagicNNCPBv1.TooOld())
485         }
486         var cfgGeneral map[string]interface{}
487         if err = hjson.Unmarshal(data, &cfgGeneral); err != nil {
488                 return nil, err
489         }
490         marshaled, err := json.Marshal(cfgGeneral)
491         if err != nil {
492                 return nil, err
493         }
494         var cfgJSON CfgJSON
495         err = json.Unmarshal(marshaled, &cfgJSON)
496         return &cfgJSON, err
497 }
498
499 func Cfg2Ctx(cfgJSON *CfgJSON) (*Ctx, error) {
500         if _, exists := cfgJSON.Neigh["self"]; !exists {
501                 return nil, errors.New("self neighbour missing")
502         }
503         var self *NodeOur
504         if cfgJSON.Self != nil {
505                 var err error
506                 self, err = NewNodeOur(cfgJSON.Self)
507                 if err != nil {
508                         return nil, err
509                 }
510         }
511         spoolPath := path.Clean(cfgJSON.Spool)
512         if !path.IsAbs(spoolPath) {
513                 return nil, errors.New("Spool path must be absolute")
514         }
515         logPath := path.Clean(cfgJSON.Log)
516         if !path.IsAbs(logPath) {
517                 return nil, errors.New("Log path must be absolute")
518         }
519         var umaskForce *int
520         if cfgJSON.Umask != nil {
521                 r, err := strconv.ParseUint(*cfgJSON.Umask, 8, 16)
522                 if err != nil {
523                         return nil, err
524                 }
525                 rInt := int(r)
526                 umaskForce = &rInt
527         }
528         showPrgrs := true
529         if cfgJSON.OmitPrgrs {
530                 showPrgrs = false
531         }
532         hdrUsage := true
533         if cfgJSON.NoHdr {
534                 hdrUsage = false
535         }
536         ctx := Ctx{
537                 Spool:      spoolPath,
538                 LogPath:    logPath,
539                 UmaskForce: umaskForce,
540                 ShowPrgrs:  showPrgrs,
541                 HdrUsage:   hdrUsage,
542                 Self:       self,
543                 Neigh:      make(map[NodeId]*Node, len(cfgJSON.Neigh)),
544                 Alias:      make(map[string]*NodeId),
545                 MCDRxIfis:  cfgJSON.MCDRxIfis,
546                 MCDTxIfis:  cfgJSON.MCDTxIfis,
547
548                 YggdrasilAliases: cfgJSON.YggdrasilAliases,
549         }
550         if cfgJSON.Notify != nil {
551                 if cfgJSON.Notify.File != nil {
552                         ctx.NotifyFile = cfgJSON.Notify.File
553                 }
554                 if cfgJSON.Notify.Freq != nil {
555                         ctx.NotifyFreq = cfgJSON.Notify.Freq
556                 }
557                 if cfgJSON.Notify.Exec != nil {
558                         ctx.NotifyExec = cfgJSON.Notify.Exec
559                 }
560         }
561         vias := make(map[NodeId][]string)
562         for name, neighJSON := range cfgJSON.Neigh {
563                 neigh, err := NewNode(name, neighJSON)
564                 if err != nil {
565                         return nil, err
566                 }
567                 ctx.Neigh[*neigh.Id] = neigh
568                 if _, already := ctx.Alias[name]; already {
569                         return nil, errors.New("Node names conflict")
570                 }
571                 ctx.Alias[name] = neigh.Id
572                 vias[*neigh.Id] = neighJSON.Via
573         }
574         ctx.SelfId = ctx.Alias["self"]
575         for neighId, viasRaw := range vias {
576                 for _, viaRaw := range viasRaw {
577                         foundNodeId, err := ctx.FindNode(viaRaw)
578                         if err != nil {
579                                 return nil, err
580                         }
581                         ctx.Neigh[neighId].Via = append(
582                                 ctx.Neigh[neighId].Via,
583                                 foundNodeId.Id,
584                         )
585                 }
586         }
587         ctx.AreaId2Area = make(map[AreaId]*Area, len(cfgJSON.Areas))
588         ctx.AreaName2Id = make(map[string]*AreaId, len(cfgJSON.Areas))
589         for name, areaJSON := range cfgJSON.Areas {
590                 area, err := NewArea(&ctx, name, &areaJSON)
591                 if err != nil {
592                         return nil, err
593                 }
594                 ctx.AreaId2Area[*area.Id] = area
595                 ctx.AreaName2Id[name] = area.Id
596         }
597         return &ctx, nil
598 }