2 NNCP -- Node to Node copy, utilities for store-and-forward data exchange
3 Copyright (C) 2016-2021 Sergey Matveev <stargrave@stargrave.org>
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.
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.
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/>.
30 "github.com/gorhill/cronexpr"
31 "github.com/hjson/hjson-go"
32 "golang.org/x/crypto/ed25519"
37 CfgPathEnv = "NNCPCFG"
38 CfgSpoolEnv = "NNCPSPOOL"
43 DefaultCfgPath string = "/usr/local/etc/nncp.hjson"
44 DefaultSendmailPath string = "/usr/sbin/sendmail"
45 DefaultSpoolPath string = "/var/spool/nncp"
46 DefaultLogPath string = "/var/spool/nncp/log"
49 type NodeJSON struct {
51 ExchPub string `json:"exchpub"`
52 SignPub string `json:"signpub"`
53 NoisePub *string `json:"noisepub,omitempty"`
54 Incoming *string `json:"incoming,omitempty"`
55 Exec map[string][]string `json:"exec,omitempty"`
56 Freq *NodeFreqJSON `json:"freq,omitempty"`
57 Via []string `json:"via,omitempty"`
58 Calls []CallJSON `json:"calls,omitempty"`
60 Addrs map[string]string `json:"addrs,omitempty"`
62 RxRate *int `json:"rxrate,omitempty"`
63 TxRate *int `json:"txrate,omitempty"`
64 OnlineDeadline *uint `json:"onlinedeadline,omitempty"`
65 MaxOnlineTime *uint `json:"maxonlinetime,omitempty"`
68 type NodeFreqJSON struct {
69 Path *string `json:"path,omitempty"`
70 Chunked *uint64 `json:"chunked,omitempty"`
71 MinSize *uint64 `json:"minsize,omitempty"`
72 MaxSize *uint64 `json:"maxsize,omitempty"`
75 type CallJSON struct {
76 Cron string `json:"cron"`
77 Nice *string `json:"nice,omitempty"`
78 Xx *string `json:"xx,omitempty"`
79 RxRate *int `json:"rxrate,omitempty"`
80 TxRate *int `json:"txrate,omitempty"`
81 Addr *string `json:"addr,omitempty"`
82 OnlineDeadline *uint `json:"onlinedeadline,omitempty"`
83 MaxOnlineTime *uint `json:"maxonlinetime,omitempty"`
84 WhenTxExists bool `json:"when-tx-exists,omitempty"`
85 NoCK bool `json:"nock,omitempty"`
86 MCDIgnore bool `json:"mcd-ignore,omitempty"`
88 AutoToss bool `json:"autotoss,omitempty"`
89 AutoTossDoSeen bool `json:"autotoss-doseen,omitempty"`
90 AutoTossNoFile bool `json:"autotoss-nofile,omitempty"`
91 AutoTossNoFreq bool `json:"autotoss-nofreq,omitempty"`
92 AutoTossNoExec bool `json:"autotoss-noexec,omitempty"`
93 AutoTossNoTrns bool `json:"autotoss-notrns,omitempty"`
94 AutoTossNoArea bool `json:"autotoss-noarea,omitempty"`
97 type NodeOurJSON struct {
99 ExchPub string `json:"exchpub"`
100 ExchPrv string `json:"exchprv"`
101 SignPub string `json:"signpub"`
102 SignPrv string `json:"signprv"`
103 NoisePub string `json:"noisepub"`
104 NoisePrv string `json:"noiseprv"`
107 type FromToJSON struct {
108 From string `json:"from"`
109 To string `json:"to"`
112 type NotifyJSON struct {
113 File *FromToJSON `json:"file,omitempty"`
114 Freq *FromToJSON `json:"freq,omitempty"`
115 Exec map[string]*FromToJSON `json:"exec,omitempty"`
118 type AreaJSON struct {
119 Id string `json:"id"`
120 Pub *string `json:"pub,omitempty"`
121 Prv *string `json:"prv,omitempty"`
123 Subs []string `json:"subs"`
125 Incoming *string `json:"incoming,omitempty"`
126 Exec map[string][]string `json:"exec,omitempty"`
128 AllowUnknown bool `json:"allow-unknown,omitempty"`
131 type CfgJSON struct {
132 Spool string `json:"spool"`
133 Log string `json:"log"`
134 Umask *string `json:"umask,omitempty"`
136 OmitPrgrs bool `json:"noprogress,omitempty"`
137 NoHdr bool `json:"nohdr,omitempty"`
139 MCDRxIfis []string `json:"mcd-listen,omitempty"`
140 MCDTxIfis map[string]int `json:"mcd-send,omitempty"`
142 Notify *NotifyJSON `json:"notify,omitempty"`
144 Self *NodeOurJSON `json:"self"`
145 Neigh map[string]NodeJSON `json:"neigh"`
147 Areas map[string]AreaJSON `json:"areas,omitempty"`
150 func NewNode(name string, cfg NodeJSON) (*Node, error) {
151 nodeId, err := NodeIdFromString(cfg.Id)
156 exchPub, err := Base32Codec.DecodeString(cfg.ExchPub)
160 if len(exchPub) != 32 {
161 return nil, errors.New("Invalid exchPub size")
164 signPub, err := Base32Codec.DecodeString(cfg.SignPub)
168 if len(signPub) != ed25519.PublicKeySize {
169 return nil, errors.New("Invalid signPub size")
173 if cfg.NoisePub != nil {
174 noisePub, err = Base32Codec.DecodeString(*cfg.NoisePub)
178 if len(noisePub) != 32 {
179 return nil, errors.New("Invalid noisePub size")
184 if cfg.Incoming != nil {
185 inc := path.Clean(*cfg.Incoming)
186 if !path.IsAbs(inc) {
187 return nil, errors.New("Incoming path must be absolute")
193 freqChunked := int64(MaxFileSize)
194 var freqMinSize int64
195 freqMaxSize := int64(MaxFileSize)
199 fPath := path.Clean(*f.Path)
200 if !path.IsAbs(fPath) {
201 return nil, errors.New("freq.path path must be absolute")
205 if f.Chunked != nil {
207 return nil, errors.New("freq.chunked value must be greater than zero")
209 freqChunked = int64(*f.Chunked) * 1024
211 if f.MinSize != nil {
212 freqMinSize = int64(*f.MinSize) * 1024
214 if f.MaxSize != nil {
215 freqMaxSize = int64(*f.MaxSize) * 1024
220 if cfg.RxRate != nil && *cfg.RxRate > 0 {
221 defRxRate = *cfg.RxRate
224 if cfg.TxRate != nil && *cfg.TxRate > 0 {
225 defTxRate = *cfg.TxRate
228 defOnlineDeadline := DefaultDeadline
229 if cfg.OnlineDeadline != nil {
230 if *cfg.OnlineDeadline <= 0 {
231 return nil, errors.New("OnlineDeadline must be at least 1 second")
233 defOnlineDeadline = time.Duration(*cfg.OnlineDeadline) * time.Second
235 var defMaxOnlineTime time.Duration
236 if cfg.MaxOnlineTime != nil {
237 defMaxOnlineTime = time.Duration(*cfg.MaxOnlineTime) * time.Second
241 for _, callCfg := range cfg.Calls {
242 expr, err := cronexpr.Parse(callCfg.Cron)
248 if callCfg.Nice != nil {
249 nice, err = NicenessParse(*callCfg.Nice)
256 if callCfg.Xx != nil {
263 return nil, errors.New("xx field must be either \"rx\" or \"tx\"")
268 if callCfg.RxRate != nil {
269 rxRate = *callCfg.RxRate
272 if callCfg.TxRate != nil {
273 txRate = *callCfg.TxRate
277 if callCfg.Addr != nil {
278 if a, exists := cfg.Addrs[*callCfg.Addr]; exists {
285 onlineDeadline := defOnlineDeadline
286 if callCfg.OnlineDeadline != nil {
287 if *callCfg.OnlineDeadline == 0 {
288 return nil, errors.New("OnlineDeadline must be at least 1 second")
290 onlineDeadline = time.Duration(*callCfg.OnlineDeadline) * time.Second
300 OnlineDeadline: onlineDeadline,
303 if callCfg.MaxOnlineTime != nil {
304 call.MaxOnlineTime = time.Duration(*callCfg.MaxOnlineTime) * time.Second
306 call.WhenTxExists = callCfg.WhenTxExists
307 call.NoCK = callCfg.NoCK
308 call.MCDIgnore = callCfg.MCDIgnore
309 call.AutoToss = callCfg.AutoToss
310 call.AutoTossDoSeen = callCfg.AutoTossDoSeen
311 call.AutoTossNoFile = callCfg.AutoTossNoFile
312 call.AutoTossNoFreq = callCfg.AutoTossNoFreq
313 call.AutoTossNoExec = callCfg.AutoTossNoExec
314 call.AutoTossNoTrns = callCfg.AutoTossNoTrns
315 call.AutoTossNoArea = callCfg.AutoTossNoArea
317 calls = append(calls, &call)
323 ExchPub: new([32]byte),
324 SignPub: ed25519.PublicKey(signPub),
328 FreqChunked: freqChunked,
329 FreqMinSize: freqMinSize,
330 FreqMaxSize: freqMaxSize,
335 OnlineDeadline: defOnlineDeadline,
336 MaxOnlineTime: defMaxOnlineTime,
338 copy(node.ExchPub[:], exchPub)
339 if len(noisePub) > 0 {
340 node.NoisePub = new([32]byte)
341 copy(node.NoisePub[:], noisePub)
346 func NewNodeOur(cfg *NodeOurJSON) (*NodeOur, error) {
347 id, err := NodeIdFromString(cfg.Id)
352 exchPub, err := Base32Codec.DecodeString(cfg.ExchPub)
356 if len(exchPub) != 32 {
357 return nil, errors.New("Invalid exchPub size")
360 exchPrv, err := Base32Codec.DecodeString(cfg.ExchPrv)
364 if len(exchPrv) != 32 {
365 return nil, errors.New("Invalid exchPrv size")
368 signPub, err := Base32Codec.DecodeString(cfg.SignPub)
372 if len(signPub) != ed25519.PublicKeySize {
373 return nil, errors.New("Invalid signPub size")
376 signPrv, err := Base32Codec.DecodeString(cfg.SignPrv)
380 if len(signPrv) != ed25519.PrivateKeySize {
381 return nil, errors.New("Invalid signPrv size")
384 noisePub, err := Base32Codec.DecodeString(cfg.NoisePub)
388 if len(noisePub) != 32 {
389 return nil, errors.New("Invalid noisePub size")
392 noisePrv, err := Base32Codec.DecodeString(cfg.NoisePrv)
396 if len(noisePrv) != 32 {
397 return nil, errors.New("Invalid noisePrv size")
402 ExchPub: new([32]byte),
403 ExchPrv: new([32]byte),
404 SignPub: ed25519.PublicKey(signPub),
405 SignPrv: ed25519.PrivateKey(signPrv),
406 NoisePub: new([32]byte),
407 NoisePrv: new([32]byte),
409 copy(node.ExchPub[:], exchPub)
410 copy(node.ExchPrv[:], exchPrv)
411 copy(node.NoisePub[:], noisePub)
412 copy(node.NoisePrv[:], noisePrv)
416 func NewArea(ctx *Ctx, name string, cfg *AreaJSON) (*Area, error) {
417 areaId, err := AreaIdFromString(cfg.Id)
421 subs := make([]*NodeId, 0, len(cfg.Subs))
422 for _, s := range cfg.Subs {
423 node, err := ctx.FindNode(s)
427 subs = append(subs, node.Id)
434 Incoming: cfg.Incoming,
437 pub, err := Base32Codec.DecodeString(*cfg.Pub)
442 return nil, errors.New("Invalid pub size")
444 area.Pub = new([32]byte)
445 copy(area.Pub[:], pub)
448 prv, err := Base32Codec.DecodeString(*cfg.Prv)
453 return nil, errors.New("Invalid prv size")
455 area.Prv = new([32]byte)
456 copy(area.Prv[:], prv)
458 area.AllowUnknown = cfg.AllowUnknown
462 func CfgParse(data []byte) (*CfgJSON, error) {
464 if bytes.Compare(data[:8], MagicNNCPBv3.B[:]) == 0 {
465 os.Stderr.WriteString("Passphrase:") // #nosec G104
466 password, err := term.ReadPassword(0)
470 os.Stderr.WriteString("\n") // #nosec G104
471 data, err = DeEBlob(data, password)
475 } else if bytes.Compare(data[:8], MagicNNCPBv2.B[:]) == 0 {
476 log.Fatalln(MagicNNCPBv2.TooOld())
477 } else if bytes.Compare(data[:8], MagicNNCPBv1.B[:]) == 0 {
478 log.Fatalln(MagicNNCPBv1.TooOld())
480 var cfgGeneral map[string]interface{}
481 if err = hjson.Unmarshal(data, &cfgGeneral); err != nil {
484 marshaled, err := json.Marshal(cfgGeneral)
489 err = json.Unmarshal(marshaled, &cfgJSON)
493 func Cfg2Ctx(cfgJSON *CfgJSON) (*Ctx, error) {
494 if _, exists := cfgJSON.Neigh["self"]; !exists {
495 return nil, errors.New("self neighbour missing")
498 if cfgJSON.Self != nil {
500 self, err = NewNodeOur(cfgJSON.Self)
505 spoolPath := path.Clean(cfgJSON.Spool)
506 if !path.IsAbs(spoolPath) {
507 return nil, errors.New("Spool path must be absolute")
509 logPath := path.Clean(cfgJSON.Log)
510 if !path.IsAbs(logPath) {
511 return nil, errors.New("Log path must be absolute")
514 if cfgJSON.Umask != nil {
515 r, err := strconv.ParseUint(*cfgJSON.Umask, 8, 16)
523 if cfgJSON.OmitPrgrs {
533 UmaskForce: umaskForce,
534 ShowPrgrs: showPrgrs,
537 Neigh: make(map[NodeId]*Node, len(cfgJSON.Neigh)),
538 Alias: make(map[string]*NodeId),
539 MCDRxIfis: cfgJSON.MCDRxIfis,
540 MCDTxIfis: cfgJSON.MCDTxIfis,
542 if cfgJSON.Notify != nil {
543 if cfgJSON.Notify.File != nil {
544 ctx.NotifyFile = cfgJSON.Notify.File
546 if cfgJSON.Notify.Freq != nil {
547 ctx.NotifyFreq = cfgJSON.Notify.Freq
549 if cfgJSON.Notify.Exec != nil {
550 ctx.NotifyExec = cfgJSON.Notify.Exec
553 vias := make(map[NodeId][]string)
554 for name, neighJSON := range cfgJSON.Neigh {
555 neigh, err := NewNode(name, neighJSON)
559 ctx.Neigh[*neigh.Id] = neigh
560 if _, already := ctx.Alias[name]; already {
561 return nil, errors.New("Node names conflict")
563 ctx.Alias[name] = neigh.Id
564 vias[*neigh.Id] = neighJSON.Via
566 ctx.SelfId = ctx.Alias["self"]
567 for neighId, viasRaw := range vias {
568 for _, viaRaw := range viasRaw {
569 foundNodeId, err := ctx.FindNode(viaRaw)
573 ctx.Neigh[neighId].Via = append(
574 ctx.Neigh[neighId].Via,
579 ctx.AreaId2Area = make(map[AreaId]*Area, len(cfgJSON.Areas))
580 ctx.AreaName2Id = make(map[string]*AreaId, len(cfgJSON.Areas))
581 for name, areaJSON := range cfgJSON.Areas {
582 area, err := NewArea(&ctx, name, &areaJSON)
586 ctx.AreaId2Area[*area.Id] = area
587 ctx.AreaName2Id[name] = area.Id