-
Notifications
You must be signed in to change notification settings - Fork 160
/
dataplane.go
2175 lines (1997 loc) · 64.8 KB
/
dataplane.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
// Copyright 2020 Anapaya Systems
// Copyright 2023 ETH Zurich
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package router
import (
"bytes"
"context"
"crypto/rand"
"crypto/subtle"
"errors"
"fmt"
"hash"
"hash/fnv"
"math"
"math/big"
"net"
"runtime"
"strconv"
"sync"
"syscall"
"time"
"github.com/google/gopacket"
"github.com/google/gopacket/layers"
"github.com/prometheus/client_golang/prometheus"
"golang.org/x/sync/errgroup"
"github.com/scionproto/scion/pkg/addr"
"github.com/scionproto/scion/pkg/drkey"
libepic "github.com/scionproto/scion/pkg/experimental/epic"
"github.com/scionproto/scion/pkg/log"
"github.com/scionproto/scion/pkg/private/serrors"
"github.com/scionproto/scion/pkg/private/util"
"github.com/scionproto/scion/pkg/scrypto"
"github.com/scionproto/scion/pkg/slayers"
"github.com/scionproto/scion/pkg/slayers/path"
"github.com/scionproto/scion/pkg/slayers/path/empty"
"github.com/scionproto/scion/pkg/slayers/path/epic"
"github.com/scionproto/scion/pkg/slayers/path/onehop"
"github.com/scionproto/scion/pkg/slayers/path/scion"
"github.com/scionproto/scion/pkg/spao"
"github.com/scionproto/scion/private/topology"
underlayconn "github.com/scionproto/scion/private/underlay/conn"
"github.com/scionproto/scion/router/bfd"
"github.com/scionproto/scion/router/control"
)
const (
// TODO(karampok). Investigate whether that value should be higher. In
// theory, PayloadLen in SCION header is 16 bits long, supporting a maximum
// payload size of 64KB. At the moment we are limited by Ethernet size
// usually ~1500B, but 9000B to support jumbo frames.
bufSize = 9000
// hopFieldDefaultExpTime is the default validity of the hop field
// and 63 is equivalent to 6h.
hopFieldDefaultExpTime = 63
// e2eAuthHdrLen is the length in bytes of added information when a SCMP packet
// needs to be authenticated: 16B (e2e.option.Len()) + 16B (CMAC_tag.Len()).
e2eAuthHdrLen = 32
)
type bfdSession interface {
Run(ctx context.Context) error
ReceiveMessage(*layers.BFD)
IsUp() bool
}
// BatchConn is a connection that supports batch reads and writes.
type BatchConn interface {
ReadBatch(underlayconn.Messages) (int, error)
WriteTo([]byte, *net.UDPAddr) (int, error)
WriteBatch(msgs underlayconn.Messages, flags int) (int, error)
Close() error
}
// DataPlane contains a SCION Border Router's forwarding logic. It reads packets
// from multiple sockets, performs routing, and sends them to their destinations
// (after updating the path, if that is needed).
//
// XXX(lukedirtwalker): this is still in development and not feature complete.
// Currently, only the following features are supported:
// - initializing connections; MUST be done prior to calling Run
type DataPlane struct {
external map[uint16]BatchConn
linkTypes map[uint16]topology.LinkType
neighborIAs map[uint16]addr.IA
internal BatchConn
internalIP *net.IPAddr
internalNextHops map[uint16]*net.UDPAddr
svc *services
macFactory func() hash.Hash
bfdSessions map[uint16]bfdSession
localIA addr.IA
mtx sync.Mutex
running bool
Metrics *Metrics
forwardingMetrics map[uint16]forwardingMetrics
// fields for the router-internal queues and routines, see
// https://github.com/scionproto/scion/blob/master/doc/dev/design/BorderRouter.rst
interfaces map[uint16]NetworkInterface
numProcRoutines uint32
procChannels []chan *packet
forwardChannels map[uint16]chan *packet
packetPool chan *packet
interfaceBatchSize int
processorQueueSize int
forwarderQueueSize int
// the random value is hashed together with the flowID and the address header
// to identify the processing routine that is responsible to process a packet
randomValue []byte
}
var (
alreadySet = serrors.New("already set")
invalidSrcIA = serrors.New("invalid source ISD-AS")
invalidDstIA = serrors.New("invalid destination ISD-AS")
invalidSrcAddrForTransit = serrors.New("invalid source address for transit pkt")
cannotRoute = serrors.New("cannot route, dropping pkt")
emptyValue = serrors.New("empty value")
malformedPath = serrors.New("malformed path content")
modifyExisting = serrors.New("modifying a running dataplane is not allowed")
noSVCBackend = serrors.New("cannot find internal IP for the SVC")
unsupportedPathType = serrors.New("unsupported path type")
unsupportedPathTypeNextHeader = serrors.New("unsupported combination")
noBFDSessionFound = serrors.New("no BFD sessions was found")
noBFDSessionConfigured = serrors.New("no BFD sessions have been configured")
errBFDDisabled = serrors.New("BFD is disabled")
// zeroBuffer will be used to reset the Authenticator option in the
// scionPacketProcessor.OptAuth
zeroBuffer = make([]byte, 16)
)
type drkeyProvider interface {
GetAuthKey(validTime time.Time, dstIA addr.IA, dstAddr net.Addr) (drkey.Key, error)
}
type scmpError struct {
TypeCode slayers.SCMPTypeCode
Cause error
}
func (e scmpError) Error() string {
return serrors.New("scmp", "typecode", e.TypeCode, "cause", e.Cause).Error()
}
// SetIA sets the local IA for the dataplane.
func (d *DataPlane) SetIA(ia addr.IA) error {
d.mtx.Lock()
defer d.mtx.Unlock()
if d.running {
return modifyExisting
}
if ia.IsZero() {
return emptyValue
}
if !d.localIA.IsZero() {
return alreadySet
}
d.localIA = ia
return nil
}
// SetKey sets the key used for MAC verification. The key provided here should
// already be derived as in scrypto.HFMacFactory.
func (d *DataPlane) SetKey(key []byte) error {
d.mtx.Lock()
defer d.mtx.Unlock()
if d.running {
return modifyExisting
}
if len(key) == 0 {
return emptyValue
}
if d.macFactory != nil {
return alreadySet
}
// First check for MAC creation errors.
if _, err := scrypto.InitMac(key); err != nil {
return err
}
d.macFactory = func() hash.Hash {
mac, _ := scrypto.InitMac(key)
return mac
}
return nil
}
// AddInternalInterface sets the interface the data-plane will use to
// send/receive traffic in the local AS. This can only be called once; future
// calls will return an error. This can only be called on a not yet running
// dataplane.
func (d *DataPlane) AddInternalInterface(conn BatchConn, ip net.IP) error {
d.mtx.Lock()
defer d.mtx.Unlock()
if d.running {
return modifyExisting
}
if conn == nil {
return emptyValue
}
if d.internal != nil {
return alreadySet
}
d.internal = conn
d.internalIP = &net.IPAddr{IP: ip}
return nil
}
// AddExternalInterface adds the inter AS connection for the given interface ID.
// If a connection for the given ID is already set this method will return an
// error. This can only be called on a not yet running dataplane.
func (d *DataPlane) AddExternalInterface(ifID uint16, conn BatchConn) error {
d.mtx.Lock()
defer d.mtx.Unlock()
if d.running {
return modifyExisting
}
if conn == nil {
return emptyValue
}
if _, exists := d.external[ifID]; exists {
return serrors.WithCtx(alreadySet, "ifID", ifID)
}
if d.external == nil {
d.external = make(map[uint16]BatchConn)
}
d.external[ifID] = conn
return nil
}
// AddNeighborIA adds the neighboring IA for a given interface ID. If an IA for
// the given ID is already set, this method will return an error. This can only
// be called on a yet running dataplane.
func (d *DataPlane) AddNeighborIA(ifID uint16, remote addr.IA) error {
d.mtx.Lock()
defer d.mtx.Unlock()
if d.running {
return modifyExisting
}
if remote.IsZero() {
return emptyValue
}
if _, exists := d.neighborIAs[ifID]; exists {
return serrors.WithCtx(alreadySet, "ifID", ifID)
}
if d.neighborIAs == nil {
d.neighborIAs = make(map[uint16]addr.IA)
}
d.neighborIAs[ifID] = remote
return nil
}
// AddLinkType adds the link type for a given interface ID. If a link type for
// the given ID is already set, this method will return an error. This can only
// be called on a not yet running dataplane.
func (d *DataPlane) AddLinkType(ifID uint16, linkTo topology.LinkType) error {
if _, exists := d.linkTypes[ifID]; exists {
return serrors.WithCtx(alreadySet, "ifID", ifID)
}
if d.linkTypes == nil {
d.linkTypes = make(map[uint16]topology.LinkType)
}
d.linkTypes[ifID] = linkTo
return nil
}
// AddExternalInterfaceBFD adds the inter AS connection BFD session.
func (d *DataPlane) AddExternalInterfaceBFD(ifID uint16, conn BatchConn,
src, dst control.LinkEnd, cfg control.BFD) error {
d.mtx.Lock()
defer d.mtx.Unlock()
if d.running {
return modifyExisting
}
if conn == nil {
return emptyValue
}
var m bfd.Metrics
if d.Metrics != nil {
labels := prometheus.Labels{
"interface": fmt.Sprint(ifID),
"isd_as": d.localIA.String(),
"neighbor_isd_as": dst.IA.String(),
}
m = bfd.Metrics{
Up: d.Metrics.InterfaceUp.With(labels),
StateChanges: d.Metrics.BFDInterfaceStateChanges.With(labels),
PacketsSent: d.Metrics.BFDPacketsSent.With(labels),
PacketsReceived: d.Metrics.BFDPacketsReceived.With(labels),
}
}
s := newBFDSend(conn, src.IA, dst.IA, src.Addr, dst.Addr, ifID, d.macFactory())
return d.addBFDController(ifID, s, cfg, m)
}
// getInterfaceState checks if there is a bfd session for the input interfaceID and
// returns InterfaceUp if the relevant bfdsession state is up, or if there is no BFD
// session. Otherwise, it returns InterfaceDown.
func (d *DataPlane) getInterfaceState(interfaceID uint16) control.InterfaceState {
bfdSessions := d.bfdSessions
if bfdSession, ok := bfdSessions[interfaceID]; ok && !bfdSession.IsUp() {
return control.InterfaceDown
}
return control.InterfaceUp
}
func (d *DataPlane) addBFDController(ifID uint16, s *bfdSend, cfg control.BFD,
metrics bfd.Metrics) error {
if cfg.Disable {
return errBFDDisabled
}
if d.bfdSessions == nil {
d.bfdSessions = make(map[uint16]bfdSession)
}
// Generate random discriminator. It can't be zero.
discInt, err := rand.Int(rand.Reader, big.NewInt(0xfffffffe))
if err != nil {
return err
}
disc := layers.BFDDiscriminator(uint32(discInt.Uint64()) + 1)
d.bfdSessions[ifID] = &bfd.Session{
Sender: s,
DetectMult: layers.BFDDetectMultiplier(cfg.DetectMult),
DesiredMinTxInterval: cfg.DesiredMinTxInterval,
RequiredMinRxInterval: cfg.RequiredMinRxInterval,
LocalDiscriminator: disc,
ReceiveQueueSize: 10,
Metrics: metrics,
}
return nil
}
// AddSvc adds the address for the given service. This can be called multiple
// times for the same service, with the address added to the list of addresses
// that provide the service.
func (d *DataPlane) AddSvc(svc addr.HostSVC, a *net.UDPAddr) error {
d.mtx.Lock()
defer d.mtx.Unlock()
if a == nil {
return emptyValue
}
if d.svc == nil {
d.svc = newServices()
}
d.svc.AddSvc(svc, a)
if d.Metrics != nil {
labels := serviceMetricLabels(d.localIA, svc)
d.Metrics.ServiceInstanceChanges.With(labels).Add(1)
d.Metrics.ServiceInstanceCount.With(labels).Add(1)
}
return nil
}
// DelSvc deletes the address for the given service.
func (d *DataPlane) DelSvc(svc addr.HostSVC, a *net.UDPAddr) error {
d.mtx.Lock()
defer d.mtx.Unlock()
if a == nil {
return emptyValue
}
if d.svc == nil {
return nil
}
d.svc.DelSvc(svc, a)
if d.Metrics != nil {
labels := serviceMetricLabels(d.localIA, svc)
d.Metrics.ServiceInstanceChanges.With(labels).Add(1)
d.Metrics.ServiceInstanceCount.With(labels).Add(-1)
}
return nil
}
// AddNextHop sets the next hop address for the given interface ID. If the
// interface ID already has an address associated this operation fails. This can
// only be called on a not yet running dataplane.
func (d *DataPlane) AddNextHop(ifID uint16, a *net.UDPAddr) error {
d.mtx.Lock()
defer d.mtx.Unlock()
if d.running {
return modifyExisting
}
if a == nil {
return emptyValue
}
if _, exists := d.internalNextHops[ifID]; exists {
return serrors.WithCtx(alreadySet, "ifID", ifID)
}
if d.internalNextHops == nil {
d.internalNextHops = make(map[uint16]*net.UDPAddr)
}
d.internalNextHops[ifID] = a
return nil
}
// AddNextHopBFD adds the BFD session for the next hop address.
// If the remote ifID belongs to an existing address, the existing
// BFD session will be re-used.
func (d *DataPlane) AddNextHopBFD(ifID uint16, src, dst *net.UDPAddr, cfg control.BFD,
sibling string) error {
d.mtx.Lock()
defer d.mtx.Unlock()
if d.running {
return modifyExisting
}
if dst == nil {
return emptyValue
}
for k, v := range d.internalNextHops {
if v.String() == dst.String() {
if c, ok := d.bfdSessions[k]; ok {
d.bfdSessions[ifID] = c
return nil
}
}
}
var m bfd.Metrics
if d.Metrics != nil {
labels := prometheus.Labels{"isd_as": d.localIA.String(), "sibling": sibling}
m = bfd.Metrics{
Up: d.Metrics.SiblingReachable.With(labels),
StateChanges: d.Metrics.SiblingBFDStateChanges.With(labels),
PacketsSent: d.Metrics.SiblingBFDPacketsSent.With(labels),
PacketsReceived: d.Metrics.SiblingBFDPacketsReceived.With(labels),
}
}
s := newBFDSend(d.internal, d.localIA, d.localIA, src, dst, 0, d.macFactory())
return d.addBFDController(ifID, s, cfg, m)
}
// Run starts running the dataplane. Note that configuration is not possible
// after calling this method.
func (d *DataPlane) Run(ctx context.Context) error {
d.mtx.Lock()
d.running = true
d.initMetrics()
d.initComponents(ctx)
d.mtx.Unlock()
<-ctx.Done()
return nil
}
func (d *DataPlane) Exit() {
d.running = false
for _, ni := range d.interfaces {
ni.Conn.Close()
}
}
// loadDefaults sets the default configuration for the number of
// processing routines, the random value, the batch and queue sizes
func (d *DataPlane) loadDefaults() {
// TODO(rohrerj) move this logic to configuration in configuration PR
d.numProcRoutines = uint32(runtime.GOMAXPROCS(0))
d.forwarderQueueSize = 256
d.interfaceBatchSize = 256
d.processorQueueSize = int(math.Max(
float64(len(d.interfaces)*d.interfaceBatchSize/int(d.numProcRoutines)),
float64(d.interfaceBatchSize)))
d.randomValue = make([]byte, 16)
if _, err := rand.Read(d.randomValue); err != nil {
log.Error("Error while generating random value", "err", err)
}
}
// initializePacketPool calculates the size of the packet pool based on the
// current dataplane settings and allocates all the buffers
func (d *DataPlane) initializePacketPool() {
poolSize := len(d.interfaces)*d.interfaceBatchSize +
int(d.numProcRoutines)*(d.processorQueueSize+1) +
len(d.interfaces)*(d.forwarderQueueSize+d.interfaceBatchSize)
log.Debug("Initialize packet pool of size", "poolSize", poolSize)
d.packetPool = make(chan *packet, poolSize)
for i := 0; i < poolSize; i++ {
d.packetPool <- &packet{
rawPacket: make([]byte, bufSize),
}
}
}
// initComponents initializes the channels, buffers, the receivers, the forwarders,
// processing routines and the bfd sessions
func (d *DataPlane) initComponents(ctx context.Context) {
receiverGroup := &errgroup.Group{}
procGroup := &errgroup.Group{}
forwarderGroup := &errgroup.Group{}
d.interfaces = make(map[uint16]NetworkInterface)
d.interfaces[0] = NetworkInterface{
InterfaceId: 0,
Conn: d.internal,
}
for id, conn := range d.external {
d.interfaces[id] = NetworkInterface{
InterfaceId: id,
Conn: conn,
}
}
d.loadDefaults()
d.initializePacketPool()
d.procChannels = make([]chan *packet, d.numProcRoutines)
for i := 0; i < int(d.numProcRoutines); i++ {
d.procChannels[i] = make(chan *packet, d.processorQueueSize)
}
d.forwardChannels = make(map[uint16]chan *packet)
for _, ni := range d.interfaces {
d.forwardChannels[ni.InterfaceId] = make(chan *packet, d.forwarderQueueSize)
}
for _, ni := range d.interfaces {
func(ni NetworkInterface) {
receiverGroup.Go(func() error {
defer log.HandlePanic()
d.runReceiver(ni)
return nil
})
forwarderGroup.Go(func() error {
defer log.HandlePanic()
d.runForwarder(ni)
return nil
})
}(ni)
}
for i := 0; i < int(d.numProcRoutines); i++ {
func(i int) {
procGroup.Go(func() error {
defer log.HandlePanic()
d.runProcessingRoutine(i)
return nil
})
}(i)
}
for k, v := range d.bfdSessions {
go func(ifID uint16, c bfdSession) {
defer log.HandlePanic()
if err := c.Run(ctx); err != nil && err != bfd.AlreadyRunning {
log.Error("BFD session failed to start", "ifID", ifID, "err", err)
}
}(k, v)
}
if err := receiverGroup.Wait(); err != nil {
log.Debug("Receiver error", "err", err)
}
for _, ch := range d.procChannels {
close(ch)
}
if err := procGroup.Wait(); err != nil {
log.Debug("Processing error", "err", err)
}
for _, ch := range d.forwardChannels {
close(ch)
}
if err := forwarderGroup.Wait(); err != nil {
log.Debug("Forwarder error", "err", err)
}
log.Debug("all components terminated")
}
type NetworkInterface struct {
InterfaceId uint16
Addr net.Addr
Conn BatchConn
}
type packet struct {
// The source address. Will be set by the receiver
srcAddr *net.UDPAddr
// The address to where we are forwarding the packet.
// Will be set by the processing routine
dstAddr *net.UDPAddr
// The ingress on which this packet arrived. Will be
// set by the receiver
ingress uint16
rawPacket []byte
}
func (d *DataPlane) runReceiver(ni NetworkInterface) {
log.Debug("Initialize receiver for", "interface", ni.InterfaceId)
msgs := underlayconn.NewReadMessages(d.interfaceBatchSize)
newBufferCount := 0 // newly loaded buffers
unusedBufferCount := 0 // unused buffers from previous loop
metrics := d.forwardingMetrics[ni.InterfaceId]
currentPacketsFromPool := make([]*packet, d.interfaceBatchSize)
for d.running {
// collect packets
for newBufferCount+unusedBufferCount < d.interfaceBatchSize {
p := <-d.packetPool
msgs[newBufferCount].Buffers[0] = p.rawPacket[:bufSize]
currentPacketsFromPool[newBufferCount] = p
newBufferCount++
}
// read batch
numPkts, err := ni.Conn.ReadBatch(msgs[:newBufferCount+unusedBufferCount])
if err != nil {
log.Debug("Error while reading batch", "interfaceId", ni.InterfaceId, "err", err)
unusedBufferCount += newBufferCount
newBufferCount = 0
continue
}
for k, pkt := range msgs[:numPkts] {
metrics.InputPacketsTotal.Inc()
metrics.InputBytesTotal.Add(float64(pkt.N))
srcAddr := pkt.Addr.(*net.UDPAddr)
currPkt := currentPacketsFromPool[k]
currPkt.ingress = ni.InterfaceId
currPkt.dstAddr = nil
currPkt.srcAddr = &net.UDPAddr{
IP: srcAddr.IP,
Port: srcAddr.Port,
}
currPkt.rawPacket = currPkt.rawPacket[:pkt.N]
procId, err := d.computeProcId(currPkt.rawPacket)
if err != nil {
log.Debug("Error while computing procId", "err", err)
continue
}
select {
case d.procChannels[procId] <- currPkt:
// TODO(rohrerj) add metrics
default:
d.returnPacketToPool(currPkt)
metrics.DroppedPacketsTotal.Inc()
}
}
unusedBufferCount += newBufferCount - numPkts
newBufferCount = 0
}
}
func (d *DataPlane) computeProcId(data []byte) (uint32, error) {
srcHostAddrLen := ((data[9] & 0x3) + 1) * 4
dstHostAddrLen := ((data[9] >> 4 & 0x3) + 1) * 4
addrHdrLen := 16 + int(srcHostAddrLen+dstHostAddrLen)
if len(data) < slayers.CmnHdrLen+addrHdrLen {
return 0, serrors.New("Packet is too short")
}
if addrHdrLen > 48 {
return 0, serrors.New("Address header is invalid")
}
flowIDBuffer := [3]byte{}
copy(flowIDBuffer[0:3], data[1:4])
flowIDBuffer[0] &= 0xF // the left 4 bits don't belong to the flowID
hasher := fnv.New32a()
hasher.Write(d.randomValue)
hasher.Write(flowIDBuffer[:])
hasher.Write(data[slayers.CmnHdrLen : slayers.CmnHdrLen+addrHdrLen+1])
return hasher.Sum32() % d.numProcRoutines, nil
}
func (d *DataPlane) returnPacketToPool(pkt *packet) {
d.packetPool <- pkt
}
func (d *DataPlane) runProcessingRoutine(id int) {
log.Debug("Initialize processing routine with", "id", id)
c := d.procChannels[id]
processor := newPacketProcessor(d, 0)
var scmpErr scmpError
for d.running {
p, ok := <-c
if !ok {
continue
}
processor.ingressID = p.ingress
metrics := d.forwardingMetrics[p.ingress]
result, err := processor.processPkt(p.rawPacket, p.srcAddr)
egress := result.EgressID
isSCMP := false
switch {
case err == nil:
case errors.As(err, &scmpErr):
if !scmpErr.TypeCode.InfoMsg() {
log.Debug("SCMP", "err", scmpErr)
}
// SCMP go back the way they came.
egress = p.ingress
result.OutAddr = p.srcAddr
// SCMP does not use the same buffer as we provide.
// Because of that we have to copy it back to our buffer
if len(result.OutPkt) > bufSize {
log.Debug("Error while processing packet. result.OutPkt is too long",
"len", len(result.OutPkt))
d.returnPacketToPool(p)
continue
}
p.rawPacket = p.rawPacket[:len(result.OutPkt)]
copy(p.rawPacket, result.OutPkt)
result.OutPkt = p.rawPacket
isSCMP = true
default:
log.Debug("Error processing packet", "err", err)
metrics.DroppedPacketsTotal.Inc()
d.returnPacketToPool(p)
continue
}
if !isSCMP && result.OutConn == nil { // e.g. BFD case no message is forwarded
d.returnPacketToPool(p)
continue
}
fwCh, ok := d.forwardChannels[egress]
if !ok {
log.Debug("Error determining forwarder. Egress is invalid", "egress", egress)
metrics.DroppedPacketsTotal.Inc()
d.returnPacketToPool(p)
continue
}
p.rawPacket = result.OutPkt
if result.OutAddr != nil {
p.dstAddr = result.OutAddr
}
select {
case fwCh <- p:
// TODO(rohrerj) add metrics
default:
d.returnPacketToPool(p)
metrics.DroppedPacketsTotal.Inc()
}
}
}
func (d *DataPlane) runForwarder(ni NetworkInterface) {
log.Debug("Initialize forwarder for", "interface", ni.InterfaceId)
c := d.forwardChannels[ni.InterfaceId]
writeMsgs := make(underlayconn.Messages, d.interfaceBatchSize)
for i := range writeMsgs {
writeMsgs[i].Buffers = make([][]byte, 1)
}
metrics := d.forwardingMetrics[ni.InterfaceId]
currentPacketsToSend := make([]*packet, d.interfaceBatchSize)
// byteLen contains the length of all packets in the batch,
// also those that might not be sent correctly
byteLen := 0
prepareMsg := func(p *packet, i int) {
writeMsgs[i].Buffers[0] = p.rawPacket
writeMsgs[i].Addr = nil
if p.dstAddr != nil {
writeMsgs[i].Addr = p.dstAddr
}
currentPacketsToSend[i] = p
}
for d.running {
p, ok := <-c
if !ok {
continue
}
prepareMsg(p, 0)
byteLen = len(p.rawPacket)
availablePacket := int(math.Min(float64(len(c)), float64(d.interfaceBatchSize-1)) + 1)
for i := 1; i < availablePacket; i++ {
p, ok = <-c
if !ok {
availablePacket = i
break
}
prepareMsg(p, i)
byteLen += len(p.rawPacket)
}
k, err := ni.Conn.WriteBatch(writeMsgs[:availablePacket], syscall.MSG_DONTWAIT)
if err != nil {
var errno syscall.Errno
if !errors.As(err, &errno) ||
!(errno == syscall.EAGAIN || errno == syscall.EWOULDBLOCK) {
log.Debug("Error writing packet", "ni", ni, "err", err)
metrics.DroppedPacketsTotal.Add(float64(availablePacket))
}
// TODO(rohrerj) add metrics
} else {
metrics.DroppedPacketsTotal.Add(float64(availablePacket - k))
metrics.OutputPacketsTotal.Add(float64(k))
metrics.OutputBytesTotal.Add(float64(byteLen))
}
for j := 0; j < availablePacket; j++ {
d.returnPacketToPool(currentPacketsToSend[j])
}
}
}
// initMetrics initializes the metrics related to packet forwarding. The
// counters are already instantiated for all the relevant interfaces so this
// will not have to be repeated during packet forwarding.
func (d *DataPlane) initMetrics() {
d.forwardingMetrics = make(map[uint16]forwardingMetrics)
labels := interfaceToMetricLabels(0, d.localIA, d.neighborIAs)
d.forwardingMetrics[0] = initForwardingMetrics(d.Metrics, labels)
for id := range d.external {
if _, notOwned := d.internalNextHops[id]; notOwned {
continue
}
labels = interfaceToMetricLabels(id, d.localIA, d.neighborIAs)
d.forwardingMetrics[id] = initForwardingMetrics(d.Metrics, labels)
}
}
type processResult struct {
EgressID uint16
OutConn BatchConn
OutAddr *net.UDPAddr
OutPkt []byte
}
func newPacketProcessor(d *DataPlane, ingressID uint16) *scionPacketProcessor {
p := &scionPacketProcessor{
d: d,
ingressID: ingressID,
buffer: gopacket.NewSerializeBuffer(),
mac: d.macFactory(),
macBuffers: macBuffers{
scionInput: make([]byte, path.MACBufferSize),
epicInput: make([]byte, libepic.MACBufferSize),
drkeyInput: make([]byte, spao.MACBufferSize),
},
// TODO(JordiSubira): Replace this with a useful implementation.
drkeyProvider: &fakeProvider{},
optAuth: slayers.PacketAuthOption{EndToEndOption: new(slayers.EndToEndOption)},
validAuthBuf: make([]byte, 16),
}
p.scionLayer.RecyclePaths()
return p
}
func (p *scionPacketProcessor) reset() error {
p.rawPkt = nil
//p.scionLayer // cannot easily be reset
p.path = nil
p.hopField = path.HopField{}
p.infoField = path.InfoField{}
p.segmentChange = false
if err := p.buffer.Clear(); err != nil {
return serrors.WrapStr("Failed to clear buffer", err)
}
p.mac.Reset()
p.cachedMac = nil
// Reset hbh layer
p.hbhLayer = slayers.HopByHopExtnSkipper{}
// Reset e2e layer
p.e2eLayer = slayers.EndToEndExtnSkipper{}
return nil
}
func (p *scionPacketProcessor) processPkt(rawPkt []byte,
srcAddr *net.UDPAddr) (processResult, error) {
if err := p.reset(); err != nil {
return processResult{}, err
}
p.rawPkt = rawPkt
p.srcAddr = srcAddr
// parse SCION header and skip extensions;
var err error
p.lastLayer, err = decodeLayers(p.rawPkt, &p.scionLayer, &p.hbhLayer, &p.e2eLayer)
if err != nil {
return processResult{}, err
}
pld := p.lastLayer.LayerPayload()
pathType := p.scionLayer.PathType
switch pathType {
case empty.PathType:
if p.lastLayer.NextLayerType() == layers.LayerTypeBFD {
return processResult{}, p.processIntraBFD(pld)
}
return processResult{}, serrors.WithCtx(unsupportedPathTypeNextHeader,
"type", pathType, "header", nextHdr(p.lastLayer))
case onehop.PathType:
if p.lastLayer.NextLayerType() == layers.LayerTypeBFD {
ohp, ok := p.scionLayer.Path.(*onehop.Path)
if !ok {
return processResult{}, malformedPath
}
return processResult{}, p.processInterBFD(ohp, pld)
}
return p.processOHP()
case scion.PathType:
return p.processSCION()
case epic.PathType:
return p.processEPIC()
default:
return processResult{}, serrors.WithCtx(unsupportedPathType, "type", pathType)
}
}
func (p *scionPacketProcessor) processInterBFD(oh *onehop.Path, data []byte) error {
if len(p.d.bfdSessions) == 0 {
return noBFDSessionConfigured
}
bfd := &p.bfdLayer
if err := bfd.DecodeFromBytes(data, gopacket.NilDecodeFeedback); err != nil {
return err
}
if v, ok := p.d.bfdSessions[p.ingressID]; ok {
v.ReceiveMessage(bfd)
return nil
}
return noBFDSessionFound
}
func (p *scionPacketProcessor) processIntraBFD(data []byte) error {
if len(p.d.bfdSessions) == 0 {
return noBFDSessionConfigured
}
bfd := &p.bfdLayer
if err := bfd.DecodeFromBytes(data, gopacket.NilDecodeFeedback); err != nil {
return err
}
ifID := uint16(0)
for k, v := range p.d.internalNextHops {
if bytes.Equal(v.IP, p.srcAddr.IP) && v.Port == p.srcAddr.Port {
ifID = k
break
}
}
if v, ok := p.d.bfdSessions[ifID]; ok {
v.ReceiveMessage(bfd)
return nil
}
return noBFDSessionFound
}
func (p *scionPacketProcessor) processSCION() (processResult, error) {
var ok bool
p.path, ok = p.scionLayer.Path.(*scion.Raw)
if !ok {
// TODO(lukedirtwalker) parameter problem invalid path?
return processResult{}, malformedPath
}
return p.process()
}
func (p *scionPacketProcessor) processEPIC() (processResult, error) {
epicPath, ok := p.scionLayer.Path.(*epic.Path)
if !ok {
return processResult{}, malformedPath
}
p.path = epicPath.ScionPath
if p.path == nil {
return processResult{}, malformedPath
}
isPenultimate := p.path.IsPenultimateHop()
isLast := p.path.IsLastHop()
result, err := p.process()
if err != nil {
return result, err
}
if isPenultimate || isLast {
firstInfo, err := p.path.GetInfoField(0)
if err != nil {
return processResult{}, err
}
timestamp := time.Unix(int64(firstInfo.Timestamp), 0)