]> Cypherpunks.ru repositories - nncp.git/blob - src/cfg.go
edc132a37ffc403a09dd55221871ceb07fb15a27
[nncp.git] / src / cfg.go
1 /*
2 NNCP -- Node to Node copy, utilities for store-and-forward data exchange
3 Copyright (C) 2016-2019 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
29         "github.com/gorhill/cronexpr"
30         "github.com/hjson/hjson-go"
31         "golang.org/x/crypto/ed25519"
32         "golang.org/x/crypto/ssh/terminal"
33 )
34
35 const (
36         CfgPathEnv  = "NNCPCFG"
37         CfgSpoolEnv = "NNCPSPOOL"
38         CfgLogEnv   = "NNCPLOG"
39 )
40
41 var (
42         DefaultCfgPath      string = "/usr/local/etc/nncp.hjson"
43         DefaultSendmailPath string = "/usr/sbin/sendmail"
44         DefaultSpoolPath    string = "/var/spool/nncp"
45         DefaultLogPath      string = "/var/spool/nncp/log"
46 )
47
48 type NodeJSON struct {
49         Id       string              `json:"id"`
50         ExchPub  string              `json:"exchpub"`
51         SignPub  string              `json:"signpub"`
52         NoisePub *string             `json:"noisepub,omitempty"`
53         Exec     map[string][]string `json:"exec,omitempty"`
54         Incoming *string             `json:"incoming,omitempty"`
55         Freq     *NodeFreqJSON       `json:"freq,omitempty"`
56         Via      []string            `json:"via,omitempty"`
57         Calls    []CallJSON          `json:"calls,omitempty"`
58
59         Addrs map[string]string `json:"addrs,omitempty"`
60
61         RxRate         *int  `json:"rxrate,omitempty"`
62         TxRate         *int  `json:"txrate,omitempty"`
63         OnlineDeadline *uint `json:"onlinedeadline,omitempty"`
64         MaxOnlineTime  *uint `json:"maxonlinetime,omitempty"`
65 }
66
67 type NodeFreqJSON struct {
68         Path    *string `json:"path,omitempty"`
69         Chunked *uint64 `json:"chunked,omitempty"`
70         MinSize *uint64 `json:"minsize,omitempty"`
71         MaxSize *uint64 `json:"maxsize,omitempty"`
72 }
73
74 type CallJSON struct {
75         Cron           string
76         Nice           *string `json:"nice,omitempty"`
77         Xx             *string `json:"xx,omitempty"`
78         RxRate         *int    `json:"rxrate,omitempty"`
79         TxRate         *int    `json:"txrate,omitempty"`
80         Addr           *string `json:"addr,omitempty"`
81         OnlineDeadline *uint   `json:"onlinedeadline,omitempty"`
82         MaxOnlineTime  *uint   `json:"maxonlinetime,omitempty"`
83 }
84
85 type NodeOurJSON struct {
86         Id       string `json:"id"`
87         ExchPub  string `json:"exchpub"`
88         ExchPrv  string `json:"exchprv"`
89         SignPub  string `json:"signpub"`
90         SignPrv  string `json:"signprv"`
91         NoisePrv string `json:"noiseprv"`
92         NoisePub string `json:"noisepub"`
93 }
94
95 type FromToJSON struct {
96         From string
97         To   string
98 }
99
100 type NotifyJSON struct {
101         File *FromToJSON            `json:"file,omitempty"`
102         Freq *FromToJSON            `json:"freq,omitempty"`
103         Exec map[string]*FromToJSON `json:"exec,omitempty"`
104 }
105
106 type CfgJSON struct {
107         Spool string `json:"spool"`
108         Log   string `json:"log"`
109         Umask string `json:"umask",omitempty`
110
111         Notify *NotifyJSON `json:"notify,omitempty"`
112
113         Self  *NodeOurJSON        `json:"self"`
114         Neigh map[string]NodeJSON `json:"neigh"`
115 }
116
117 func NewNode(name string, yml NodeJSON) (*Node, error) {
118         nodeId, err := NodeIdFromString(yml.Id)
119         if err != nil {
120                 return nil, err
121         }
122
123         exchPub, err := FromBase32(yml.ExchPub)
124         if err != nil {
125                 return nil, err
126         }
127         if len(exchPub) != 32 {
128                 return nil, errors.New("Invalid exchPub size")
129         }
130
131         signPub, err := FromBase32(yml.SignPub)
132         if err != nil {
133                 return nil, err
134         }
135         if len(signPub) != ed25519.PublicKeySize {
136                 return nil, errors.New("Invalid signPub size")
137         }
138
139         var noisePub []byte
140         if yml.NoisePub != nil {
141                 noisePub, err = FromBase32(*yml.NoisePub)
142                 if err != nil {
143                         return nil, err
144                 }
145                 if len(noisePub) != 32 {
146                         return nil, errors.New("Invalid noisePub size")
147                 }
148         }
149
150         var incoming *string
151         if yml.Incoming != nil {
152                 inc := path.Clean(*yml.Incoming)
153                 if !path.IsAbs(inc) {
154                         return nil, errors.New("Incoming path must be absolute")
155                 }
156                 incoming = &inc
157         }
158
159         var freqPath *string
160         freqChunked := int64(MaxFileSize)
161         var freqMinSize int64
162         freqMaxSize := int64(MaxFileSize)
163         if yml.Freq != nil {
164                 f := yml.Freq
165                 if f.Path != nil {
166                         fPath := path.Clean(*f.Path)
167                         if !path.IsAbs(fPath) {
168                                 return nil, errors.New("freq.path path must be absolute")
169                         }
170                         freqPath = &fPath
171                 }
172                 if f.Chunked != nil {
173                         if *f.Chunked == 0 {
174                                 return nil, errors.New("freq.chunked value must be greater than zero")
175                         }
176                         freqChunked = int64(*f.Chunked) * 1024
177                 }
178                 if f.MinSize != nil {
179                         freqMinSize = int64(*f.MinSize) * 1024
180                 }
181                 if f.MaxSize != nil {
182                         freqMaxSize = int64(*f.MaxSize) * 1024
183                 }
184         }
185
186         defRxRate := 0
187         if yml.RxRate != nil && *yml.RxRate > 0 {
188                 defRxRate = *yml.RxRate
189         }
190         defTxRate := 0
191         if yml.TxRate != nil && *yml.TxRate > 0 {
192                 defTxRate = *yml.TxRate
193         }
194
195         defOnlineDeadline := uint(DefaultDeadline)
196         if yml.OnlineDeadline != nil {
197                 if *yml.OnlineDeadline <= 0 {
198                         return nil, errors.New("OnlineDeadline must be at least 1 second")
199                 }
200                 defOnlineDeadline = *yml.OnlineDeadline
201         }
202         var defMaxOnlineTime uint
203         if yml.MaxOnlineTime != nil {
204                 defMaxOnlineTime = *yml.MaxOnlineTime
205         }
206
207         var calls []*Call
208         for _, callYml := range yml.Calls {
209                 expr, err := cronexpr.Parse(callYml.Cron)
210                 if err != nil {
211                         return nil, err
212                 }
213
214                 nice := uint8(255)
215                 if callYml.Nice != nil {
216                         nice, err = NicenessParse(*callYml.Nice)
217                         if err != nil {
218                                 return nil, err
219                         }
220                 }
221
222                 var xx TRxTx
223                 if callYml.Xx != nil {
224                         switch *callYml.Xx {
225                         case "rx":
226                                 xx = TRx
227                         case "tx":
228                                 xx = TTx
229                         default:
230                                 return nil, errors.New("xx field must be either \"rx\" or \"tx\"")
231                         }
232                 }
233
234                 rxRate := defRxRate
235                 if callYml.RxRate != nil {
236                         rxRate = *callYml.RxRate
237                 }
238                 txRate := defTxRate
239                 if callYml.TxRate != nil {
240                         txRate = *callYml.TxRate
241                 }
242
243                 var addr *string
244                 if callYml.Addr != nil {
245                         if a, exists := yml.Addrs[*callYml.Addr]; exists {
246                                 addr = &a
247                         } else {
248                                 addr = callYml.Addr
249                         }
250                 }
251
252                 onlineDeadline := defOnlineDeadline
253                 if callYml.OnlineDeadline != nil {
254                         if *callYml.OnlineDeadline == 0 {
255                                 return nil, errors.New("OnlineDeadline must be at least 1 second")
256                         }
257                         onlineDeadline = *callYml.OnlineDeadline
258                 }
259
260                 var maxOnlineTime uint
261                 if callYml.MaxOnlineTime != nil {
262                         maxOnlineTime = *callYml.MaxOnlineTime
263                 }
264
265                 calls = append(calls, &Call{
266                         Cron:           expr,
267                         Nice:           nice,
268                         Xx:             xx,
269                         RxRate:         rxRate,
270                         TxRate:         txRate,
271                         Addr:           addr,
272                         OnlineDeadline: onlineDeadline,
273                         MaxOnlineTime:  maxOnlineTime,
274                 })
275         }
276
277         node := Node{
278                 Name:           name,
279                 Id:             nodeId,
280                 ExchPub:        new([32]byte),
281                 SignPub:        ed25519.PublicKey(signPub),
282                 Exec:           yml.Exec,
283                 Incoming:       incoming,
284                 FreqPath:       freqPath,
285                 FreqChunked:    freqChunked,
286                 FreqMinSize:    freqMinSize,
287                 FreqMaxSize:    freqMaxSize,
288                 Calls:          calls,
289                 Addrs:          yml.Addrs,
290                 RxRate:         defRxRate,
291                 TxRate:         defTxRate,
292                 OnlineDeadline: defOnlineDeadline,
293                 MaxOnlineTime:  defMaxOnlineTime,
294         }
295         copy(node.ExchPub[:], exchPub)
296         if len(noisePub) > 0 {
297                 node.NoisePub = new([32]byte)
298                 copy(node.NoisePub[:], noisePub)
299         }
300         return &node, nil
301 }
302
303 func NewNodeOur(yml *NodeOurJSON) (*NodeOur, error) {
304         id, err := NodeIdFromString(yml.Id)
305         if err != nil {
306                 return nil, err
307         }
308
309         exchPub, err := FromBase32(yml.ExchPub)
310         if err != nil {
311                 return nil, err
312         }
313         if len(exchPub) != 32 {
314                 return nil, errors.New("Invalid exchPub size")
315         }
316
317         exchPrv, err := FromBase32(yml.ExchPrv)
318         if err != nil {
319                 return nil, err
320         }
321         if len(exchPrv) != 32 {
322                 return nil, errors.New("Invalid exchPrv size")
323         }
324
325         signPub, err := FromBase32(yml.SignPub)
326         if err != nil {
327                 return nil, err
328         }
329         if len(signPub) != ed25519.PublicKeySize {
330                 return nil, errors.New("Invalid signPub size")
331         }
332
333         signPrv, err := FromBase32(yml.SignPrv)
334         if err != nil {
335                 return nil, err
336         }
337         if len(signPrv) != ed25519.PrivateKeySize {
338                 return nil, errors.New("Invalid signPrv size")
339         }
340
341         noisePub, err := FromBase32(yml.NoisePub)
342         if err != nil {
343                 return nil, err
344         }
345         if len(noisePub) != 32 {
346                 return nil, errors.New("Invalid noisePub size")
347         }
348
349         noisePrv, err := FromBase32(yml.NoisePrv)
350         if err != nil {
351                 return nil, err
352         }
353         if len(noisePrv) != 32 {
354                 return nil, errors.New("Invalid noisePrv size")
355         }
356
357         node := NodeOur{
358                 Id:       id,
359                 ExchPub:  new([32]byte),
360                 ExchPrv:  new([32]byte),
361                 SignPub:  ed25519.PublicKey(signPub),
362                 SignPrv:  ed25519.PrivateKey(signPrv),
363                 NoisePub: new([32]byte),
364                 NoisePrv: new([32]byte),
365         }
366         copy(node.ExchPub[:], exchPub)
367         copy(node.ExchPrv[:], exchPrv)
368         copy(node.NoisePub[:], noisePub)
369         copy(node.NoisePrv[:], noisePrv)
370         return &node, nil
371 }
372
373 func CfgParse(data []byte) (*Ctx, error) {
374         var err error
375         if bytes.Compare(data[:8], MagicNNCPBv3[:]) == 0 {
376                 os.Stderr.WriteString("Passphrase:")
377                 password, err := terminal.ReadPassword(0)
378                 if err != nil {
379                         log.Fatalln(err)
380                 }
381                 os.Stderr.WriteString("\n")
382                 data, err = DeEBlob(data, password)
383                 if err != nil {
384                         return nil, err
385                 }
386         }
387         var cfgGeneral map[string]interface{}
388         if err = hjson.Unmarshal(data, &cfgGeneral); err != nil {
389                 return nil, err
390         }
391         marshaled, err := json.Marshal(cfgGeneral)
392         if err != nil {
393                 return nil, err
394         }
395         var cfgJSON CfgJSON
396         if err = json.Unmarshal(marshaled, &cfgJSON); err != nil {
397                 return nil, err
398         }
399         if _, exists := cfgJSON.Neigh["self"]; !exists {
400                 return nil, errors.New("self neighbour missing")
401         }
402         var self *NodeOur
403         if cfgJSON.Self != nil {
404                 self, err = NewNodeOur(cfgJSON.Self)
405                 if err != nil {
406                         return nil, err
407                 }
408         }
409         spoolPath := path.Clean(cfgJSON.Spool)
410         if !path.IsAbs(spoolPath) {
411                 return nil, errors.New("Spool path must be absolute")
412         }
413         logPath := path.Clean(cfgJSON.Log)
414         if !path.IsAbs(logPath) {
415                 return nil, errors.New("Log path must be absolute")
416         }
417         var umaskForce *int
418         if cfgJSON.Umask != "" {
419                 r, err := strconv.ParseUint(cfgJSON.Umask, 8, 16)
420                 if err != nil {
421                         return nil, err
422                 }
423                 rInt := int(r)
424                 umaskForce = &rInt
425         }
426         ctx := Ctx{
427                 Spool:      spoolPath,
428                 LogPath:    logPath,
429                 UmaskForce: umaskForce,
430                 Self:       self,
431                 Neigh:      make(map[NodeId]*Node, len(cfgJSON.Neigh)),
432                 Alias:      make(map[string]*NodeId),
433         }
434         if cfgJSON.Notify != nil {
435                 if cfgJSON.Notify.File != nil {
436                         ctx.NotifyFile = cfgJSON.Notify.File
437                 }
438                 if cfgJSON.Notify.Freq != nil {
439                         ctx.NotifyFreq = cfgJSON.Notify.Freq
440                 }
441                 if cfgJSON.Notify.Exec != nil {
442                         ctx.NotifyExec = cfgJSON.Notify.Exec
443                 }
444         }
445         vias := make(map[NodeId][]string)
446         for name, neighJSON := range cfgJSON.Neigh {
447                 neigh, err := NewNode(name, neighJSON)
448                 if err != nil {
449                         return nil, err
450                 }
451                 ctx.Neigh[*neigh.Id] = neigh
452                 if _, already := ctx.Alias[name]; already {
453                         return nil, errors.New("Node names conflict")
454                 }
455                 ctx.Alias[name] = neigh.Id
456                 vias[*neigh.Id] = neighJSON.Via
457         }
458         ctx.SelfId = ctx.Alias["self"]
459         for neighId, viasRaw := range vias {
460                 for _, viaRaw := range viasRaw {
461                         foundNodeId, err := ctx.FindNode(viaRaw)
462                         if err != nil {
463                                 return nil, err
464                         }
465                         ctx.Neigh[neighId].Via = append(
466                                 ctx.Neigh[neighId].Via,
467                                 foundNodeId.Id,
468                         )
469                 }
470         }
471         return &ctx, nil
472 }