]> Cypherpunks.ru repositories - nncp.git/blob - src/cypherpunks.ru/nncp/cfg.go
Encrypted configuration file
[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                 if callYml.Xx != nil {
191                         switch *callYml.Xx {
192                         case "rx":
193                                 xx = TRx
194                         case "tx":
195                                 xx = TTx
196                         default:
197                                 return nil, errors.New("xx field must be either \"rx\" or \"tx\"")
198                         }
199                 }
200                 var addr *string
201                 if callYml.Addr != nil {
202                         if a, exists := yml.Addrs[*callYml.Addr]; exists {
203                                 addr = &a
204                         } else {
205                                 addr = callYml.Addr
206                         }
207                 }
208                 onlineDeadline := defOnlineDeadline
209                 if callYml.OnlineDeadline != nil {
210                         if *callYml.OnlineDeadline == 0 {
211                                 return nil, errors.New("OnlineDeadline must be at least 1 second")
212                         }
213                         onlineDeadline = *callYml.OnlineDeadline
214                 }
215                 var maxOnlineTime uint
216                 if callYml.MaxOnlineTime != nil {
217                         maxOnlineTime = *callYml.MaxOnlineTime
218                 }
219                 calls = append(calls, &Call{
220                         Cron:           expr,
221                         Nice:           nice,
222                         Xx:             &xx,
223                         Addr:           addr,
224                         OnlineDeadline: onlineDeadline,
225                         MaxOnlineTime:  maxOnlineTime,
226                 })
227         }
228
229         node := Node{
230                 Name:           name,
231                 Id:             nodeId,
232                 ExchPub:        new([32]byte),
233                 SignPub:        ed25519.PublicKey(signPub),
234                 Sendmail:       yml.Sendmail,
235                 Incoming:       incoming,
236                 Freq:           freq,
237                 FreqChunked:    freqChunked,
238                 FreqMinSize:    freqMinSize,
239                 Calls:          calls,
240                 Addrs:          yml.Addrs,
241                 OnlineDeadline: defOnlineDeadline,
242                 MaxOnlineTime:  defMaxOnlineTime,
243         }
244         copy(node.ExchPub[:], exchPub)
245         if len(noisePub) > 0 {
246                 node.NoisePub = new([32]byte)
247                 copy(node.NoisePub[:], noisePub)
248         }
249         return &node, nil
250 }
251
252 func NewNodeOur(yml *NodeOurYAML) (*NodeOur, error) {
253         id, err := NodeIdFromString(yml.Id)
254         if err != nil {
255                 return nil, err
256         }
257
258         exchPub, err := FromBase32(yml.ExchPub)
259         if err != nil {
260                 return nil, err
261         }
262         if len(exchPub) != 32 {
263                 return nil, errors.New("Invalid exchPub size")
264         }
265
266         exchPrv, err := FromBase32(yml.ExchPrv)
267         if err != nil {
268                 return nil, err
269         }
270         if len(exchPrv) != 32 {
271                 return nil, errors.New("Invalid exchPrv size")
272         }
273
274         signPub, err := FromBase32(yml.SignPub)
275         if err != nil {
276                 return nil, err
277         }
278         if len(signPub) != ed25519.PublicKeySize {
279                 return nil, errors.New("Invalid signPub size")
280         }
281
282         signPrv, err := FromBase32(yml.SignPrv)
283         if err != nil {
284                 return nil, err
285         }
286         if len(signPrv) != ed25519.PrivateKeySize {
287                 return nil, errors.New("Invalid signPrv size")
288         }
289
290         noisePub, err := FromBase32(yml.NoisePub)
291         if err != nil {
292                 return nil, err
293         }
294         if len(noisePub) != 32 {
295                 return nil, errors.New("Invalid noisePub size")
296         }
297
298         noisePrv, err := FromBase32(yml.NoisePrv)
299         if err != nil {
300                 return nil, err
301         }
302         if len(noisePrv) != 32 {
303                 return nil, errors.New("Invalid noisePrv size")
304         }
305
306         node := NodeOur{
307                 Id:       id,
308                 ExchPub:  new([32]byte),
309                 ExchPrv:  new([32]byte),
310                 SignPub:  ed25519.PublicKey(signPub),
311                 SignPrv:  ed25519.PrivateKey(signPrv),
312                 NoisePub: new([32]byte),
313                 NoisePrv: new([32]byte),
314         }
315         copy(node.ExchPub[:], exchPub)
316         copy(node.ExchPrv[:], exchPrv)
317         copy(node.NoisePub[:], noisePub)
318         copy(node.NoisePrv[:], noisePrv)
319         return &node, nil
320 }
321
322 func (nodeOur *NodeOur) ToYAML() string {
323         yml := NodeOurYAML{
324                 Id:       nodeOur.Id.String(),
325                 ExchPub:  ToBase32(nodeOur.ExchPub[:]),
326                 ExchPrv:  ToBase32(nodeOur.ExchPrv[:]),
327                 SignPub:  ToBase32(nodeOur.SignPub[:]),
328                 SignPrv:  ToBase32(nodeOur.SignPrv[:]),
329                 NoisePub: ToBase32(nodeOur.NoisePub[:]),
330                 NoisePrv: ToBase32(nodeOur.NoisePrv[:]),
331         }
332         raw, err := yaml.Marshal(&yml)
333         if err != nil {
334                 panic(err)
335         }
336         return string(raw)
337 }
338
339 func CfgParse(data []byte) (*Ctx, error) {
340         var err error
341         if bytes.Compare(data[:8], MagicNNCPBv1[:]) == 0 {
342                 os.Stderr.WriteString("Passphrase:")
343                 password, err := terminal.ReadPassword(0)
344                 if err != nil {
345                         log.Fatalln(err)
346                 }
347                 os.Stderr.WriteString("\n")
348                 data, err = DeEBlob(data, password)
349                 if err != nil {
350                         return nil, err
351                 }
352         }
353         var cfgYAML CfgYAML
354         if err = yaml.Unmarshal(data, &cfgYAML); err != nil {
355                 return nil, err
356         }
357         if _, exists := cfgYAML.Neigh["self"]; !exists {
358                 return nil, errors.New("self neighbour missing")
359         }
360         var self *NodeOur
361         if cfgYAML.Self != nil {
362                 self, err = NewNodeOur(cfgYAML.Self)
363                 if err != nil {
364                         return nil, err
365                 }
366         }
367         spoolPath := path.Clean(cfgYAML.Spool)
368         if !path.IsAbs(spoolPath) {
369                 return nil, errors.New("Spool path must be absolute")
370         }
371         logPath := path.Clean(cfgYAML.Log)
372         if !path.IsAbs(logPath) {
373                 return nil, errors.New("Log path must be absolute")
374         }
375         ctx := Ctx{
376                 Spool:   spoolPath,
377                 LogPath: logPath,
378                 Self:    self,
379                 Neigh:   make(map[NodeId]*Node, len(cfgYAML.Neigh)),
380                 Alias:   make(map[string]*NodeId),
381         }
382         if cfgYAML.Notify != nil {
383                 if cfgYAML.Notify.File != nil {
384                         ctx.NotifyFile = cfgYAML.Notify.File
385                 }
386                 if cfgYAML.Notify.Freq != nil {
387                         ctx.NotifyFreq = cfgYAML.Notify.Freq
388                 }
389         }
390         vias := make(map[NodeId][]string)
391         for name, neighYAML := range cfgYAML.Neigh {
392                 neigh, err := NewNode(name, neighYAML)
393                 if err != nil {
394                         return nil, err
395                 }
396                 ctx.Neigh[*neigh.Id] = neigh
397                 if _, already := ctx.Alias[name]; already {
398                         return nil, errors.New("Node names conflict")
399                 }
400                 ctx.Alias[name] = neigh.Id
401                 vias[*neigh.Id] = neighYAML.Via
402         }
403         ctx.SelfId = ctx.Alias["self"]
404         for neighId, viasRaw := range vias {
405                 for _, viaRaw := range viasRaw {
406                         foundNodeId, err := ctx.FindNode(viaRaw)
407                         if err != nil {
408                                 return nil, err
409                         }
410                         ctx.Neigh[neighId].Via = append(
411                                 ctx.Neigh[neighId].Via,
412                                 foundNodeId.Id,
413                         )
414                 }
415         }
416         return &ctx, nil
417 }
418
419 func CfgPathFromEnv(cmdlineFlag *string) (p string) {
420         p = os.Getenv(CfgPathEnv)
421         if p == "" {
422                 p = *cmdlineFlag
423         }
424         return
425 }