]> Cypherpunks.ru repositories - nncp.git/blob - src/cfg.go
.hdr files
[nncp.git] / src / cfg.go
1 /*
2 NNCP -- Node to Node copy, utilities for store-and-forward data exchange
3 Copyright (C) 2016-2021 Sergey Matveev <stargrave@stargrave.org>
4
5 This program is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation, version 3 of the License.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 GNU General Public License for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with this program.  If not, see <http://www.gnu.org/licenses/>.
16 */
17
18 package nncp
19
20 import (
21         "bytes"
22         "encoding/json"
23         "errors"
24         "log"
25         "os"
26         "path"
27         "strconv"
28         "time"
29
30         "github.com/gorhill/cronexpr"
31         "github.com/hjson/hjson-go"
32         "golang.org/x/crypto/ed25519"
33         "golang.org/x/term"
34 )
35
36 const (
37         CfgPathEnv  = "NNCPCFG"
38         CfgSpoolEnv = "NNCPSPOOL"
39         CfgLogEnv   = "NNCPLOG"
40 )
41
42 var (
43         DefaultCfgPath      string = "/usr/local/etc/nncp.hjson"
44         DefaultSendmailPath string = "/usr/sbin/sendmail"
45         DefaultSpoolPath    string = "/var/spool/nncp"
46         DefaultLogPath      string = "/var/spool/nncp/log"
47 )
48
49 type NodeJSON struct {
50         Id       string              `json:"id"`
51         ExchPub  string              `json:"exchpub"`
52         SignPub  string              `json:"signpub"`
53         NoisePub *string             `json:"noisepub,omitempty"`
54         Exec     map[string][]string `json:"exec,omitempty"`
55         Incoming *string             `json:"incoming,omitempty"`
56         Freq     *NodeFreqJSON       `json:"freq,omitempty"`
57         Via      []string            `json:"via,omitempty"`
58         Calls    []CallJSON          `json:"calls,omitempty"`
59
60         Addrs map[string]string `json:"addrs,omitempty"`
61
62         RxRate         *int  `json:"rxrate,omitempty"`
63         TxRate         *int  `json:"txrate,omitempty"`
64         OnlineDeadline *uint `json:"onlinedeadline,omitempty"`
65         MaxOnlineTime  *uint `json:"maxonlinetime,omitempty"`
66 }
67
68 type NodeFreqJSON struct {
69         Path    *string `json:"path,omitempty"`
70         Chunked *uint64 `json:"chunked,omitempty"`
71         MinSize *uint64 `json:"minsize,omitempty"`
72         MaxSize *uint64 `json:"maxsize,omitempty"`
73 }
74
75 type CallJSON struct {
76         Cron           string
77         Nice           *string `json:"nice,omitempty"`
78         Xx             *string `json:"xx,omitempty"`
79         RxRate         *int    `json:"rxrate,omitempty"`
80         TxRate         *int    `json:"txrate,omitempty"`
81         Addr           *string `json:"addr,omitempty"`
82         OnlineDeadline *uint   `json:"onlinedeadline,omitempty"`
83         MaxOnlineTime  *uint   `json:"maxonlinetime,omitempty"`
84         WhenTxExists   *bool   `json:"when-tx-exists,omitempty"`
85         NoCK           *bool   `json:"nock"`
86
87         AutoToss       *bool `json:"autotoss,omitempty"`
88         AutoTossDoSeen *bool `json:"autotoss-doseen,omitempty"`
89         AutoTossNoFile *bool `json:"autotoss-nofile,omitempty"`
90         AutoTossNoFreq *bool `json:"autotoss-nofreq,omitempty"`
91         AutoTossNoExec *bool `json:"autotoss-noexec,omitempty"`
92         AutoTossNoTrns *bool `json:"autotoss-notrns,omitempty"`
93 }
94
95 type NodeOurJSON struct {
96         Id       string `json:"id"`
97         ExchPub  string `json:"exchpub"`
98         ExchPrv  string `json:"exchprv"`
99         SignPub  string `json:"signpub"`
100         SignPrv  string `json:"signprv"`
101         NoisePrv string `json:"noiseprv"`
102         NoisePub string `json:"noisepub"`
103 }
104
105 type FromToJSON struct {
106         From string
107         To   string
108 }
109
110 type NotifyJSON struct {
111         File *FromToJSON            `json:"file,omitempty"`
112         Freq *FromToJSON            `json:"freq,omitempty"`
113         Exec map[string]*FromToJSON `json:"exec,omitempty"`
114 }
115
116 type CfgJSON struct {
117         Spool string `json:"spool"`
118         Log   string `json:"log"`
119         Umask string `json:"umask,omitempty"`
120
121         OmitPrgrs bool `json:"noprogress,omitempty"`
122         NoHdr     bool `json:"nohdr,omitempty"`
123
124         Notify *NotifyJSON `json:"notify,omitempty"`
125
126         Self  *NodeOurJSON        `json:"self"`
127         Neigh map[string]NodeJSON `json:"neigh"`
128 }
129
130 func NewNode(name string, cfg NodeJSON) (*Node, error) {
131         nodeId, err := NodeIdFromString(cfg.Id)
132         if err != nil {
133                 return nil, err
134         }
135
136         exchPub, err := Base32Codec.DecodeString(cfg.ExchPub)
137         if err != nil {
138                 return nil, err
139         }
140         if len(exchPub) != 32 {
141                 return nil, errors.New("Invalid exchPub size")
142         }
143
144         signPub, err := Base32Codec.DecodeString(cfg.SignPub)
145         if err != nil {
146                 return nil, err
147         }
148         if len(signPub) != ed25519.PublicKeySize {
149                 return nil, errors.New("Invalid signPub size")
150         }
151
152         var noisePub []byte
153         if cfg.NoisePub != nil {
154                 noisePub, err = Base32Codec.DecodeString(*cfg.NoisePub)
155                 if err != nil {
156                         return nil, err
157                 }
158                 if len(noisePub) != 32 {
159                         return nil, errors.New("Invalid noisePub size")
160                 }
161         }
162
163         var incoming *string
164         if cfg.Incoming != nil {
165                 inc := path.Clean(*cfg.Incoming)
166                 if !path.IsAbs(inc) {
167                         return nil, errors.New("Incoming path must be absolute")
168                 }
169                 incoming = &inc
170         }
171
172         var freqPath *string
173         freqChunked := int64(MaxFileSize)
174         var freqMinSize int64
175         freqMaxSize := int64(MaxFileSize)
176         if cfg.Freq != nil {
177                 f := cfg.Freq
178                 if f.Path != nil {
179                         fPath := path.Clean(*f.Path)
180                         if !path.IsAbs(fPath) {
181                                 return nil, errors.New("freq.path path must be absolute")
182                         }
183                         freqPath = &fPath
184                 }
185                 if f.Chunked != nil {
186                         if *f.Chunked == 0 {
187                                 return nil, errors.New("freq.chunked value must be greater than zero")
188                         }
189                         freqChunked = int64(*f.Chunked) * 1024
190                 }
191                 if f.MinSize != nil {
192                         freqMinSize = int64(*f.MinSize) * 1024
193                 }
194                 if f.MaxSize != nil {
195                         freqMaxSize = int64(*f.MaxSize) * 1024
196                 }
197         }
198
199         defRxRate := 0
200         if cfg.RxRate != nil && *cfg.RxRate > 0 {
201                 defRxRate = *cfg.RxRate
202         }
203         defTxRate := 0
204         if cfg.TxRate != nil && *cfg.TxRate > 0 {
205                 defTxRate = *cfg.TxRate
206         }
207
208         defOnlineDeadline := DefaultDeadline
209         if cfg.OnlineDeadline != nil {
210                 if *cfg.OnlineDeadline <= 0 {
211                         return nil, errors.New("OnlineDeadline must be at least 1 second")
212                 }
213                 defOnlineDeadline = time.Duration(*cfg.OnlineDeadline) * time.Second
214         }
215         var defMaxOnlineTime time.Duration
216         if cfg.MaxOnlineTime != nil {
217                 defMaxOnlineTime = time.Duration(*cfg.MaxOnlineTime) * time.Second
218         }
219
220         var calls []*Call
221         for _, callCfg := range cfg.Calls {
222                 expr, err := cronexpr.Parse(callCfg.Cron)
223                 if err != nil {
224                         return nil, err
225                 }
226
227                 nice := uint8(255)
228                 if callCfg.Nice != nil {
229                         nice, err = NicenessParse(*callCfg.Nice)
230                         if err != nil {
231                                 return nil, err
232                         }
233                 }
234
235                 var xx TRxTx
236                 if callCfg.Xx != nil {
237                         switch *callCfg.Xx {
238                         case "rx":
239                                 xx = TRx
240                         case "tx":
241                                 xx = TTx
242                         default:
243                                 return nil, errors.New("xx field must be either \"rx\" or \"tx\"")
244                         }
245                 }
246
247                 rxRate := defRxRate
248                 if callCfg.RxRate != nil {
249                         rxRate = *callCfg.RxRate
250                 }
251                 txRate := defTxRate
252                 if callCfg.TxRate != nil {
253                         txRate = *callCfg.TxRate
254                 }
255
256                 var addr *string
257                 if callCfg.Addr != nil {
258                         if a, exists := cfg.Addrs[*callCfg.Addr]; exists {
259                                 addr = &a
260                         } else {
261                                 addr = callCfg.Addr
262                         }
263                 }
264
265                 onlineDeadline := defOnlineDeadline
266                 if callCfg.OnlineDeadline != nil {
267                         if *callCfg.OnlineDeadline == 0 {
268                                 return nil, errors.New("OnlineDeadline must be at least 1 second")
269                         }
270                         onlineDeadline = time.Duration(*callCfg.OnlineDeadline) * time.Second
271                 }
272
273                 call := Call{
274                         Cron:           expr,
275                         Nice:           nice,
276                         Xx:             xx,
277                         RxRate:         rxRate,
278                         TxRate:         txRate,
279                         Addr:           addr,
280                         OnlineDeadline: onlineDeadline,
281                 }
282
283                 if callCfg.MaxOnlineTime != nil {
284                         call.MaxOnlineTime = time.Duration(*callCfg.MaxOnlineTime) * time.Second
285                 }
286                 if callCfg.WhenTxExists != nil {
287                         call.WhenTxExists = *callCfg.WhenTxExists
288                 }
289                 if callCfg.NoCK != nil {
290                         call.NoCK = *callCfg.NoCK
291                 }
292                 if callCfg.AutoToss != nil {
293                         call.AutoToss = *callCfg.AutoToss
294                 }
295                 if callCfg.AutoTossDoSeen != nil {
296                         call.AutoTossDoSeen = *callCfg.AutoTossDoSeen
297                 }
298                 if callCfg.AutoTossNoFile != nil {
299                         call.AutoTossNoFile = *callCfg.AutoTossNoFile
300                 }
301                 if callCfg.AutoTossNoFreq != nil {
302                         call.AutoTossNoFreq = *callCfg.AutoTossNoFreq
303                 }
304                 if callCfg.AutoTossNoExec != nil {
305                         call.AutoTossNoExec = *callCfg.AutoTossNoExec
306                 }
307                 if callCfg.AutoTossNoTrns != nil {
308                         call.AutoTossNoTrns = *callCfg.AutoTossNoTrns
309                 }
310
311                 calls = append(calls, &call)
312         }
313
314         node := Node{
315                 Name:           name,
316                 Id:             nodeId,
317                 ExchPub:        new([32]byte),
318                 SignPub:        ed25519.PublicKey(signPub),
319                 Exec:           cfg.Exec,
320                 Incoming:       incoming,
321                 FreqPath:       freqPath,
322                 FreqChunked:    freqChunked,
323                 FreqMinSize:    freqMinSize,
324                 FreqMaxSize:    freqMaxSize,
325                 Calls:          calls,
326                 Addrs:          cfg.Addrs,
327                 RxRate:         defRxRate,
328                 TxRate:         defTxRate,
329                 OnlineDeadline: defOnlineDeadline,
330                 MaxOnlineTime:  defMaxOnlineTime,
331         }
332         copy(node.ExchPub[:], exchPub)
333         if len(noisePub) > 0 {
334                 node.NoisePub = new([32]byte)
335                 copy(node.NoisePub[:], noisePub)
336         }
337         return &node, nil
338 }
339
340 func NewNodeOur(cfg *NodeOurJSON) (*NodeOur, error) {
341         id, err := NodeIdFromString(cfg.Id)
342         if err != nil {
343                 return nil, err
344         }
345
346         exchPub, err := Base32Codec.DecodeString(cfg.ExchPub)
347         if err != nil {
348                 return nil, err
349         }
350         if len(exchPub) != 32 {
351                 return nil, errors.New("Invalid exchPub size")
352         }
353
354         exchPrv, err := Base32Codec.DecodeString(cfg.ExchPrv)
355         if err != nil {
356                 return nil, err
357         }
358         if len(exchPrv) != 32 {
359                 return nil, errors.New("Invalid exchPrv size")
360         }
361
362         signPub, err := Base32Codec.DecodeString(cfg.SignPub)
363         if err != nil {
364                 return nil, err
365         }
366         if len(signPub) != ed25519.PublicKeySize {
367                 return nil, errors.New("Invalid signPub size")
368         }
369
370         signPrv, err := Base32Codec.DecodeString(cfg.SignPrv)
371         if err != nil {
372                 return nil, err
373         }
374         if len(signPrv) != ed25519.PrivateKeySize {
375                 return nil, errors.New("Invalid signPrv size")
376         }
377
378         noisePub, err := Base32Codec.DecodeString(cfg.NoisePub)
379         if err != nil {
380                 return nil, err
381         }
382         if len(noisePub) != 32 {
383                 return nil, errors.New("Invalid noisePub size")
384         }
385
386         noisePrv, err := Base32Codec.DecodeString(cfg.NoisePrv)
387         if err != nil {
388                 return nil, err
389         }
390         if len(noisePrv) != 32 {
391                 return nil, errors.New("Invalid noisePrv size")
392         }
393
394         node := NodeOur{
395                 Id:       id,
396                 ExchPub:  new([32]byte),
397                 ExchPrv:  new([32]byte),
398                 SignPub:  ed25519.PublicKey(signPub),
399                 SignPrv:  ed25519.PrivateKey(signPrv),
400                 NoisePub: new([32]byte),
401                 NoisePrv: new([32]byte),
402         }
403         copy(node.ExchPub[:], exchPub)
404         copy(node.ExchPrv[:], exchPrv)
405         copy(node.NoisePub[:], noisePub)
406         copy(node.NoisePrv[:], noisePrv)
407         return &node, nil
408 }
409
410 func CfgParse(data []byte) (*Ctx, error) {
411         var err error
412         if bytes.Compare(data[:8], MagicNNCPBv3[:]) == 0 {
413                 os.Stderr.WriteString("Passphrase:") // #nosec G104
414                 password, err := term.ReadPassword(0)
415                 if err != nil {
416                         log.Fatalln(err)
417                 }
418                 os.Stderr.WriteString("\n") // #nosec G104
419                 data, err = DeEBlob(data, password)
420                 if err != nil {
421                         return nil, err
422                 }
423         }
424         var cfgGeneral map[string]interface{}
425         if err = hjson.Unmarshal(data, &cfgGeneral); err != nil {
426                 return nil, err
427         }
428         marshaled, err := json.Marshal(cfgGeneral)
429         if err != nil {
430                 return nil, err
431         }
432         var cfgJSON CfgJSON
433         if err = json.Unmarshal(marshaled, &cfgJSON); err != nil {
434                 return nil, err
435         }
436         if _, exists := cfgJSON.Neigh["self"]; !exists {
437                 return nil, errors.New("self neighbour missing")
438         }
439         var self *NodeOur
440         if cfgJSON.Self != nil {
441                 self, err = NewNodeOur(cfgJSON.Self)
442                 if err != nil {
443                         return nil, err
444                 }
445         }
446         spoolPath := path.Clean(cfgJSON.Spool)
447         if !path.IsAbs(spoolPath) {
448                 return nil, errors.New("Spool path must be absolute")
449         }
450         logPath := path.Clean(cfgJSON.Log)
451         if !path.IsAbs(logPath) {
452                 return nil, errors.New("Log path must be absolute")
453         }
454         var umaskForce *int
455         if cfgJSON.Umask != "" {
456                 r, err := strconv.ParseUint(cfgJSON.Umask, 8, 16)
457                 if err != nil {
458                         return nil, err
459                 }
460                 rInt := int(r)
461                 umaskForce = &rInt
462         }
463         showPrgrs := true
464         if cfgJSON.OmitPrgrs {
465                 showPrgrs = false
466         }
467         hdrUsage := true
468         if cfgJSON.NoHdr {
469                 hdrUsage = false
470         }
471         ctx := Ctx{
472                 Spool:      spoolPath,
473                 LogPath:    logPath,
474                 UmaskForce: umaskForce,
475                 ShowPrgrs:  showPrgrs,
476                 HdrUsage:   hdrUsage,
477                 Self:       self,
478                 Neigh:      make(map[NodeId]*Node, len(cfgJSON.Neigh)),
479                 Alias:      make(map[string]*NodeId),
480         }
481         if cfgJSON.Notify != nil {
482                 if cfgJSON.Notify.File != nil {
483                         ctx.NotifyFile = cfgJSON.Notify.File
484                 }
485                 if cfgJSON.Notify.Freq != nil {
486                         ctx.NotifyFreq = cfgJSON.Notify.Freq
487                 }
488                 if cfgJSON.Notify.Exec != nil {
489                         ctx.NotifyExec = cfgJSON.Notify.Exec
490                 }
491         }
492         vias := make(map[NodeId][]string)
493         for name, neighJSON := range cfgJSON.Neigh {
494                 neigh, err := NewNode(name, neighJSON)
495                 if err != nil {
496                         return nil, err
497                 }
498                 ctx.Neigh[*neigh.Id] = neigh
499                 if _, already := ctx.Alias[name]; already {
500                         return nil, errors.New("Node names conflict")
501                 }
502                 ctx.Alias[name] = neigh.Id
503                 vias[*neigh.Id] = neighJSON.Via
504         }
505         ctx.SelfId = ctx.Alias["self"]
506         for neighId, viasRaw := range vias {
507                 for _, viaRaw := range viasRaw {
508                         foundNodeId, err := ctx.FindNode(viaRaw)
509                         if err != nil {
510                                 return nil, err
511                         }
512                         ctx.Neigh[neighId].Via = append(
513                                 ctx.Neigh[neighId].Via,
514                                 foundNodeId.Id,
515                         )
516                 }
517         }
518         return &ctx, nil
519 }