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