-
Notifications
You must be signed in to change notification settings - Fork 1
/
netceptor.go
2063 lines (1855 loc) · 58 KB
/
netceptor.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Package netceptor is the networking layer of Receptor.
package netceptor
import (
"bytes"
"context"
"crypto/sha256"
"crypto/sha512"
"crypto/tls"
"crypto/x509"
"encoding/binary"
"encoding/json"
"fmt"
"io"
"math"
"math/rand"
"reflect"
"strings"
"sync"
"time"
"github.com/distronode/receptor/pkg/logger"
"github.com/distronode/receptor/pkg/randstr"
"github.com/distronode/receptor/pkg/tickrunner"
"github.com/distronode/receptor/pkg/utils"
priorityQueue "github.com/jupp0r/go-priority-queue"
"github.com/minio/highwayhash"
)
// defaultMTU is the largest message sendable over the Netceptor network.
const defaultMTU = 16384
// defaultRouteUpdateTime is the interval at which regular route updates will be sent.
const defaultRouteUpdateTime = 10 * time.Second
// defaultServiceAdTime is the interval at which regular service advertisements will be sent.
const defaultServiceAdTime = 60 * time.Second
// defaultSeenUpdateExpireTime is the age after which routing update IDs can be discarded.
const defaultSeenUpdateExpireTime = 1 * time.Hour
// defaultMaxForwardingHops is the maximum number of times that Netceptor will forward a data packet.
const defaultMaxForwardingHops = 30
// defaultMaxConnectionIdleTime is the maximum time a connection can go without data before we consider it failed.
const defaultMaxConnectionIdleTime = 2*defaultRouteUpdateTime + 1*time.Second
// MainInstance is the global instance of Netceptor instantiated by the command-line main() function.
var MainInstance *Netceptor
// ErrorFunc is a function parameter used to process errors. The boolean parameter
// indicates whether the error is fatal (i.e. the associated process is going to exit).
type ErrorFunc func(error, bool)
// ErrTimeout is returned for an expired deadline.
var ErrTimeout error = &TimeoutError{}
// TimeoutError is returned for an expired deadline.
type TimeoutError struct{}
// Error returns a string describing the error.
func (e *TimeoutError) Error() string { return "i/o timeout" }
// Timeout returns true if this error was a timeout.
func (e *TimeoutError) Timeout() bool { return true }
// Temporary returns true if a retry is likely a good idea.
func (e *TimeoutError) Temporary() bool { return true }
// Backend is the interface for back-ends that the Receptor network can run over.
type Backend interface {
Start(context.Context, *sync.WaitGroup) (chan BackendSession, error)
}
// BackendSession is the interface for a single session of a back-end.
// Backends must be DATAGRAM ORIENTED, meaning that Recv() must return
// whole packets sent by Send(). If the underlying protocol is stream
// oriented, then the backend must deal with any required buffering.
type BackendSession interface {
Send([]byte) error
Recv(time.Duration) ([]byte, error) // Must return netceptor.ErrTimeout if the timeout is exceeded
Close() error
}
// FirewallRuleFunc is a function that takes a message and returns a firewall decision.
type FirewallRuleFunc func(*MessageData) FirewallResult
// FirewallResult enumerates the actions that can be taken as a result of a firewall rule.
type FirewallResult int
const (
// FirewallResultContinue continues processing further rules (no result).
FirewallResultContinue FirewallResult = iota
// FirewallResultAccept accepts the message for normal processing.
FirewallResultAccept
// FirewallResultReject denies the message, sending an unreachable message to the originator.
FirewallResultReject
// FirewallResultDrop denies the message silently, leaving the originator to time out.
FirewallResultDrop
)
// Netceptor is the main object of the Receptor mesh network protocol.
type Netceptor struct {
nodeID string
mtu int
routeUpdateTime time.Duration
serviceAdTime time.Duration
seenUpdateExpireTime time.Duration
maxForwardingHops byte
maxConnectionIdleTime time.Duration
workCommands []WorkCommand
workCommandsLock *sync.RWMutex
epoch uint64
sequence uint64
sequenceLock *sync.RWMutex
connLock *sync.RWMutex
connections map[string]*connInfo
knownNodeLock *sync.RWMutex
knownNodeInfo map[string]*nodeInfo
seenUpdatesLock *sync.RWMutex
seenUpdates map[string]time.Time
knownConnectionCosts map[string]map[string]float64
routingTableLock *sync.RWMutex
routingTable map[string]string
routingPathCosts map[string]float64
listenerLock *sync.RWMutex
listenerRegistry map[string]*PacketConn
sendRouteFloodChan chan time.Duration
updateRoutingTableChan chan time.Duration
context context.Context
cancelFunc context.CancelFunc
hashLock *sync.RWMutex
nameHashes map[uint64]string
reservedServices map[string]func(*MessageData) error
serviceAdsLock *sync.RWMutex
serviceAdsReceived map[string]map[string]*ServiceAdvertisement
sendServiceAdsChan chan time.Duration
backendWaitGroup sync.WaitGroup
backendCount int
backendCancel []context.CancelFunc
networkName string
serverTLSConfigs map[string]*tls.Config
clientTLSConfigs map[string]*tls.Config
clientPinnedFingerprints map[string][][]byte
unreachableBroker *utils.Broker
routingUpdateBroker *utils.Broker
firewallLock *sync.RWMutex
firewallRules []FirewallRuleFunc
Logger *logger.ReceptorLogger
}
// ConnStatus holds information about a single connection in the Status struct.
type ConnStatus struct {
NodeID string
Cost float64
}
// Status is the struct returned by Netceptor.Status(). It represents a public
// view of the internal status of the Netceptor object.
type Status struct {
NodeID string
Connections []*ConnStatus
RoutingTable map[string]string
Advertisements []*ServiceAdvertisement
KnownConnectionCosts map[string]map[string]float64
}
const (
// MsgTypeData is a normal data-containing message.
MsgTypeData = 0
// MsgTypeRoute is a routing update.
MsgTypeRoute = 1
// MsgTypeServiceAdvertisement is an advertisement for a service.
MsgTypeServiceAdvertisement = 2
// MsgTypeReject indicates a rejection (closure) of a backend connection.
MsgTypeReject = 3
)
const (
// ProblemServiceUnknown occurs when a message arrives for a non-listening service.
ProblemServiceUnknown = "service unknown"
// ProblemExpiredInTransit occurs when a message's HopsToLive expires in transit.
ProblemExpiredInTransit = "message expired"
// ProblemRejected occurs when a packet is rejected by a firewall rule.
ProblemRejected = "blocked by firewall"
)
// MessageData contains a single message packet from the network.
type MessageData struct {
FromNode string
FromService string
ToNode string
ToService string
HopsToLive byte
Data []byte
}
type connInfo struct {
ReadChan chan []byte
WriteChan chan []byte
Context context.Context
CancelFunc context.CancelFunc
Cost float64
lastReceivedData time.Time
lastReceivedLock *sync.RWMutex
logger *logger.ReceptorLogger
}
type nodeInfo struct {
Epoch uint64
Sequence uint64
}
type routingUpdate struct {
NodeID string
UpdateID string
UpdateEpoch uint64
UpdateSequence uint64
Connections map[string]float64
ForwardingNode string
SuspectedDuplicate uint64
}
const (
// ConnTypeDatagram indicates a packetconn (datagram) service listener.
ConnTypeDatagram = 0
// ConnTypeStream indicates a conn (stream) service listener, without a user-defined TLS.
ConnTypeStream = 1
// ConnTypeStreamTLS indicates the service listens on a packetconn connection, with a user-defined TLS.
ConnTypeStreamTLS = 2
)
// WorkCommand tracks available work types and whether they verify work submissions.
type WorkCommand struct {
WorkType string
// Secure true means receptor will verify the signature of the work submit payload
Secure bool
}
// ServiceAdvertisement is the data associated with a service advertisement.
type ServiceAdvertisement struct {
NodeID string
Service string
Time time.Time
ConnType byte
Tags map[string]string
WorkCommands []WorkCommand
}
// serviceAdvertisementFull is the whole message from the network.
type serviceAdvertisementFull struct {
*ServiceAdvertisement
Cancel bool
}
// UnreachableMessage is the on-the-wire data associated with an unreachable message.
type UnreachableMessage struct {
FromNode string
ToNode string
FromService string
ToService string
Problem string
}
// UnreachableNotification includes additional information returned from SubscribeUnreachable.
type UnreachableNotification struct {
UnreachableMessage
ReceivedFromNode string
}
var (
networkNames = make([]string, 0)
networkNamesLock = sync.Mutex{}
)
// makeNetworkName returns a network name that is unique within global scope.
func makeNetworkName(nodeID string) string {
networkNamesLock.Lock()
defer networkNamesLock.Unlock()
nameCounter := 1
proposedName := fmt.Sprintf("netceptor-%s", nodeID)
for {
good := true
for i := range networkNames {
if networkNames[i] == proposedName {
good = false
break
}
}
if good {
networkNames = append(networkNames, proposedName)
return proposedName
}
nameCounter++
proposedName = fmt.Sprintf("netceptor-%s-%d", nodeID, nameCounter)
}
}
// NewWithConsts constructs a new Receptor network protocol instance, specifying operational constants.
func NewWithConsts(ctx context.Context, nodeID string,
mtu int, routeUpdateTime time.Duration, serviceAdTime time.Duration, seenUpdateExpireTime time.Duration,
maxForwardingHops byte, maxConnectionIdleTime time.Duration,
) *Netceptor {
s := Netceptor{
nodeID: nodeID,
mtu: mtu,
routeUpdateTime: routeUpdateTime,
serviceAdTime: serviceAdTime,
seenUpdateExpireTime: seenUpdateExpireTime,
maxForwardingHops: maxForwardingHops,
maxConnectionIdleTime: maxConnectionIdleTime,
epoch: uint64(time.Now().Unix()*(1<<24)) + uint64(rand.Intn(1<<24)),
sequence: 0,
sequenceLock: &sync.RWMutex{},
connLock: &sync.RWMutex{},
connections: make(map[string]*connInfo),
knownNodeLock: &sync.RWMutex{},
knownNodeInfo: make(map[string]*nodeInfo),
seenUpdatesLock: &sync.RWMutex{},
seenUpdates: make(map[string]time.Time),
knownConnectionCosts: make(map[string]map[string]float64),
routingTableLock: &sync.RWMutex{},
routingTable: make(map[string]string),
routingPathCosts: make(map[string]float64),
listenerLock: &sync.RWMutex{},
listenerRegistry: make(map[string]*PacketConn),
sendRouteFloodChan: nil,
updateRoutingTableChan: nil,
hashLock: &sync.RWMutex{},
nameHashes: make(map[uint64]string),
serviceAdsLock: &sync.RWMutex{},
serviceAdsReceived: make(map[string]map[string]*ServiceAdvertisement),
sendServiceAdsChan: nil,
backendWaitGroup: sync.WaitGroup{},
backendCount: 0,
backendCancel: nil,
networkName: makeNetworkName(nodeID),
clientTLSConfigs: make(map[string]*tls.Config),
clientPinnedFingerprints: make(map[string][][]byte),
serverTLSConfigs: make(map[string]*tls.Config),
firewallLock: &sync.RWMutex{},
workCommandsLock: &sync.RWMutex{},
Logger: logger.NewReceptorLogger(""),
}
s.reservedServices = map[string]func(*MessageData) error{
"ping": s.handlePing,
"unreach": s.handleUnreachable,
}
if ctx == nil {
ctx = context.Background()
}
s.clientTLSConfigs["default"] = &tls.Config{
MinVersion: tls.VersionTLS12,
}
s.AddNameHash(nodeID)
s.context, s.cancelFunc = context.WithCancel(ctx)
s.unreachableBroker = utils.NewBroker(s.context, reflect.TypeOf(UnreachableNotification{}))
s.routingUpdateBroker = utils.NewBroker(s.context, reflect.TypeOf(map[string]string{}))
s.updateRoutingTableChan = tickrunner.Run(s.context, s.updateRoutingTable, time.Hour*24, time.Millisecond*100)
s.sendRouteFloodChan = tickrunner.Run(s.context, func() { s.sendRoutingUpdate(0) }, s.routeUpdateTime, time.Millisecond*100)
if s.serviceAdTime > 0 {
s.sendServiceAdsChan = tickrunner.Run(s.context, s.sendServiceAds, s.serviceAdTime, time.Second*5)
} else {
s.sendServiceAdsChan = make(chan time.Duration)
go func() {
for {
select {
case <-s.sendServiceAdsChan:
// do nothing
case <-s.context.Done():
return
}
}
}()
}
go s.monitorConnectionAging()
go s.expireSeenUpdates()
return &s
}
// New constructs a new Receptor network protocol instance.
func New(ctx context.Context, nodeID string) *Netceptor {
return NewWithConsts(ctx, nodeID, defaultMTU, defaultRouteUpdateTime, defaultServiceAdTime,
defaultSeenUpdateExpireTime, defaultMaxForwardingHops, defaultMaxConnectionIdleTime)
}
// NewAddr generates a Receptor network address from a node ID and service name.
func (s *Netceptor) NewAddr(node string, service string) Addr {
return Addr{
network: s.networkName,
node: node,
service: service,
}
}
// Context returns the context for this Netceptor instance.
func (s *Netceptor) Context() context.Context {
return s.context
}
// Shutdown shuts down a Netceptor instance.
func (s *Netceptor) Shutdown() {
s.cancelFunc()
}
// NetceptorDone returns the channel for the netceptor context.
func (s *Netceptor) NetceptorDone() <-chan struct{} {
return s.context.Done()
}
// NodeID returns the local Node ID of this Netceptor instance.
func (s *Netceptor) NodeID() string {
return s.nodeID
}
// MTU returns the configured MTU of this Netceptor instance.
func (s *Netceptor) MTU() int {
return s.mtu
}
// RouteUpdateTime returns the configured RouteUpdateTime of this Netceptor instance.
func (s *Netceptor) RouteUpdateTime() time.Duration {
return s.routeUpdateTime
}
// ServiceAdTime returns the configured ServiceAdTime of this Netceptor instance.
func (s *Netceptor) ServiceAdTime() time.Duration {
return s.serviceAdTime
}
// SeenUpdateExpireTime returns the configured SeenUpdateExpireTime of this Netceptor instance.
func (s *Netceptor) SeenUpdateExpireTime() time.Duration {
return s.seenUpdateExpireTime
}
// MaxForwardingHops returns the configured MaxForwardingHops of this Netceptor instance.
func (s *Netceptor) MaxForwardingHops() byte {
return s.maxForwardingHops
}
// MaxConnectionIdleTime returns the configured MaxConnectionIdleTime of this Netceptor instance.
func (s *Netceptor) MaxConnectionIdleTime() time.Duration {
return s.maxConnectionIdleTime
}
// GetLogger returns the logger of this Netceptor instance.
func (s *Netceptor) GetLogger() *logger.ReceptorLogger {
return s.Logger
}
// GetListenerRegistry returns listener registry map.
func (s *Netceptor) GetListenerRegistry() map[string]*PacketConn {
return s.listenerRegistry
}
// GetNetworkName returns networkName.
func (s *Netceptor) GetNetworkName() string {
return s.networkName
}
// GetListenerLock returns listenerLock.
func (s *Netceptor) GetListenerLock() *sync.RWMutex {
return s.listenerLock
}
// GetUnreachableBroker returns unreachableBroker.
func (s *Netceptor) GetUnreachableBroker() *utils.Broker {
return s.unreachableBroker
}
// Sets the MaxConnectionIdleTime object on the Netceptor instance.
func (s *Netceptor) SetMaxConnectionIdleTime(userDefinedMaxIdleConnectionTimeout string) error {
// before we instantiate a new instance of Netceptor, let's verify that the user defined maxidleconnectiontimeout value is parseable
duration, err := time.ParseDuration(userDefinedMaxIdleConnectionTimeout)
if err != nil {
return fmt.Errorf("failed to parse MaxIdleConnectionTimeout from configuration file -- valid examples include '1.5h', '30m', '30m10s'")
}
// we don't want the user defined timeout to be less than the defaultMaxConnectionIdleTime constant
if duration < defaultMaxConnectionIdleTime {
return fmt.Errorf("user defined maxIdleConnectionTimeout [%d] is less than the default default timeout [%d]", duration, defaultMaxConnectionIdleTime)
}
s.maxConnectionIdleTime = duration
return nil
}
type BackendInfo struct {
connectionCost float64
nodeCost map[string]float64
allowedPeers []string
}
// BackendConnectionCost is a modifier for AddBackend, which sets the global connection cost.
func BackendConnectionCost(cost float64) func(*BackendInfo) {
return func(bi *BackendInfo) {
bi.connectionCost = cost
}
}
// BackendNodeCost is a modifier for AddBackend, which sets the per-node connection costs.
func BackendNodeCost(nodeCost map[string]float64) func(*BackendInfo) {
return func(bi *BackendInfo) {
bi.nodeCost = nodeCost
}
}
// BackendAllowedPeers is a modifier for AddBackend, which sets the list of peers allowed to connect.
func BackendAllowedPeers(peers []string) func(*BackendInfo) {
return func(bi *BackendInfo) {
bi.allowedPeers = peers
}
}
// AddBackend adds a backend to the Netceptor system.
func (s *Netceptor) AddBackend(backend Backend, modifiers ...func(*BackendInfo)) error {
bi := &BackendInfo{
connectionCost: 1.0,
nodeCost: nil,
allowedPeers: nil,
}
for _, mod := range modifiers {
mod(bi)
}
ctxBackend, cancel := context.WithCancel(s.context)
s.backendCancel = append(s.backendCancel, cancel)
// Start() runs a go routine that attempts establish a session over this
// backend. For listeners, each time a peer dials this backend, sessChan is
// written to, resulting in multiple ongoing sessions at once.
sessChan, err := backend.Start(ctxBackend, &s.backendWaitGroup)
if err != nil {
return err
}
s.backendWaitGroup.Add(1)
s.backendCount++
// Outer go routine -- this go routine waits for new sessions to be written to the sessChan and
// starts the runProtocol() for that session
go func() {
runProtocolWg := sync.WaitGroup{}
defer func() {
// First wait for all session protocols to finish (the inner go routines)
// for this backend before exiting this outer go routine.
// It is important that the inner go routine is on a separate wait group
// from the outer go routine.
runProtocolWg.Wait()
s.backendWaitGroup.Done()
}()
for {
select {
case sess, ok := <-sessChan:
if ok {
runProtocolWg.Add(1)
// Inner go routine -- start the runProtocol loop for the new session
// that was just passed to sessChan (which was written to from the
// Start() method above)
go func() {
defer runProtocolWg.Done()
err := s.runProtocol(ctxBackend, sess, bi)
if err != nil {
s.Logger.SanitizedError("Backend error: %s\n", err)
}
}()
} else {
return
}
case <-ctxBackend.Done():
return
}
}
}()
return nil
}
// BackendWait waits for the backend wait group.
func (s *Netceptor) BackendWait() {
s.backendWaitGroup.Wait()
}
// BackendDone calls Done on the backendWaitGroup.
func (s *Netceptor) BackendDone() {
s.backendWaitGroup.Done()
}
// BackendCount returns the number of backends that ever registered with this Netceptor.
func (s *Netceptor) BackendCount() int {
return s.backendCount
}
// CancelBackends stops all backends by calling a context cancel.
func (s *Netceptor) CancelBackends() {
s.Logger.Debug("Canceling backends")
for i := range s.backendCancel {
// a context cancel function
s.backendCancel[i]()
}
s.BackendWait()
s.backendCancel = nil
s.backendCount = 0
}
// Status returns the current state of the Netceptor object.
func (s *Netceptor) Status() Status {
s.connLock.RLock()
conns := make([]*ConnStatus, 0)
for conn := range s.connections {
conns = append(conns, &ConnStatus{
NodeID: conn,
Cost: s.connections[conn].Cost,
})
}
s.connLock.RUnlock()
s.routingTableLock.RLock()
routes := make(map[string]string)
for k, v := range s.routingTable {
routes[k] = v
}
s.routingTableLock.RUnlock()
s.serviceAdsLock.RLock()
serviceAds := make([]*ServiceAdvertisement, 0)
for n := range s.serviceAdsReceived {
for _, ad := range s.serviceAdsReceived[n] {
adCopy := *ad
if adCopy.NodeID == s.nodeID {
adCopy.Time = time.Now()
s.workCommandsLock.RLock()
if len(s.workCommands) > 0 {
adCopy.WorkCommands = s.workCommands
}
s.workCommandsLock.RUnlock()
}
serviceAds = append(serviceAds, &adCopy)
}
}
s.serviceAdsLock.RUnlock()
s.knownNodeLock.RLock()
knownConnectionCosts := make(map[string]map[string]float64)
for k1, v1 := range s.knownConnectionCosts {
knownConnectionCosts[k1] = make(map[string]float64)
for k2, v2 := range v1 {
knownConnectionCosts[k1][k2] = v2
}
}
s.knownNodeLock.RUnlock()
return Status{
NodeID: s.nodeID,
Connections: conns,
RoutingTable: routes,
Advertisements: serviceAds,
KnownConnectionCosts: knownConnectionCosts,
}
}
// PathCost returns the cost to a given remote node, or an error if the node doesn't exist.
func (s *Netceptor) PathCost(nodeID string) (float64, error) {
s.routingTableLock.RLock()
defer s.routingTableLock.RUnlock()
cost, ok := s.routingPathCosts[nodeID]
if !ok {
return 0, fmt.Errorf("node not found")
}
return cost, nil
}
// AddFirewallRules adds firewall rules, optionally clearing existing rules first.
func (s *Netceptor) AddFirewallRules(rules []FirewallRuleFunc, clearExisting bool) error {
s.firewallLock.Lock()
defer s.firewallLock.Unlock()
if clearExisting {
s.firewallRules = nil
}
s.firewallRules = append(s.firewallRules, rules...)
return nil
}
func (s *Netceptor) AddLocalServiceAdvertisement(service string, connType byte, tags map[string]string) {
s.serviceAdsLock.Lock()
n, ok := s.serviceAdsReceived[s.nodeID]
if !ok {
n = make(map[string]*ServiceAdvertisement)
s.serviceAdsReceived[s.nodeID] = n
}
n[service] = &ServiceAdvertisement{
NodeID: s.nodeID,
Service: service,
Time: time.Now(),
ConnType: connType,
Tags: tags,
}
s.serviceAdsLock.Unlock()
select {
case <-s.context.Done():
return
case s.sendServiceAdsChan <- 0:
default:
}
}
func (s *Netceptor) RemoveLocalServiceAdvertisement(service string) error {
s.serviceAdsLock.Lock()
defer s.serviceAdsLock.Unlock()
n, ok := s.serviceAdsReceived[s.nodeID]
connType := n[service].ConnType
if ok {
delete(n, service)
}
sa := &serviceAdvertisementFull{
ServiceAdvertisement: &ServiceAdvertisement{
NodeID: s.nodeID,
Service: service,
Time: time.Now(),
ConnType: connType,
Tags: nil,
},
Cancel: true,
}
data, err := s.translateStructToNetwork(MsgTypeServiceAdvertisement, sa)
if err != nil {
return err
}
s.flood(data, "")
return nil
}
// Send a single service broadcast.
func (s *Netceptor) sendServiceAd(si *ServiceAdvertisement) error {
s.Logger.Debug("Sending service advertisement: %v\n", si)
sf := serviceAdvertisementFull{
ServiceAdvertisement: si,
Cancel: false,
}
data, err := s.translateStructToNetwork(MsgTypeServiceAdvertisement, sf)
if err != nil {
return err
}
s.flood(data, "")
return nil
}
// Send advertisements for all advertised services.
func (s *Netceptor) sendServiceAds() {
ads := make([]ServiceAdvertisement, 0)
s.listenerLock.RLock()
for sn := range s.listenerRegistry {
if s.listenerRegistry[sn].advertise {
sa := ServiceAdvertisement{
NodeID: s.nodeID,
Service: sn,
Time: time.Now(),
ConnType: s.listenerRegistry[sn].connType,
Tags: s.listenerRegistry[sn].adTags,
}
if svcType, ok := sa.Tags["type"]; ok {
if svcType == "Control Service" {
s.workCommandsLock.RLock()
if len(s.workCommands) > 0 {
sa.WorkCommands = s.workCommands
}
s.workCommandsLock.RUnlock()
}
}
ads = append(ads, sa)
}
}
s.listenerLock.RUnlock()
for i := range ads {
err := s.sendServiceAd(&ads[i])
if err != nil {
s.Logger.Error("Error sending service advertisement: %s\n", err)
}
}
}
// Watches connections and expires any that haven't seen traffic in too long.
func (s *Netceptor) monitorConnectionAging() {
for {
select {
case <-time.After(5 * time.Second):
timedOut := make(map[string]context.CancelFunc, 0)
s.connLock.RLock()
for conn := range s.connections {
connInfo := s.connections[conn]
connInfo.lastReceivedLock.RLock()
if time.Since(connInfo.lastReceivedData) > s.maxConnectionIdleTime {
timedOut[conn] = s.connections[conn].CancelFunc
}
connInfo.lastReceivedLock.RUnlock()
}
s.connLock.RUnlock()
for conn := range timedOut {
s.Logger.Warning("Timing out connection %s, idle for the past %s\n", conn, s.maxConnectionIdleTime)
timedOut[conn]()
s.removeConnection(conn)
}
case <-s.context.Done():
return
}
}
}
// Expires old updates from the seenUpdates table.
func (s *Netceptor) expireSeenUpdates() {
for {
select {
case <-time.After(s.seenUpdateExpireTime / 2):
thresholdTime := time.Now().Add(-s.seenUpdateExpireTime)
s.seenUpdatesLock.Lock()
for id := range s.seenUpdates {
if s.seenUpdates[id].Before(thresholdTime) {
delete(s.seenUpdates, id)
}
}
s.seenUpdatesLock.Unlock()
case <-s.context.Done():
return
}
}
}
// Re-calculates the next-hop table based on current knowledge of the network.
func (s *Netceptor) updateRoutingTable() {
s.knownNodeLock.RLock()
defer s.knownNodeLock.RUnlock()
s.Logger.Debug("Re-calculating routing table\n")
// Dijkstra's algorithm
Q := priorityQueue.New()
Q.Insert(s.nodeID, 0.0)
cost := make(map[string]float64)
prev := make(map[string]string)
for node := range s.knownConnectionCosts {
if node == s.nodeID {
cost[node] = 0.0
} else {
cost[node] = math.MaxFloat64
}
prev[node] = ""
Q.Insert(node, cost[node])
}
for Q.Len() > 0 {
nodeIf, _ := Q.Pop()
node := fmt.Sprintf("%v", nodeIf)
for neighbor, edgeCost := range s.knownConnectionCosts[node] {
pathCost := cost[node] + edgeCost
if pathCost < cost[neighbor] {
cost[neighbor] = pathCost
prev[neighbor] = node
Q.Insert(neighbor, pathCost)
}
}
}
s.routingTableLock.Lock()
defer s.routingTableLock.Unlock()
s.routingTable = make(map[string]string)
for dest := range s.knownConnectionCosts {
p := dest
for {
if prev[p] == s.nodeID {
s.routingTable[dest] = p
break
} else if prev[p] == "" {
break
}
p = prev[p]
}
}
s.routingPathCosts = cost
routingTableCopy := make(map[string]string)
for k, v := range s.routingTable {
routingTableCopy[k] = v
}
go s.routingUpdateBroker.Publish(routingTableCopy)
s.printRoutingTable()
}
// SubscribeRoutingUpdates subscribes for messages when the routing table is changed.
func (s *Netceptor) SubscribeRoutingUpdates() chan map[string]string {
iChan := s.routingUpdateBroker.Subscribe()
uChan := make(chan map[string]string)
go func() {
for {
select {
case msgIf, ok := <-iChan:
if !ok {
close(uChan)
return
}
msg, ok := msgIf.(map[string]string)
if !ok {
continue
}
select {
case uChan <- msg:
case <-s.context.Done():
close(uChan)
return
}
case <-s.context.Done():
close(uChan)
return
}
}
}()
return uChan
}
// Forwards a message to all neighbors, possibly excluding one.
func (s *Netceptor) flood(message []byte, excludeConn string) {
s.connLock.RLock()
defer s.connLock.RUnlock()
for conn, ci := range s.connections {
if conn != excludeConn {
go func(conn string, ci *connInfo) {
select {
case ci.WriteChan <- message:
case <-ci.Context.Done():
s.Logger.Debug("connInfo for connection %s cancelled during flood write", conn)
}
}(conn, ci)
}
}
}
// GetServerTLSConfig retrieves a server TLS config by name.
func (s *Netceptor) GetServerTLSConfig(name string) (*tls.Config, error) {
if name == "" {
return nil, nil
}
sc, ok := s.serverTLSConfigs[name]
if !ok {
return nil, fmt.Errorf("unknown TLS config %s", name)
}
return sc.Clone(), nil
}
// AddWorkCommand records a work command so it can be included in service announcements.
func (s *Netceptor) AddWorkCommand(command string, secure bool) error {
if command == "" {
return fmt.Errorf("must provide a name")
}
wC := WorkCommand{WorkType: command, Secure: secure}
s.workCommandsLock.Lock()
defer s.workCommandsLock.Unlock()
s.workCommands = append(s.workCommands, wC)
return nil
}
// SetServerTLSConfig stores a server TLS config by name.
func (s *Netceptor) SetServerTLSConfig(name string, config *tls.Config) error {
if name == "" {
return fmt.Errorf("must provide a name")
}
s.serverTLSConfigs[name] = config
return nil
}
// ReceptorCertNameError is the error produced when Receptor certificate name verification fails.
type ReceptorCertNameError struct {
ValidNodes []string
ExpectedNode string
}
func (rce ReceptorCertNameError) Error() string {
if len(rce.ValidNodes) == 0 {
return fmt.Sprintf("x509: certificate is not valid for any Receptor node IDs, but wanted to match %s",
rce.ExpectedNode)
}
var plural string
if len(rce.ValidNodes) > 1 {
plural = "s"
}
return fmt.Sprintf("x509: certificate is valid for Receptor node ID%s %s, not %s",
plural, strings.Join(rce.ValidNodes, ", "), rce.ExpectedNode)
}
// VerifyType indicates whether we are verifying a server or client.
type VerifyType int
const (
// VerifyServer indicates we are the client, verifying a server.
VerifyServer VerifyType = 1
// VerifyClient indicates we are the server, verifying a client.
VerifyClient = 2