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