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