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