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