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