-
Notifications
You must be signed in to change notification settings - Fork 161
/
dataplane.go
2361 lines (2158 loc) · 69.4 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/big"
"net"
"net/netip"
"strconv"
"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/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 {
interfaces map[uint16]BatchConn
external map[uint16]BatchConn
linkTypes map[uint16]topology.LinkType
neighborIAs map[uint16]addr.IA
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]forwardingMetrics
// 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 = 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")
slowPathRequired = serrors.New("slow-path-required")
// 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 addr.Host) (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
}
if d.interfaces == nil {
d.interfaces = make(map[uint16]BatchConn)
}
d.interfaces[0] = conn
d.internal = conn
var ok bool
d.internalIP, ok = netip.AddrFromSlice(ip)
if !ok {
return serrors.New("invalid ip", "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)
}
if d.interfaces == nil {
d.interfaces = make(map[uint16]BatchConn)
}
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
}
// 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, 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 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.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 := 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.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 := 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, 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 slow_packet) {
procQs := make([]chan packet, cfg.NumProcessors)
for i := 0; i < cfg.NumProcessors; i++ {
procQs[i] = make(chan packet, processorQueueSize)
}
slowQs := make([]chan slow_packet, cfg.NumSlowPathProcessors)
for i := 0; i < cfg.NumSlowPathProcessors; i++ {
slowQs[i] = make(chan slow_packet, 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. Will be
// set by the receiver
ingress uint16
rawPacket []byte
}
type slow_packet struct {
packet packet
slowPathState slowPathState
}
func (d *DataPlane) runReceiver(ifID uint16, conn BatchConn, cfg *RunConfig,
procQs []chan packet) {
log.Debug("Run receiver for", "interface", ifID)
randomValue := make([]byte, 16)
if _, err := rand.Read(randomValue); err != nil {
panic("Error while generating random value")
}
msgs := underlayconn.NewReadMessages(cfg.BatchSize)
numReusable := 0 // unused buffers from previous loop
metrics := d.forwardingMetrics[ifID]
flowIDBuffer := make([]byte, 3)
hasher := fnv.New32a()
enqueueForProcessing := func(pkt ipv4.Message) {
metrics.InputPacketsTotal.Inc()
metrics.InputBytesTotal.Add(float64(pkt.N))
srcAddr := pkt.Addr.(*net.UDPAddr)
procID, err := computeProcID(pkt.Buffers[0],
cfg.NumProcessors, randomValue, flowIDBuffer, hasher)
if err != nil {
log.Debug("Error while computing procID", "err", err)
d.returnPacketToPool(pkt.Buffers[0])
metrics.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.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)
}
}
}
func computeProcID(data []byte, numProcRoutines int, randomValue []byte,
flowIDBuffer []byte, hasher hash.Hash32) (uint32, error) {
if len(data) < slayers.CmnHdrLen {
return 0, serrors.New("Packet is too short")
}
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, serrors.New("Packet is too short")
}
copy(flowIDBuffer[0:3], data[1:4])
flowIDBuffer[0] &= 0xF // the left 4 bits don't belong to the flowID
hasher.Reset()
hasher.Write(randomValue)
hasher.Write(flowIDBuffer[:])
hasher.Write(data[slayers.CmnHdrLen : slayers.CmnHdrLen+addrHdrLen])
return hasher.Sum32() % 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<- slow_packet) {
log.Debug("Initialize processor with", "id", id)
processor := newPacketProcessor(d)
for d.running {
p, ok := <-q
if !ok {
continue
}
metrics := d.forwardingMetrics[p.ingress]
result, err := processor.processPkt(p.rawPacket, p.srcAddr, p.ingress)
metrics.ProcessedPackets.Inc()
egress := result.EgressID
switch {
case err == nil:
case errors.Is(err, slowPathRequired):
select {
case slowQ <- slow_packet{
packet: p,
slowPathState: processor.slowPathState,
}:
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
select {
case fwCh <- p:
default:
d.returnPacketToPool(p.rawPacket)
metrics.DroppedPacketsBusyForwarder.Inc()
}
}
}
func (d *DataPlane) runSlowPathProcessor(id int, q <-chan slow_packet,
fwQs map[uint16]chan packet) {
log.Debug("Initialize slow-path processor with", "id", id)
processor := newSlowPathProcessor(d)
var scmpErr scmpError
for d.running {
p, ok := <-q
if !ok {
continue
}
metrics := d.forwardingMetrics[p.packet.ingress]
res, err := processor.processPacket(p)
switch {
case err == nil:
case errors.As(err, &scmpErr):
if !scmpErr.TypeCode.InfoMsg() {
log.Debug("SCMP", "err", scmpErr)
}
default:
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(),
mac: d.macFactory(),
macBuffers: macBuffers{
scionInput: make([]byte, path.MACBufferSize),
epicInput: make([]byte, libepic.MACBufferSize),
drkeyInput: make([]byte, spao.MACBufferSize),
},
drkeyProvider: &fakeProvider{},
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
mac hash.Hash
scionLayer slayers.SCION
hbhLayer slayers.HopByHopExtnSkipper
e2eLayer slayers.EndToEndExtnSkipper
lastLayer gopacket.DecodingLayer
path *scion.Raw
// cachedMac contains the full 16 bytes of the MAC. Will be set during processing.
// For a hop performing an Xover, it is the MAC corresponding to the down segment.
cachedMac []byte
// macBuffers avoid allocating memory during processing.
macBuffers macBuffers
// 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.mac.Reset()
p.cachedMac = nil
p.path = nil
p.hbhLayer = slayers.HopByHopExtnSkipper{}
p.e2eLayer = slayers.EndToEndExtnSkipper{}
}
func (p *slowPathPacketProcessor) processPacket(pkt slow_packet) (processResult, error) {
var err error
p.reset()
p.ingressID = pkt.packet.ingress
p.srcAddr = pkt.packet.srcAddr
p.rawPkt = pkt.packet.rawPacket
p.lastLayer, err = decodeLayers(pkt.packet.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.slowPathState.mode {
case 0: //SCMP
s := pkt.slowPathState
var layer gopacket.SerializableLayer
switch s.typ {
case slayers.SCMPTypeParameterProblem:
layer = &slayers.SCMPParameterProblem{Pointer: s.parameters[0].(uint16)}
case slayers.SCMPTypeDestinationUnreachable:
layer = &slayers.SCMPDestinationUnreachable{}
case slayers.SCMPTypeExternalInterfaceDown:
layer = &slayers.SCMPExternalInterfaceDown{IA: s.parameters[0].(addr.IA),
IfID: s.parameters[1].(uint64)}
case slayers.SCMPTypeInternalConnectivityDown:
layer = &slayers.SCMPInternalConnectivityDown{IA: s.parameters[0].(addr.IA),
Ingress: s.parameters[1].(uint64), Egress: s.parameters[2].(uint64)}
}
return p.packSCMP(s.typ, s.code, layer, s.cause)
case 1: //Traceroute
return p.handleSCMPTraceRouteRequest(pkt.slowPathState.parameters[0].(uint16))
default:
return processResult{}, serrors.New("Unspoorted slow-path mode", "mode",
pkt.slowPathState.mode)
}
}
func (d *DataPlane) runForwarder(ifID uint16, conn BatchConn,
cfg *RunConfig, c <-chan packet) {
log.Debug("Initialize forwarder for", "interface", ifID)
writeMsgs := make(underlayconn.Messages, cfg.BatchSize)
for i := range writeMsgs {
writeMsgs[i].Buffers = make([][]byte, 1)
}
metrics := d.forwardingMetrics[ifID]
remaining := 0
for d.running {
available := readUpTo(c, cfg.BatchSize-remaining, remaining == 0,
writeMsgs[remaining:])
available += remaining
written, _ := conn.WriteBatch(writeMsgs[:available], 0)
if written < 0 {
// WriteBatch returns -1 on error, we just consider this as
// 0 packets written
written = 0
}
writtenBytes := 0
for i := range writeMsgs[:written] {
writtenBytes += len(writeMsgs[i].Buffers[0])
d.returnPacketToPool(writeMsgs[i].Buffers[0])
}
metrics.OutputPacketsTotal.Add(float64(written))
metrics.OutputBytesTotal.Add(float64(writtenBytes))
if written != available {
metrics.DroppedPacketsInvalid.Inc()
d.returnPacketToPool(writeMsgs[written].Buffers[0])
remaining = available - written - 1
for i := 0; i < remaining; i++ {
writeMsgs[i].Buffers[0] = writeMsgs[i+written+1].Buffers[0]
writeMsgs[i].Addr = writeMsgs[i+written+1].Addr
}
} else {
remaining = 0
}
}
}
func readUpTo(c <-chan packet, n int, needsBlocking bool, msg []ipv4.Message) int {
assign := func(p packet, m *ipv4.Message) {
m.Buffers[0] = p.rawPacket
m.Addr = nil
if p.dstAddr != nil {
m.Addr = p.dstAddr
}
}
i := 0
if needsBlocking {
p, ok := <-c
if !ok {
return i
}
assign(p, &msg[i])
i++
}
for ; i < n; i++ {
select {
case p, ok := <-c:
if !ok {
return i
}
assign(p, &msg[i])
default:
return i
}
}
return i
}
// 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
OutAddr *net.UDPAddr
OutPkt []byte
}
func newPacketProcessor(d *DataPlane) *scionPacketProcessor {
p := &scionPacketProcessor{
d: d,
buffer: gopacket.NewSerializeBuffer(),
mac: d.macFactory(),
macBuffers: macBuffers{
scionInput: make([]byte, path.MACBufferSize),
epicInput: make([]byte, libepic.MACBufferSize),
drkeyInput: make([]byte, spao.MACBufferSize),
},
}
p.scionLayer.RecyclePaths()
return p
}
func (p *scionPacketProcessor) reset() error {
p.rawPkt = nil
p.srcAddr = nil
p.ingressID = 0
//p.scionLayer // cannot easily be reset
p.path = nil
p.hopField = path.HopField{}
p.infoField = path.InfoField{}
p.segmentChange = false