]> Cypherpunks.ru repositories - nncp.git/blob - src/cypherpunks.ru/nncp/cfg.go
bcd547ec91c5e13cbc6052d69c6164e35e9c3f6f
[nncp.git] / src / cypherpunks.ru / nncp / 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, either version 3 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program.  If not, see <http://www.gnu.org/licenses/>.
17 */
18
19 package nncp
20
21 import (
22         "bytes"
23         "errors"
24         "log"
25         "os"
26         "path"
27
28         "github.com/gorhill/cronexpr"
29         "golang.org/x/crypto/ed25519"
30         "golang.org/x/crypto/ssh/terminal"
31         "gopkg.in/yaml.v2"
32 )
33
34 const (
35         CfgPathEnv  = "NNCPCFG"
36         CfgSpoolEnv = "NNCPSPOOL"
37         CfgLogEnv   = "NNCPLOG"
38 )
39
40 var (
41         DefaultCfgPath      string = "/usr/local/etc/nncp.yaml"
42         DefaultSendmailPath string = "/usr/sbin/sendmail"
43         DefaultSpoolPath    string = "/var/spool/nncp"
44         DefaultLogPath      string = "/var/spool/nncp/log"
45 )
46
47 type NodeYAML struct {
48         Id          string
49         ExchPub     string
50         SignPub     string
51         NoisePub    *string             `yaml:"noisepub,omitempty"`
52         Exec        map[string][]string `yaml:"exec,omitempty"`
53         Incoming    *string             `yaml:"incoming,omitempty"`
54         Freq        *string             `yaml:"freq,omitempty"`
55         FreqChunked *uint64             `yaml:"freqchunked,omitempty"`
56         FreqMinSize *uint64             `yaml:"freqminsize,omitempty"`
57         Via         []string            `yaml:"via,omitempty"`
58         Calls       []CallYAML          `yaml:"calls,omitempty"`
59
60         Addrs map[string]string `yaml:"addrs,omitempty"`
61
62         RxRate         *int  `yaml:"rxrate,omitempty"`
63         TxRate         *int  `yaml:"txrate,omitempty"`
64         OnlineDeadline *uint `yaml:"onlinedeadline,omitempty"`
65         MaxOnlineTime  *uint `yaml:"maxonlinetime,omitempty"`
66 }
67
68 type CallYAML struct {
69         Cron           string
70         Nice           *string `yaml:"nice,omitempty"`
71         Xx             string  `yaml:"xx,omitempty"`
72         RxRate         *int    `yaml:"rxrate,omitempty"`
73         TxRate         *int    `yaml:"txrate,omitempty"`
74         Addr           *string `yaml:"addr,omitempty"`
75         OnlineDeadline *uint   `yaml:"onlinedeadline,omitempty"`
76         MaxOnlineTime  *uint   `yaml:"maxonlinetime,omitempty"`
77 }
78
79 type NodeOurYAML struct {
80         Id       string
81         ExchPub  string
82         ExchPrv  string
83         SignPub  string
84         SignPrv  string
85         NoisePrv string
86         NoisePub string
87 }
88
89 type FromToYAML struct {
90         From string
91         To   string
92 }
93
94 type NotifyYAML struct {
95         File *FromToYAML `yaml:"file,omitempty"`
96         Freq *FromToYAML `yaml:"freq,omitempty"`
97 }
98
99 type CfgYAML struct {
100         Self  *NodeOurYAML `yaml:"self,omitempty"`
101         Neigh map[string]NodeYAML
102
103         Spool  string
104         Log    string
105         Notify *NotifyYAML `yaml:"notify,omitempty"`
106 }
107
108 func NewNode(name string, yml NodeYAML) (*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                 switch callYml.Xx {
208                 case "rx":
209                         xx = TRx
210                 case "tx":
211                         xx = TTx
212                 case "":
213                 default:
214                         return nil, errors.New("xx field must be either \"rx\" or \"tx\"")
215                 }
216
217                 rxRate := defRxRate
218                 if callYml.RxRate != nil {
219                         rxRate = *callYml.RxRate
220                 }
221                 txRate := defTxRate
222                 if callYml.TxRate != nil {
223                         txRate = *callYml.TxRate
224                 }
225
226                 var addr *string
227                 if callYml.Addr != nil {
228                         if a, exists := yml.Addrs[*callYml.Addr]; exists {
229                                 addr = &a
230                         } else {
231                                 addr = callYml.Addr
232                         }
233                 }
234
235                 onlineDeadline := defOnlineDeadline
236                 if callYml.OnlineDeadline != nil {
237                         if *callYml.OnlineDeadline == 0 {
238                                 return nil, errors.New("OnlineDeadline must be at least 1 second")
239                         }
240                         onlineDeadline = *callYml.OnlineDeadline
241                 }
242
243                 var maxOnlineTime uint
244                 if callYml.MaxOnlineTime != nil {
245                         maxOnlineTime = *callYml.MaxOnlineTime
246                 }
247
248                 calls = append(calls, &Call{
249                         Cron:           expr,
250                         Nice:           nice,
251                         Xx:             xx,
252                         RxRate:         rxRate,
253                         TxRate:         txRate,
254                         Addr:           addr,
255                         OnlineDeadline: onlineDeadline,
256                         MaxOnlineTime:  maxOnlineTime,
257                 })
258         }
259
260         node := Node{
261                 Name:           name,
262                 Id:             nodeId,
263                 ExchPub:        new([32]byte),
264                 SignPub:        ed25519.PublicKey(signPub),
265                 Exec:           yml.Exec,
266                 Incoming:       incoming,
267                 Freq:           freq,
268                 FreqChunked:    freqChunked,
269                 FreqMinSize:    freqMinSize,
270                 Calls:          calls,
271                 Addrs:          yml.Addrs,
272                 RxRate:         defRxRate,
273                 TxRate:         defTxRate,
274                 OnlineDeadline: defOnlineDeadline,
275                 MaxOnlineTime:  defMaxOnlineTime,
276         }
277         copy(node.ExchPub[:], exchPub)
278         if len(noisePub) > 0 {
279                 node.NoisePub = new([32]byte)
280                 copy(node.NoisePub[:], noisePub)
281         }
282         return &node, nil
283 }
284
285 func NewNodeOur(yml *NodeOurYAML) (*NodeOur, error) {
286         id, err := NodeIdFromString(yml.Id)
287         if err != nil {
288                 return nil, err
289         }
290
291         exchPub, err := FromBase32(yml.ExchPub)
292         if err != nil {
293                 return nil, err
294         }
295         if len(exchPub) != 32 {
296                 return nil, errors.New("Invalid exchPub size")
297         }
298
299         exchPrv, err := FromBase32(yml.ExchPrv)
300         if err != nil {
301                 return nil, err
302         }
303         if len(exchPrv) != 32 {
304                 return nil, errors.New("Invalid exchPrv size")
305         }
306
307         signPub, err := FromBase32(yml.SignPub)
308         if err != nil {
309                 return nil, err
310         }
311         if len(signPub) != ed25519.PublicKeySize {
312                 return nil, errors.New("Invalid signPub size")
313         }
314
315         signPrv, err := FromBase32(yml.SignPrv)
316         if err != nil {
317                 return nil, err
318         }
319         if len(signPrv) != ed25519.PrivateKeySize {
320                 return nil, errors.New("Invalid signPrv size")
321         }
322
323         noisePub, err := FromBase32(yml.NoisePub)
324         if err != nil {
325                 return nil, err
326         }
327         if len(noisePub) != 32 {
328                 return nil, errors.New("Invalid noisePub size")
329         }
330
331         noisePrv, err := FromBase32(yml.NoisePrv)
332         if err != nil {
333                 return nil, err
334         }
335         if len(noisePrv) != 32 {
336                 return nil, errors.New("Invalid noisePrv size")
337         }
338
339         node := NodeOur{
340                 Id:       id,
341                 ExchPub:  new([32]byte),
342                 ExchPrv:  new([32]byte),
343                 SignPub:  ed25519.PublicKey(signPub),
344                 SignPrv:  ed25519.PrivateKey(signPrv),
345                 NoisePub: new([32]byte),
346                 NoisePrv: new([32]byte),
347         }
348         copy(node.ExchPub[:], exchPub)
349         copy(node.ExchPrv[:], exchPrv)
350         copy(node.NoisePub[:], noisePub)
351         copy(node.NoisePrv[:], noisePrv)
352         return &node, nil
353 }
354
355 func (nodeOur *NodeOur) ToYAML() string {
356         yml := NodeOurYAML{
357                 Id:       nodeOur.Id.String(),
358                 ExchPub:  ToBase32(nodeOur.ExchPub[:]),
359                 ExchPrv:  ToBase32(nodeOur.ExchPrv[:]),
360                 SignPub:  ToBase32(nodeOur.SignPub[:]),
361                 SignPrv:  ToBase32(nodeOur.SignPrv[:]),
362                 NoisePub: ToBase32(nodeOur.NoisePub[:]),
363                 NoisePrv: ToBase32(nodeOur.NoisePrv[:]),
364         }
365         raw, err := yaml.Marshal(&yml)
366         if err != nil {
367                 panic(err)
368         }
369         return string(raw)
370 }
371
372 func CfgParse(data []byte) (*Ctx, error) {
373         var err error
374         if bytes.Compare(data[:8], MagicNNCPBv3[:]) == 0 {
375                 os.Stderr.WriteString("Passphrase:")
376                 password, err := terminal.ReadPassword(0)
377                 if err != nil {
378                         log.Fatalln(err)
379                 }
380                 os.Stderr.WriteString("\n")
381                 data, err = DeEBlob(data, password)
382                 if err != nil {
383                         return nil, err
384                 }
385         }
386         var cfgYAML CfgYAML
387         if err = yaml.Unmarshal(data, &cfgYAML); err != nil {
388                 return nil, err
389         }
390         if _, exists := cfgYAML.Neigh["self"]; !exists {
391                 return nil, errors.New("self neighbour missing")
392         }
393         var self *NodeOur
394         if cfgYAML.Self != nil {
395                 self, err = NewNodeOur(cfgYAML.Self)
396                 if err != nil {
397                         return nil, err
398                 }
399         }
400         spoolPath := path.Clean(cfgYAML.Spool)
401         if !path.IsAbs(spoolPath) {
402                 return nil, errors.New("Spool path must be absolute")
403         }
404         logPath := path.Clean(cfgYAML.Log)
405         if !path.IsAbs(logPath) {
406                 return nil, errors.New("Log path must be absolute")
407         }
408         ctx := Ctx{
409                 Spool:   spoolPath,
410                 LogPath: logPath,
411                 Self:    self,
412                 Neigh:   make(map[NodeId]*Node, len(cfgYAML.Neigh)),
413                 Alias:   make(map[string]*NodeId),
414         }
415         if cfgYAML.Notify != nil {
416                 if cfgYAML.Notify.File != nil {
417                         ctx.NotifyFile = cfgYAML.Notify.File
418                 }
419                 if cfgYAML.Notify.Freq != nil {
420                         ctx.NotifyFreq = cfgYAML.Notify.Freq
421                 }
422         }
423         vias := make(map[NodeId][]string)
424         for name, neighYAML := range cfgYAML.Neigh {
425                 neigh, err := NewNode(name, neighYAML)
426                 if err != nil {
427                         return nil, err
428                 }
429                 ctx.Neigh[*neigh.Id] = neigh
430                 if _, already := ctx.Alias[name]; already {
431                         return nil, errors.New("Node names conflict")
432                 }
433                 ctx.Alias[name] = neigh.Id
434                 vias[*neigh.Id] = neighYAML.Via
435         }
436         ctx.SelfId = ctx.Alias["self"]
437         for neighId, viasRaw := range vias {
438                 for _, viaRaw := range viasRaw {
439                         foundNodeId, err := ctx.FindNode(viaRaw)
440                         if err != nil {
441                                 return nil, err
442                         }
443                         ctx.Neigh[neighId].Via = append(
444                                 ctx.Neigh[neighId].Via,
445                                 foundNodeId.Id,
446                         )
447                 }
448         }
449         return &ctx, nil
450 }