-
Notifications
You must be signed in to change notification settings - Fork 162
/
dataplane.go
2439 lines (2218 loc) · 72.7 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"
"math/big"
"net"
"net/netip"
"sync"
"time"
"github.com/google/gopacket"
"github.com/google/gopacket/layers"
"github.com/prometheus/client_golang/prometheus"
"golang.org/x/net/ipv4"
"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/processmetrics"
"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/drkey/drkeyutil"
"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).
type DataPlane struct {
interfaces map[uint16]BatchConn
external map[uint16]BatchConn
linkTypes map[uint16]topology.LinkType
neighborIAs map[uint16]addr.IA
peerInterfaces map[uint16]uint16
internal BatchConn
internalIP netip.Addr
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]interfaceMetrics
ExperimentalSCMPAuthentication bool
// The pool that stores all the packet buffers as described in the design document. See
// https://github.com/scionproto/scion/blob/master/doc/dev/design/BorderRouter.rst
packetPool chan []byte
}
var (
alreadySet = errors.New("already set")
invalidSrcIA = errors.New("invalid source ISD-AS")
invalidDstIA = errors.New("invalid destination ISD-AS")
invalidSrcAddrForTransit = errors.New("invalid source address for transit pkt")
cannotRoute = errors.New("cannot route, dropping pkt")
emptyValue = errors.New("empty value")
malformedPath = errors.New("malformed path content")
modifyExisting = errors.New("modifying a running dataplane is not allowed")
noSVCBackend = errors.New("cannot find internal IP for the SVC")
unsupportedPathType = errors.New("unsupported path type")
unsupportedPathTypeNextHeader = errors.New("unsupported combination")
noBFDSessionFound = errors.New("no BFD session was found")
noBFDSessionConfigured = errors.New("no BFD sessions have been configured")
errPeeringEmptySeg0 = errors.New("zero-length segment[0] in peering path")
errPeeringEmptySeg1 = errors.New("zero-length segment[1] in peering path")
errPeeringNonemptySeg2 = errors.New("non-zero-length segment[2] in peering path")
errShortPacket = errors.New("Packet is too short")
errBFDSessionDown = errors.New("bfd session down")
expiredHop = errors.New("expired hop")
ingressInterfaceInvalid = errors.New("ingress interface invalid")
macVerificationFailed = errors.New("MAC verification failed")
badPacketSize = errors.New("bad packet size")
slowPathRequired = errors.New("slow-path required")
// zeroBuffer will be used to reset the Authenticator option in the
// scionPacketProcessor.OptAuth
zeroBuffer = make([]byte, 16)
)
type drkeyProvider interface {
GetASHostKey(validTime time.Time, dstIA addr.IA, dstAddr addr.Host) (drkey.ASHostKey, error)
GetKeyWithinAcceptanceWindow(
validTime time.Time,
timestamp uint64,
dstIA addr.IA,
dstAddr addr.Host,
) (drkey.ASHostKey, 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 netip.Addr) error {
d.mtx.Lock()
defer d.mtx.Unlock()
if d.running {
return modifyExisting
}
if conn == nil {
return emptyValue
}
if d.internal != nil {
return alreadySet
}
if d.interfaces == nil {
d.interfaces = make(map[uint16]BatchConn)
}
d.interfaces[0] = conn
d.internal = conn
d.internalIP = 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,
src, dst control.LinkEnd, cfg control.BFD) error {
d.mtx.Lock()
defer d.mtx.Unlock()
if d.running {
return modifyExisting
}
if conn == nil || src.Addr == nil || dst.Addr == nil {
return emptyValue
}
err := d.addExternalInterfaceBFD(ifID, conn, src, dst, cfg)
if err != nil {
return serrors.WrapStr("adding external BFD", err, "if_id", ifID)
}
if d.external == nil {
d.external = make(map[uint16]BatchConn)
}
if d.interfaces == nil {
d.interfaces = make(map[uint16]BatchConn)
}
if _, exists := d.external[ifID]; exists {
return serrors.WithCtx(alreadySet, "ifID", ifID)
}
d.interfaces[ifID] = conn
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
}
// AddRemotePeer adds the remote peering interface ID for local
// interface ID. If the link type for the given ID is already set to
// a different type, this method will return an error. This can only
// be called on a not yet running dataplane.
func (d *DataPlane) AddRemotePeer(local, remote uint16) error {
if t, ok := d.linkTypes[local]; ok && t != topology.Peer {
return serrors.WithCtx(unsupportedPathType, "type", t)
}
if _, exists := d.peerInterfaces[local]; exists {
return serrors.WithCtx(alreadySet, "local_interface", local)
}
if d.peerInterfaces == nil {
d.peerInterfaces = make(map[uint16]uint16)
}
d.peerInterfaces[local] = remote
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 {
if *cfg.Disable {
return nil
}
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, err := newBFDSend(conn, src.IA, dst.IA, src.Addr, dst.Addr, ifID, d.macFactory())
if err != nil {
return err
}
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 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.SVC, 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 := serviceLabels(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.SVC, 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 := serviceLabels(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, 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 || src == nil {
return emptyValue
}
err := d.addNextHopBFD(ifID, src, dst, cfg, sibling)
if err != nil {
return serrors.WrapStr("adding next hop BFD", err, "if_id", ifID)
}
if d.internalNextHops == nil {
d.internalNextHops = make(map[uint16]*net.UDPAddr)
}
if _, exists := d.internalNextHops[ifID]; exists {
return serrors.WithCtx(alreadySet, "ifID", ifID)
}
d.internalNextHops[ifID] = dst
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 {
if *cfg.Disable {
return nil
}
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, err := newBFDSend(d.internal, d.localIA, d.localIA, src, dst, 0, d.macFactory())
if err != nil {
return err
}
return d.addBFDController(ifID, s, cfg, m)
}
func max(a int, b int) int {
if a > b {
return a
}
return b
}
type RunConfig struct {
NumProcessors int
NumSlowPathProcessors int
BatchSize int
}
func (d *DataPlane) Run(ctx context.Context, cfg *RunConfig) error {
d.mtx.Lock()
d.running = true
d.initMetrics()
processorQueueSize := max(
len(d.interfaces)*cfg.BatchSize/cfg.NumProcessors,
cfg.BatchSize)
d.initPacketPool(cfg, processorQueueSize)
procQs, fwQs, slowQs := initQueues(cfg, d.interfaces, processorQueueSize)
for ifID, conn := range d.interfaces {
go func(ifID uint16, conn BatchConn) {
defer log.HandlePanic()
d.runReceiver(ifID, conn, cfg, procQs)
}(ifID, conn)
go func(ifID uint16, conn BatchConn) {
defer log.HandlePanic()
d.runForwarder(ifID, conn, cfg, fwQs[ifID])
}(ifID, conn)
}
for i := 0; i < cfg.NumProcessors; i++ {
go func(i int) {
defer log.HandlePanic()
d.runProcessor(i, procQs[i], fwQs, slowQs[i%cfg.NumSlowPathProcessors])
}(i)
}
for i := 0; i < cfg.NumSlowPathProcessors; i++ {
go func(i int) {
defer log.HandlePanic()
d.runSlowPathProcessor(i, slowQs[i], fwQs)
}(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)
}
d.mtx.Unlock()
<-ctx.Done()
return nil
}
// initializePacketPool calculates the size of the packet pool based on the
// current dataplane settings and allocates all the buffers
func (d *DataPlane) initPacketPool(cfg *RunConfig, processorQueueSize int) {
poolSize := len(d.interfaces)*cfg.BatchSize +
(cfg.NumProcessors+cfg.NumSlowPathProcessors)*(processorQueueSize+1) +
len(d.interfaces)*(2*cfg.BatchSize)
log.Debug("Initialize packet pool of size", "poolSize", poolSize)
d.packetPool = make(chan []byte, poolSize)
for i := 0; i < poolSize; i++ {
d.packetPool <- make([]byte, bufSize)
}
}
// initializes the processing routines and forwarders queues
func initQueues(cfg *RunConfig, interfaces map[uint16]BatchConn,
processorQueueSize int) ([]chan packet, map[uint16]chan packet,
[]chan slowPacket) {
procQs := make([]chan packet, cfg.NumProcessors)
for i := 0; i < cfg.NumProcessors; i++ {
procQs[i] = make(chan packet, processorQueueSize)
}
slowQs := make([]chan slowPacket, cfg.NumSlowPathProcessors)
for i := 0; i < cfg.NumSlowPathProcessors; i++ {
slowQs[i] = make(chan slowPacket, processorQueueSize)
}
fwQs := make(map[uint16]chan packet)
for ifID := range interfaces {
fwQs[ifID] = make(chan packet, cfg.BatchSize)
}
return procQs, fwQs, slowQs
}
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. This is
// set by the receiver.
ingress uint16
// The type of traffic. This is used for metrics at the forwarding stage, but is most
// economically determined at the processing stage. So transport it here.
trafficType trafficType
// The goods
rawPacket []byte
}
type slowPacket struct {
packet
slowPathRequest slowPathRequest
}
func (d *DataPlane) runReceiver(ifID uint16, conn BatchConn, cfg *RunConfig,
procQs []chan packet) {
log.Debug("Run receiver for", "interface", ifID)
msgs := underlayconn.NewReadMessages(cfg.BatchSize)
numReusable := 0 // unused buffers from previous loop
metrics := d.forwardingMetrics[ifID] // If receiver exists, fw metrics exist too.
enqueueForProcessing := func(pkt ipv4.Message) {
srcAddr := pkt.Addr.(*net.UDPAddr)
size := pkt.N
sc := classOfSize(size)
metrics[sc].InputPacketsTotal.Inc()
metrics[sc].InputBytesTotal.Add(float64(size))
procID, err := computeProcID(pkt.Buffers[0], cfg.NumProcessors, ifID)
if err != nil {
log.Debug("Error while computing procID", "err", err)
d.returnPacketToPool(pkt.Buffers[0])
metrics[sc].DroppedPacketsInvalid.Inc()
return
}
outPkt := packet{
rawPacket: pkt.Buffers[0][:pkt.N],
ingress: ifID,
srcAddr: srcAddr,
}
select {
case procQs[procID] <- outPkt:
default:
d.returnPacketToPool(pkt.Buffers[0])
metrics[sc].DroppedPacketsBusyProcessor.Inc()
}
}
for d.running {
// collect packets
for i := 0; i < cfg.BatchSize-numReusable; i++ {
p := <-d.packetPool
msgs[i].Buffers[0] = p
}
// read batch
numPkts, err := conn.ReadBatch(msgs)
numReusable = len(msgs) - numPkts
if err != nil {
log.Debug("Error while reading batch", "interfaceID", ifID, "err", err)
continue
}
for _, pkt := range msgs[:numPkts] {
enqueueForProcessing(pkt)
}
}
}
// The hasher API is very expensive. Make our own cheap version.
const (
prime32 = 16777619
offset32 = 2166136261
)
func computeProcID(data []byte, numProcRoutines int, base uint16) (uint32, error) {
if len(data) < slayers.CmnHdrLen {
return 0, errShortPacket
}
dstHostAddrLen := slayers.AddrType(data[9] >> 4 & 0xf).Length()
srcHostAddrLen := slayers.AddrType(data[9] & 0xf).Length()
addrHdrLen := 2*addr.IABytes + srcHostAddrLen + dstHostAddrLen
if len(data) < slayers.CmnHdrLen+addrHdrLen {
return 0, errShortPacket
}
var s uint32 = offset32
// Inject the base number (i.e. ifID)
s ^= uint32(base & 0xff)
s *= prime32
s ^= uint32(base >> 8)
s *= prime32
// inject the flowID
s ^= uint32(data[1] & 0xF) // The left 4 bits aren't part of the flowID.
s *= prime32
for _, c := range data[2:4] {
s ^= uint32(c)
s *= prime32
}
// Inject the src/dst addresses
for _, c := range data[slayers.CmnHdrLen : slayers.CmnHdrLen+addrHdrLen] {
s ^= uint32(c)
s *= prime32
}
return s % uint32(numProcRoutines), nil
}
func (d *DataPlane) returnPacketToPool(pkt []byte) {
d.packetPool <- pkt[:cap(pkt)]
}
func (d *DataPlane) runProcessor(id int, q <-chan packet,
fwQs map[uint16]chan packet, slowQ chan<- slowPacket) {
log.Debug("Initialize processor with", "id", id)
processor := newPacketProcessor(d)
for d.running {
p, ok := <-q
if !ok {
continue
}
result, err := processor.processPkt(p.rawPacket, p.srcAddr, p.ingress)
sc := classOfSize(len(p.rawPacket))
metrics := d.forwardingMetrics[p.ingress][sc]
metrics.ProcessedPackets.Inc()
egress := result.EgressID
switch {
case err == nil:
case errors.Is(err, slowPathRequired):
select {
case slowQ <- slowPacket{p, result.SlowPathRequest}:
default:
metrics.DroppedPacketsBusySlowPath.Inc()
d.returnPacketToPool(p.rawPacket)
}
continue
default:
log.Debug("Error processing packet", "err", err)
metrics.DroppedPacketsInvalid.Inc()
d.returnPacketToPool(p.rawPacket)
continue
}
if result.OutPkt == nil { // e.g. BFD case no message is forwarded
d.returnPacketToPool(p.rawPacket)
continue
}
fwCh, ok := fwQs[egress]
if !ok {
log.Debug("Error determining forwarder. Egress is invalid", "egress", egress)
metrics.DroppedPacketsInvalid.Inc()
d.returnPacketToPool(p.rawPacket)
continue
}
p.rawPacket = result.OutPkt
p.dstAddr = result.OutAddr
p.trafficType = result.TrafficType
select {
case fwCh <- p:
default:
d.returnPacketToPool(p.rawPacket)
metrics.DroppedPacketsBusyForwarder.Inc()
}
}
}
func (d *DataPlane) runSlowPathProcessor(id int, q <-chan slowPacket,
fwQs map[uint16]chan packet) {
log.Debug("Initialize slow-path processor with", "id", id)
processor := newSlowPathProcessor(d)
for d.running {
p, ok := <-q
if !ok {
continue
}
res, err := processor.processPacket(p)
sc := classOfSize(len(p.rawPacket))
metrics := d.forwardingMetrics[p.packet.ingress][sc]
if err != nil {
log.Debug("Error processing packet", "err", err)
metrics.DroppedPacketsInvalid.Inc()
d.returnPacketToPool(p.packet.rawPacket)
continue
}
p.packet.dstAddr = res.OutAddr
p.packet.rawPacket = res.OutPkt
fwCh, ok := fwQs[res.EgressID]
if !ok {
log.Debug("Error determining forwarder. Egress is invalid", "egress", res.EgressID)
d.returnPacketToPool(p.packet.rawPacket)
continue
}
select {
case fwCh <- p.packet:
default:
d.returnPacketToPool(p.packet.rawPacket)
}
}
}
func newSlowPathProcessor(d *DataPlane) *slowPathPacketProcessor {
p := &slowPathPacketProcessor{
d: d,
buffer: gopacket.NewSerializeBuffer(),
macInputBuffer: make([]byte, spao.MACBufferSize),
drkeyProvider: &drkeyutil.FakeProvider{
EpochDuration: drkeyutil.LoadEpochDuration(),
AcceptanceWindow: drkeyutil.LoadAcceptanceWindow(),
},
optAuth: slayers.PacketAuthOption{EndToEndOption: new(slayers.EndToEndOption)},
validAuthBuf: make([]byte, 16),
}
p.scionLayer.RecyclePaths()
return p
}
type slowPathPacketProcessor struct {
d *DataPlane
ingressID uint16
rawPkt []byte
srcAddr *net.UDPAddr
buffer gopacket.SerializeBuffer
scionLayer slayers.SCION
hbhLayer slayers.HopByHopExtnSkipper
e2eLayer slayers.EndToEndExtnSkipper
lastLayer gopacket.DecodingLayer
path *scion.Raw
// macInputBuffer avoid allocating memory during processing.
macInputBuffer []byte
// optAuth is a reusable Packet Authenticator Option
optAuth slayers.PacketAuthOption
// validAuthBuf is a reusable buffer for the authentication tag
// to be used in the hasValidAuth() method.
validAuthBuf []byte
// DRKey key derivation for SCMP authentication
drkeyProvider drkeyProvider
}
func (p *slowPathPacketProcessor) reset() {
if err := p.buffer.Clear(); err != nil {
log.Debug("Error while clearing buffer", "err", err)
}
p.path = nil
p.hbhLayer = slayers.HopByHopExtnSkipper{}
p.e2eLayer = slayers.EndToEndExtnSkipper{}
}
// processResults carries what could be determined while processing
// a packet. In most cases of error, all fields are left to their
// zero value.
type processResult struct {
EgressID uint16
OutAddr *net.UDPAddr
OutPkt []byte
SlowPathRequest slowPathRequest
TrafficType trafficType
}
func (p *slowPathPacketProcessor) processPacket(pkt slowPacket) (processResult, error) {
var err error
p.reset()
p.ingressID = pkt.ingress
p.srcAddr = pkt.srcAddr
p.rawPkt = pkt.rawPacket
p.lastLayer, err = decodeLayers(pkt.rawPacket, &p.scionLayer, &p.hbhLayer, &p.e2eLayer)
if err != nil {
return processResult{}, err
}
pathType := p.scionLayer.PathType
switch pathType {
case scion.PathType:
var ok bool
p.path, ok = p.scionLayer.Path.(*scion.Raw)
if !ok {
return processResult{}, malformedPath
}
case epic.PathType:
epicPath, ok := p.scionLayer.Path.(*epic.Path)
if !ok {
return processResult{}, malformedPath
}
p.path = epicPath.ScionPath
if p.path == nil {
return processResult{}, malformedPath
}
default:
//unsupported path type
return processResult{}, serrors.New("Path type not supported for slow-path",
"type", pathType)
}
switch pkt.slowPathRequest.typ {
case slowPathSCMP: //SCMP
s := pkt.slowPathRequest
var layer gopacket.SerializableLayer
switch s.scmpType {
case slayers.SCMPTypeParameterProblem:
layer = &slayers.SCMPParameterProblem{Pointer: s.pointer}
case slayers.SCMPTypeDestinationUnreachable:
layer = &slayers.SCMPDestinationUnreachable{}
case slayers.SCMPTypeExternalInterfaceDown:
layer = &slayers.SCMPExternalInterfaceDown{IA: s.ia,
IfID: uint64(s.interfaceId)}
case slayers.SCMPTypeInternalConnectivityDown:
layer = &slayers.SCMPInternalConnectivityDown{IA: s.ia,
Ingress: uint64(s.ingressId), Egress: uint64(s.egressId)}
}
return p.packSCMP(s.scmpType, s.code, layer, s.cause)
case slowPathRouterAlert: //Traceroute
return p.handleSCMPTraceRouteRequest(pkt.slowPathRequest.interfaceId)
default:
panic("Unsupported slow-path type")
}
}
func updateOutputMetrics(metrics interfaceMetrics, packets []packet) {
// We need to collect stats by traffic type and size class.
// Try to reduce the metrics lookup penalty by using some
// simpler staging data structure.
writtenPkts := [ttMax][maxSizeClass]int{}
writtenBytes := [ttMax][maxSizeClass]int{}
for _, p := range packets {
s := len(p.rawPacket)
sc := classOfSize(s)
tt := p.trafficType
writtenPkts[tt][sc]++
writtenBytes[tt][sc] += s
}
for t := ttOther; t < ttMax; t++ {
for sc := minSizeClass; sc < maxSizeClass; sc++ {
if writtenPkts[t][sc] > 0 {
metrics[sc].Output[t].OutputPacketsTotal.Add(float64(writtenPkts[t][sc]))
metrics[sc].Output[t].OutputBytesTotal.Add(float64(writtenBytes[t][sc]))
}
}
}
}
func (d *DataPlane) runForwarder(ifID uint16, conn BatchConn, cfg *RunConfig, c <-chan packet) {
log.Debug("Initialize forwarder for", "interface", ifID)
// We use this somewhat like a ring buffer.
pkts := make([]packet, cfg.BatchSize)
// We use this as a temporary buffer, but allocate it just once
// to save on garbage handling.
msgs := make(underlayconn.Messages, cfg.BatchSize)
for i := range msgs {
msgs[i].Buffers = make([][]byte, 1)
}
metrics := d.forwardingMetrics[ifID]
toWrite := 0
for d.running {
toWrite += readUpTo(c, cfg.BatchSize-toWrite, toWrite == 0, pkts[toWrite:])
// Turn the packets into underlay messages that WriteBatch can send.
for i, p := range pkts[:toWrite] {
msgs[i].Buffers[0] = p.rawPacket
msgs[i].Addr = nil
if p.dstAddr != nil {
msgs[i].Addr = p.dstAddr
}
}
written, _ := conn.WriteBatch(msgs[:toWrite], 0)
if written < 0 {
// WriteBatch returns -1 on error, we just consider this as
// 0 packets written
written = 0
}
updateOutputMetrics(metrics, pkts[:written])
for _, p := range pkts[:written] {
d.returnPacketToPool(p.rawPacket)
}
if written != toWrite {
// Only one is dropped at this time. We'll retry the rest.
sc := classOfSize(len(pkts[written].rawPacket))
metrics[sc].DroppedPacketsInvalid.Inc()
d.returnPacketToPool(pkts[written].rawPacket)
toWrite -= (written + 1)
// Shift the leftovers to the head of the buffers.
for i := 0; i < toWrite; i++ {
pkts[i] = pkts[i+written+1]
}
} else {
toWrite = 0
}
}
}
func readUpTo(c <-chan packet, n int, needsBlocking bool, pkts []packet) int {
i := 0
if needsBlocking {
p, ok := <-c
if !ok {
return i
}
pkts[i] = p