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