-
Notifications
You must be signed in to change notification settings - Fork 163
/
Copy pathdataplane.go
2789 lines (2524 loc) · 87.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
// Copyright 2024 SCION Association
//
// 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 (
"context"
"crypto/rand"
"crypto/subtle"
"encoding/binary"
"errors"
"fmt"
"hash"
"math/big"
"net"
"net/netip"
"sync"
"sync/atomic"
"time"
"unsafe"
"github.com/google/gopacket"
"github.com/google/gopacket/layers"
"github.com/prometheus/client_golang/prometheus"
"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
// Needed to compute required padding
ptrSize = unsafe.Sizeof(&struct{ int }{})
is32bit = 1 - (ptrSize-4)/4
)
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)
WriteBatch(msgs underlayconn.Messages, flags int) (int, error)
Close() error
}
// underlay is a pointer to our underlay provider.
//
// incremental refactoring: this allows for a single underlay. In the future, each link could be
// via a different underlay. That would have to be supported by the configuration code and there
// would likely be a registry of underlays. For now, That's the whole registry.
var newUnderlay func() UnderlayProvider
func AddUnderlay(newProvider func() UnderlayProvider) {
newUnderlay = newProvider
}
type disposition int
const (
pDiscard disposition = iota // Zero value, default.
pForward
pSlowPath
pDone
)
// Packet aggregates buffers and ancillary metadata related to one packet.
// That is everything we need to pass-around while processing a packet. The motivation is to save on
// copy (pass everything via one reference) AND garbage collection (reuse everything).
// The buffer is allocated in a separate location (but still reused) to keep the packet structures
// tightly packed (might not matter, though).
// Golang gives precious little guarantees about alignment and padding. We do it ourselves in such
// a way that Go has no sane reason to add any padding. Everything is 8 byte aligned (on 64 bit
// arch) until Slowpath request which is 6 bytes long. The rest is in decreasing order of size and
// size-aligned. We want to fit neatly into cache lines, so we need to fit in 64 bytes. The padding
// required to occupy exactly 64 bytes depends on the architecture.
type Packet struct {
// The useful part of the raw packet at a point in time (i.e. a slice of the full buffer).
// It can be any portion of the full buffer; not necessarily the start.
rawPacket []byte
// The entire packet buffer. We don't need it as a slice; we know its size.
buffer *[bufSize]byte
// The source address. Will be set by the receiver from smsg.Addr. We could update it in-place,
// but the IP address bytes in it are allocated by readbatch, so if we copy into a recyclable
// location, it's the original we throw away. No gain (may be a tiny bit?).
srcAddr *net.UDPAddr
// The address to where we are forwarding the packet.
// Will be set by the processing routine; it is updated in-place.
DstAddr *net.UDPAddr
// Additional metadata in case the packet is put on the slow path. Updated in-place.
slowPathRequest slowPathRequest
// The ingress on which this packet arrived. This is set by the receiver.
ingress uint16
// The egress on which this packet must leave. This is set by the processing routine.
egress uint16
// The type of traffic. This is used for metrics at the forwarding stage, but is most
// economically determined at the processing stage. So store it here. It's 2 bytes long.
trafficType trafficType
// Pad to 64 bytes. For 64bit arch, add 12 bytes. For 32bit arch, add 32 bytes.
_ [4 + is32bit*24]byte
}
// Keep this 6 bytes long. See comment for packet.
type slowPathRequest struct {
pointer uint16
typ slowPathType
scmpType slayers.SCMPType
code slayers.SCMPCode
_ uint8
}
// Make sure that the packet structure has the size we expect.
const _ uintptr = 64 - unsafe.Sizeof(Packet{}) // assert 64 >= sizeof(Packet)
const _ uintptr = unsafe.Sizeof(Packet{}) - 64 // assert sizeof(Packet) >= 64
// initPacket configures the given blank packet (and returns it, for convenience).
func (p *Packet) init(buffer *[bufSize]byte) *Packet {
p.buffer = buffer
p.rawPacket = p.buffer[:]
p.DstAddr = &net.UDPAddr{IP: make(net.IP, net.IPv6len)}
return p
}
// reset() makes the packet ready to receive a new underlay message.
// A cleared dstAddr is represented with a zero-length IP so we keep reusing the IP storage bytes.
func (p *Packet) reset() {
p.DstAddr.IP = p.DstAddr.IP[0:0] // We're keeping the object, just blank it.
*p = Packet{
buffer: p.buffer, // keep the buffer
rawPacket: p.buffer[:], // restore the full packet capacity
DstAddr: p.DstAddr, // keep the dstAddr and so the IP slice and bytes
}
// Everything else is reset to zero value.
}
// 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 {
underlay UnderlayProvider
interfaces map[uint16]Link
linkTypes map[uint16]topology.LinkType
neighborIAs map[uint16]addr.IA
internalIP netip.Addr
svc *services
macFactory func() hash.Hash
localIA addr.IA
mtx sync.Mutex
running atomic.Bool
Metrics *Metrics
forwardingMetrics map[uint16]interfaceMetrics
dispatchedPortStart uint16
dispatchedPortEnd uint16
ExperimentalSCMPAuthentication bool
RunConfig RunConfig
// 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
// To avoid garbage collection, most the meta-data that is produced during the processing of a
// packet is kept in a data structure (packet struct) that is pooled and recycled along with
// corresponding packet buffer. The packet struct refers permanently to the packet buffer. The
// packet structure is fetched from the pool passed-around through the various channels and
// returned to the pool. To reduce the cost of copying, the packet structure is passed by
// reference.
packetPool chan *Packet
}
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")
invalidDstAddr = errors.New("invalid destination address")
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")
unsupportedV4MappedV6Address = errors.New("unsupported v4mapped IP v6 address")
unsupportedUnspecifiedAddress = errors.New("unsupported unspecified address")
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")
// notImplemented = errors.New("Not Yet Implemented")
// 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)
}
// setRunning() Configures the running state of the data plane to true. setRunning() is called once
// the dataplane is finished initializing and is ready to process packets.
func (d *DataPlane) setRunning() {
d.running.Store(true)
}
// setStopping() Configures the running state of the data plane to false. This should not be called
// during the dataplane initialization. Calling this before initialization starts has no effect.
func (d *DataPlane) setStopping() {
d.running.Store(false)
}
// IsRunning() Indicates the running state of the data plane. If true, the dataplane is initialized
// and ready to process or already processing packets. In this case some configuration changes are
// not permitted. If false, the data plane is not ready to process packets yet, or is shutting
// down.
func (d *DataPlane) IsRunning() bool {
return d.running.Load()
}
// Shutdown() causes the dataplane to stop accepting packets and then terminate. Note that
// in that case the router is committed to shutting down. There is no mechanism to restart it.
func (d *DataPlane) Shutdown() {
d.mtx.Lock() // make sure we're nor racing with initialization.
defer d.mtx.Unlock()
d.setStopping()
}
// 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.IsRunning() {
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.IsRunning() {
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
}
func (d *DataPlane) SetPortRange(start, end uint16) {
d.dispatchedPortStart = start
d.dispatchedPortEnd = end
}
// 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.IsRunning() {
return modifyExisting
}
if conn == nil {
return emptyValue
}
if d.underlay == nil {
d.underlay = newUnderlay()
}
if d.interfaces == nil {
d.interfaces = make(map[uint16]Link)
} else if d.interfaces[0] != nil {
return alreadySet
}
l := d.underlay.NewInternalLink(conn, d.RunConfig.BatchSize)
d.interfaces[0] = l
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.IsRunning() {
return modifyExisting
}
if conn == nil || !src.Addr.IsValid() || !dst.Addr.IsValid() {
return emptyValue
}
if d.underlay == nil {
d.underlay = newUnderlay()
}
bfd, err := d.addExternalInterfaceBFD(ifID, src, dst, cfg)
if err != nil {
return serrors.Wrap("adding external BFD", err, "if_id", ifID)
}
if d.interfaces == nil {
d.interfaces = make(map[uint16]Link)
}
if _, exists := d.interfaces[ifID]; exists {
return serrors.JoinNoStack(alreadySet, nil, "ifID", ifID)
}
lk := d.underlay.NewExternalLink(conn, d.RunConfig.BatchSize, bfd, dst.Addr, ifID)
d.interfaces[ifID] = lk
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 not yet running dataplane.
func (d *DataPlane) AddNeighborIA(ifID uint16, remote addr.IA) error {
d.mtx.Lock()
defer d.mtx.Unlock()
if d.IsRunning() {
return modifyExisting
}
if remote.IsZero() {
return emptyValue
}
if _, exists := d.neighborIAs[ifID]; exists {
return serrors.JoinNoStack(alreadySet, nil, "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 {
d.mtx.Lock()
defer d.mtx.Unlock()
if d.IsRunning() {
return modifyExisting
}
if _, exists := d.linkTypes[ifID]; exists {
return serrors.JoinNoStack(alreadySet, nil, "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,
src, dst control.LinkEnd, cfg control.BFD) (BfdSession, error) {
if *cfg.Disable {
return nil, 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(d, src.IA, dst.IA, src.Addr, dst.Addr, ifID, d.macFactory())
if err != nil {
return nil, 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(ifID uint16) control.InterfaceState {
if l := d.interfaces[ifID]; l != nil && !l.IsUp() {
return control.InterfaceDown
}
return control.InterfaceUp
}
func (d *DataPlane) addBFDController(ifID uint16, s bfd.Sender, cfg control.BFD,
metrics bfd.Metrics) (BfdSession, error) {
// Generate random discriminator. It can't be zero.
discInt, err := rand.Int(rand.Reader, big.NewInt(0xfffffffe))
if err != nil {
return nil, err
}
disc := layers.BFDDiscriminator(uint32(discInt.Uint64()) + 1)
return &bfd.Session{
Sender: s,
DetectMult: layers.BFDDetectMultiplier(cfg.DetectMult),
DesiredMinTxInterval: cfg.DesiredMinTxInterval,
RequiredMinRxInterval: cfg.RequiredMinRxInterval,
LocalDiscriminator: disc,
ReceiveQueueSize: 10,
Metrics: metrics,
}, 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 netip.AddrPort) error {
d.mtx.Lock()
defer d.mtx.Unlock()
if !a.IsValid() {
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 netip.AddrPort) error {
d.mtx.Lock()
defer d.mtx.Unlock()
if !a.IsValid() {
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 netip.AddrPort, cfg control.BFD,
sibling string) error {
d.mtx.Lock()
defer d.mtx.Unlock()
if d.IsRunning() {
return modifyExisting
}
if !dst.IsValid() || !src.IsValid() {
return emptyValue
}
if d.underlay == nil {
d.underlay = newUnderlay()
}
bfd, err := d.addNextHopBFD(ifID, src, dst, cfg, sibling)
if err != nil {
return serrors.Wrap("adding next hop BFD", err, "if_id", ifID)
}
if d.interfaces == nil {
d.interfaces = make(map[uint16]Link)
}
if _, exists := d.interfaces[ifID]; exists {
return serrors.JoinNoStack(alreadySet, nil, "ifID", ifID)
}
sib := d.underlay.NewSiblingLink(d.RunConfig.BatchSize, bfd, dst)
d.interfaces[ifID] = sib
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 netip.AddrPort, cfg control.BFD,
sibling string) (BfdSession, error) {
if *cfg.Disable {
return nil, 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, d.localIA, d.localIA, src, dst, 0, d.macFactory())
if err != nil {
return nil, 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) error {
d.mtx.Lock()
d.initMetrics()
// incremental refactoring: we leave all the ingest work here for now, so we get the set of
// connections from the underlay.
underlayConnections := d.underlay.GetConnections()
processorQueueSize := max(
len(underlayConnections)*d.RunConfig.BatchSize/d.RunConfig.NumProcessors,
d.RunConfig.BatchSize)
d.initPacketPool(processorQueueSize)
procQs, slowQs := d.initQueues(processorQueueSize)
d.setRunning()
for _, c := range underlayConnections {
go func(c UnderlayConnection) {
defer log.HandlePanic()
d.runReceiver(c, procQs)
}(c)
go func(c UnderlayConnection) {
defer log.HandlePanic()
d.runForwarder(c)
}(c)
}
for i := 0; i < d.RunConfig.NumProcessors; i++ {
go func(i int) {
defer log.HandlePanic()
d.runProcessor(i, procQs[i], slowQs[i%d.RunConfig.NumSlowPathProcessors])
}(i)
}
for i := 0; i < d.RunConfig.NumSlowPathProcessors; i++ {
go func(i int) {
defer log.HandlePanic()
d.runSlowPathProcessor(i, slowQs[i])
}(i)
}
for a, l := range d.underlay.GetLinks() {
s := l.GetBfdSession()
if s == nil {
continue
}
go func(a netip.AddrPort) {
defer log.HandlePanic()
if err := s.Run(ctx); err != nil && err != bfd.AlreadyRunning {
log.Error("BFD session failed to start", "remote address", a, "err", err)
}
}(a)
}
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(processorQueueSize int) {
poolSize := len(d.interfaces)*d.RunConfig.BatchSize +
(d.RunConfig.NumProcessors+d.RunConfig.NumSlowPathProcessors)*(processorQueueSize+1) +
len(d.interfaces)*(2*d.RunConfig.BatchSize)
log.Debug("Initialize packet pool of size", "poolSize", poolSize)
d.packetPool = make(chan *Packet, poolSize)
pktBuffers := make([][bufSize]byte, poolSize)
pktStructs := make([]Packet, poolSize)
for i := 0; i < poolSize; i++ {
d.packetPool <- pktStructs[i].init(&pktBuffers[i])
}
}
// initializes the processing routines and queues
func (d *DataPlane) initQueues(processorQueueSize int) ([]chan *Packet, []chan *Packet) {
procQs := make([]chan *Packet, d.RunConfig.NumProcessors)
for i := 0; i < d.RunConfig.NumProcessors; i++ {
procQs[i] = make(chan *Packet, processorQueueSize)
}
slowQs := make([]chan *Packet, d.RunConfig.NumSlowPathProcessors)
for i := 0; i < d.RunConfig.NumSlowPathProcessors; i++ {
slowQs[i] = make(chan *Packet, processorQueueSize)
}
return procQs, slowQs
}
// runReceiver handles incoming traffic from the given connection.
//
// Incremental refactoring: we should not have direct knowledge of connections. Later we will move
// parts of this to the connection itself, so that we don't have to know.
func (d *DataPlane) runReceiver(u UnderlayConnection, procQs []chan *Packet) {
log.Debug("Run receiver", "connection", u.Name())
// Each receiver (therefore each input interface) has a unique random seed for the procID hash
// function.
hashSeed := fnv1aOffset32
randomBytes := make([]byte, 4)
if _, err := rand.Read(randomBytes); err != nil {
panic("Error while generating random value")
}
for _, c := range randomBytes {
hashSeed = hashFNV1a(hashSeed, c)
}
// A collection of socket messages, as the readBatch API expects them. We keep using the same
// collection, call after call; only replacing the buffer.
msgs := underlayconn.NewReadMessages(d.RunConfig.BatchSize)
// An array of corresponding packet references. Each corresponds to one msg.
// The packet owns the buffer that we set in the matching msg, plus the metadata that we'll add.
packets := make([]*Packet, d.RunConfig.BatchSize)
numReusable := 0 // unused buffers from previous loop
ifID := u.IfID()
metrics := d.forwardingMetrics[ifID] // If receiver exists, fw metrics exist too.
enqueueForProcessing := func(size int, srcAddr *net.UDPAddr, pkt *Packet) {
sc := classOfSize(size)
metrics[sc].InputPacketsTotal.Inc()
metrics[sc].InputBytesTotal.Add(float64(size))
procID, err := computeProcID(pkt.rawPacket, d.RunConfig.NumProcessors, hashSeed)
if err != nil {
log.Debug("Error while computing procID", "err", err)
d.returnPacketToPool(pkt)
metrics[sc].DroppedPacketsInvalid.Inc()
return
}
pkt.rawPacket = pkt.rawPacket[:size] // Update size; readBatch does not.
// Incremental refactoring: We should begin with finding the link and get the ifID
// from there. We will do that once we actually move these pre-processing tasks directly
// into the underlay.
pkt.ingress = ifID
pkt.srcAddr = srcAddr
select {
case procQs[procID] <- pkt:
default:
d.returnPacketToPool(pkt)
metrics[sc].DroppedPacketsBusyProcessor.Inc()
}
}
conn := u.Conn()
for d.IsRunning() {
// collect packets.
// Give a new buffer to the msgs elements that have been used in the previous loop.
for i := 0; i < d.RunConfig.BatchSize-numReusable; i++ {
p := d.getPacketFromPool()
p.reset()
packets[i] = p
msgs[i].Buffers[0] = p.rawPacket
}
// Fill the packets
numPkts, err := conn.ReadBatch(msgs)
numReusable = len(msgs) - numPkts
if err != nil {
log.Debug("Error while reading batch", "interfaceID", ifID, "err", err)
continue
}
for i, msg := range msgs[:numPkts] {
enqueueForProcessing(msg.N, msg.Addr.(*net.UDPAddr), packets[i])
}
}
}
func computeProcID(data []byte, numProcRoutines int, hashSeed uint32) (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
}
s := hashSeed
// inject the flowID
s = hashFNV1a(s, data[1]&0xF) // The left 4 bits aren't part of the flowID.
for _, c := range data[2:4] {
s = hashFNV1a(s, c)
}
// Inject the src/dst addresses
for _, c := range data[slayers.CmnHdrLen : slayers.CmnHdrLen+addrHdrLen] {
s = hashFNV1a(s, c)
}
return s % uint32(numProcRoutines), nil
}
func (d *DataPlane) getPacketFromPool() *Packet {
return <-d.packetPool
}
func (d *DataPlane) returnPacketToPool(pkt *Packet) {
d.packetPool <- pkt
}
func (d *DataPlane) runProcessor(id int, q <-chan *Packet, slowQ chan<- *Packet) {
log.Debug("Initialize processor with", "id", id)
processor := newPacketProcessor(d)
for d.IsRunning() {
p, ok := <-q
if !ok {
continue
}
disp := processor.processPkt(p)
sc := classOfSize(len(p.rawPacket))
metrics := d.forwardingMetrics[p.ingress][sc]
metrics.ProcessedPackets.Inc()
switch disp {
case pForward:
// Normal processing proceeds.
case pSlowPath:
// Not an error, processing continues on the slow path.
select {
case slowQ <- p:
default:
metrics.DroppedPacketsBusySlowPath.Inc()
d.returnPacketToPool(p)
}
continue
case pDone: // Packets that don't need more processing (e.g. BFD)
d.returnPacketToPool(p)
continue
case pDiscard: // Everything else
metrics.DroppedPacketsInvalid.Inc()
d.returnPacketToPool(p)
continue
default: // Newly added dispositions need to be handled.
log.Debug("Unknown packet disposition", "disp", disp)
d.returnPacketToPool(p)
continue
}
fwLink, ok := d.interfaces[p.egress]
if !ok {
log.Debug("Error determining forwarder. Egress is invalid", "egress", p.egress)
metrics.DroppedPacketsInvalid.Inc()
d.returnPacketToPool(p)
continue
}
if !fwLink.Send(p) {
d.returnPacketToPool(p)
metrics.DroppedPacketsBusyForwarder.Inc()
}
}
}
func (d *DataPlane) runSlowPathProcessor(id int, q <-chan *Packet) {
log.Debug("Initialize slow-path processor with", "id", id)
processor := newSlowPathProcessor(d)
for d.IsRunning() {
p, ok := <-q
if !ok {
continue
}
err := processor.processPacket(p)
sc := classOfSize(len(p.rawPacket))
metrics := d.forwardingMetrics[p.ingress][sc]
if err != nil {
log.Debug("Error processing packet", "err", err)
metrics.DroppedPacketsInvalid.Inc()
d.returnPacketToPool(p)
continue
}
fwLink, ok := d.interfaces[p.egress]
if !ok {
log.Debug("Error determining forwarder. Egress is invalid", "egress", p.egress)
d.returnPacketToPool(p)
continue
}
if !fwLink.Send(p) {
d.returnPacketToPool(p)
}
}
}
func newSlowPathProcessor(d *DataPlane) *slowPathPacketProcessor {
p := &slowPathPacketProcessor{
d: d,
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
pkt *Packet
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() {
p.path = nil
p.hbhLayer = slayers.HopByHopExtnSkipper{}
p.e2eLayer = slayers.EndToEndExtnSkipper{}
}
func (p *slowPathPacketProcessor) processPacket(pkt *Packet) error {
var err error
p.reset()
p.pkt = pkt
p.lastLayer, err = decodeLayers(pkt.rawPacket, &p.scionLayer, &p.hbhLayer, &p.e2eLayer)
if err != nil {
return err
}
pathType := p.scionLayer.PathType
switch pathType {
case scion.PathType:
var ok bool
p.path, ok = p.scionLayer.Path.(*scion.Raw)
if !ok {
return malformedPath
}
case epic.PathType:
epicPath, ok := p.scionLayer.Path.(*epic.Path)
if !ok {
return malformedPath
}
p.path = epicPath.ScionPath
if p.path == nil {
return malformedPath
}
default:
//unsupported path type
return serrors.New("Path type not supported for slow-path", "type", pathType)
}
s := pkt.slowPathRequest
switch s.typ {
case slowPathSCMP: //SCMP
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: p.d.localIA,
IfID: uint64(p.pkt.egress)}
case slayers.SCMPTypeInternalConnectivityDown:
layer = &slayers.SCMPInternalConnectivityDown{IA: p.d.localIA,
Ingress: uint64(p.pkt.ingress), Egress: uint64(p.pkt.egress)}
}
return p.packSCMP(s.scmpType, s.code, layer, true)
case slowPathRouterAlertIngress: //Traceroute
return p.handleSCMPTraceRouteRequest(p.pkt.ingress)
case slowPathRouterAlertEgress: //Traceroute
return p.handleSCMPTraceRouteRequest(p.pkt.egress)
default:
panic("Unsupported slow-path type")
}
}
func updateOutputMetrics(metrics interfaceMetrics, packets []*Packet) {
// We need to collect stats by traffic type and size class.