Repository navigation
Expand file tree
/
Copy pathconfig.go
More file actions
987 lines (939 loc) · 35.9 KB
/
Copy pathconfig.go
File metadata and controls
987 lines (939 loc) · 35.9 KB
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
package mipstack
import (
"encoding/binary"
"errors"
"net/netip"
"syscall"
)
const (
// rxChecksumOffloadIPv4Header delegates IPv4 header checksums to the link.
rxChecksumOffloadIPv4Header uint32 = 1 << iota
// rxChecksumOffloadTCP delegates complete TCP checksums to the link.
rxChecksumOffloadTCP
// rxChecksumOffloadUDP delegates nonzero UDP checksums to the link.
rxChecksumOffloadUDP
// rxChecksumOffloadICMPv4 delegates outer ICMPv4 checksums to the link.
rxChecksumOffloadICMPv4
// rxChecksumOffloadICMPv6 delegates ICMPv6 and MLD checksums to the link.
rxChecksumOffloadICMPv6
// rxChecksumOffloadIGMP delegates IGMP checksums to the link.
rxChecksumOffloadIGMP
)
// rxChecksumOffloadGenerated covers checksums produced by the Stack's protocol
// builders. Raw output never acquires this guarantee solely from its IP header.
const rxChecksumOffloadGenerated = rxChecksumOffloadIPv4Header | rxChecksumOffloadTCP | rxChecksumOffloadUDP |
rxChecksumOffloadICMPv4 | rxChecksumOffloadICMPv6 | rxChecksumOffloadIGMP
// RXChecksumOffload selects checksum verification delegated to the input
// link. Its zero value retains all verification. An enabled category requires
// the caller to supply valid complete packets with correct checksums or an
// equivalent validation guarantee.
//
// Offload does not disable framing or protocol checks, including IPv6 UDP's
// zero-checksum prohibition. Reassembled payloads, public codecs, checksums
// configured for other raw IPv6 protocols, and independent ICMP extension
// checksums retain their verification. Configure the policy before delivering
// input packets.
type RXChecksumOffload struct {
flags uint32
}
// SetIPv4Header controls IPv4 header checksum offload, including fragment
// headers, and returns o for chained configuration.
func (o *RXChecksumOffload) SetIPv4Header(enabled bool) *RXChecksumOffload {
if enabled {
o.flags |= rxChecksumOffloadIPv4Header
} else {
o.flags &^= rxChecksumOffloadIPv4Header
}
return o
}
// IPv4Header reports whether IPv4 header checksum offload is enabled.
func (o RXChecksumOffload) IPv4Header() bool { return o.flags&rxChecksumOffloadIPv4Header != 0 }
// SetTCP controls TCP checksum offload for both address families and returns
// o for chained configuration.
func (o *RXChecksumOffload) SetTCP(enabled bool) *RXChecksumOffload {
if enabled {
o.flags |= rxChecksumOffloadTCP
} else {
o.flags &^= rxChecksumOffloadTCP
}
return o
}
// TCP reports whether TCP checksum offload is enabled.
func (o RXChecksumOffload) TCP() bool { return o.flags&rxChecksumOffloadTCP != 0 }
// SetUDP controls UDP checksum offload for both address families and returns
// o for chained configuration. IPv6 zero-checksum datagrams remain invalid.
func (o *RXChecksumOffload) SetUDP(enabled bool) *RXChecksumOffload {
if enabled {
o.flags |= rxChecksumOffloadUDP
} else {
o.flags &^= rxChecksumOffloadUDP
}
return o
}
// UDP reports whether UDP checksum offload is enabled.
func (o RXChecksumOffload) UDP() bool { return o.flags&rxChecksumOffloadUDP != 0 }
// SetICMPv4 controls outer ICMPv4 checksum offload and returns o for chained
// configuration. Independent extension checksums remain verified.
func (o *RXChecksumOffload) SetICMPv4(enabled bool) *RXChecksumOffload {
if enabled {
o.flags |= rxChecksumOffloadICMPv4
} else {
o.flags &^= rxChecksumOffloadICMPv4
}
return o
}
// ICMPv4 reports whether outer ICMPv4 checksum offload is enabled.
func (o RXChecksumOffload) ICMPv4() bool { return o.flags&rxChecksumOffloadICMPv4 != 0 }
// SetICMPv6 controls ICMPv6 checksum offload, including MLD, and returns o
// for chained configuration. Independent extension checksums remain verified.
func (o *RXChecksumOffload) SetICMPv6(enabled bool) *RXChecksumOffload {
if enabled {
o.flags |= rxChecksumOffloadICMPv6
} else {
o.flags &^= rxChecksumOffloadICMPv6
}
return o
}
// ICMPv6 reports whether ICMPv6 checksum offload is enabled.
func (o RXChecksumOffload) ICMPv6() bool { return o.flags&rxChecksumOffloadICMPv6 != 0 }
// SetIGMP controls IGMP checksum offload and returns o for chained configuration.
func (o *RXChecksumOffload) SetIGMP(enabled bool) *RXChecksumOffload {
if enabled {
o.flags |= rxChecksumOffloadIGMP
} else {
o.flags &^= rxChecksumOffloadIGMP
}
return o
}
// IGMP reports whether IGMP checksum offload is enabled.
func (o RXChecksumOffload) IGMP() bool { return o.flags&rxChecksumOffloadIGMP != 0 }
// SetRXChecksumOffload replaces the input link's checksum verification policy.
// Configure it before delivering packets; changes do not establish a processing
// boundary for input already in progress. It does not affect socket defaults.
func (s *Stack) SetRXChecksumOffload(offload RXChecksumOffload) {
s.rxChecksumOffload.Store(offload.flags)
}
// RXChecksumOffload returns an independent copy of the input link's checksum
// verification policy.
func (s *Stack) RXChecksumOffload() RXChecksumOffload {
return RXChecksumOffload{flags: s.rxChecksumOffload.Load()}
}
// AddressProperties supplies RFC 6724 source-selection state that cannot be
// represented by a netip.Prefix alone.
type AddressProperties struct {
// Deprecated marks an address past its preferred lifetime. Automatic source
// selection avoids it when an otherwise usable preferred address exists.
Deprecated bool
// Temporary marks an IPv6 privacy address. PreferTemporaryAddresses selects
// whether automatic source selection favors it over a stable address.
Temporary bool
}
// Route admits one unicast destination prefix. Source optionally pins the
// preferred local source address; Metric breaks ties between equal prefixes.
// A source-less route may also carry transparent forwarder output when
// Promiscuous is enabled without a same-family local address. The embedding
// link remains responsible for next-hop selection.
type Route struct {
// Destination is the admitted unicast prefix.
Destination netip.Prefix
// Source pins the preferred local source address when valid.
Source netip.Addr
// Metric breaks ties between routes with equal prefix length.
Metric uint32
}
// networkState is an immutable address, route, and MTU snapshot.
type networkState struct {
mtu int
maxTCPConnections int
promiscuous bool
tcpDefaults TCPSocketDefaults
udpDefaults UDPSocketDefaults
ipDefaults IPSocketDefaults
local map[netip.Addr]struct{}
broadcast map[netip.Addr]struct{}
sources []netip.Addr
sourcePrefixBits []int
localPrefixes []netip.Prefix
routes []Route
addressProperties map[netip.Addr]AddressProperties
preferTemporary bool
}
// samePathConfiguration reports whether cached destination PMTU information
// remains valid across a configuration update. Address order participates in
// source selection, while prefix and route order can change admission and
// equal-priority route selection.
func (state *networkState) samePathConfiguration(other *networkState) bool {
if state == nil || other == nil || state.mtu != other.mtu ||
len(state.sources) != len(other.sources) || len(state.localPrefixes) != len(other.localPrefixes) || len(state.routes) != len(other.routes) ||
!state.sameSourceProperties(other) {
return false
}
for index := range state.sources {
if state.sources[index] != other.sources[index] {
return false
}
}
for index := range state.localPrefixes {
if state.localPrefixes[index] != other.localPrefixes[index] {
return false
}
}
for index := range state.routes {
if state.routes[index] != other.routes[index] {
return false
}
}
return true
}
// sameMulticastConfiguration reports whether family availability, report
// source selection, and IPv4 directed-broadcast classification are unchanged.
func (state *networkState) sameMulticastConfiguration(other *networkState) bool {
if state == nil || other == nil || len(state.sources) != len(other.sources) || len(state.localPrefixes) != len(other.localPrefixes) ||
!state.sameSourceProperties(other) {
return false
}
for index := range state.sources {
if state.sources[index] != other.sources[index] {
return false
}
}
for index := range state.localPrefixes {
if state.localPrefixes[index] != other.localPrefixes[index] {
return false
}
}
return true
}
// sameSourceProperties reports whether RFC 6724 address preference state is
// unchanged between immutable network snapshots.
func (state *networkState) sameSourceProperties(other *networkState) bool {
if state.preferTemporary != other.preferTemporary || len(state.addressProperties) != len(other.addressProperties) {
return false
}
for address, properties := range state.addressProperties {
otherProperties, exists := other.addressProperties[address]
if !exists || otherProperties != properties {
return false
}
}
return true
}
// buildNetworkState validates and normalizes one public configuration.
func buildNetworkState(config Config) (*networkState, error) {
mtu := int(config.MTU)
if mtu == 0 {
mtu = defaultMTU
}
if mtu < 68 || mtu > 65535 {
return nil, errors.New("mipstack: MTU must be between 68 and 65535")
}
if config.MaxTCPConnections < 0 {
return nil, errors.New("mipstack: maximum TCP connections cannot be negative")
}
tcpDefaults, err := normalizeTCPSocketDefaults(config.TCP)
if err != nil {
return nil, err
}
udpDefaults, err := normalizeUDPSocketDefaults(config.UDP)
if err != nil {
return nil, errors.New("mipstack: invalid UDP socket defaults: " + err.Error())
}
ipDefaults, err := normalizeIPSocketDefaults(config.IP)
if err != nil {
return nil, errors.New("mipstack: invalid IP socket defaults: " + err.Error())
}
state := &networkState{
mtu: mtu, maxTCPConnections: config.MaxTCPConnections, promiscuous: config.Promiscuous,
tcpDefaults: tcpDefaults, udpDefaults: udpDefaults, ipDefaults: ipDefaults,
local: make(map[netip.Addr]struct{}, len(config.LocalAddresses)), sources: make([]netip.Addr, 0, len(config.LocalAddresses)),
preferTemporary: config.PreferTemporaryAddresses,
}
configuredPrefixes := make(map[netip.Prefix]struct{}, len(config.LocalAddresses))
for _, prefix := range config.LocalAddresses {
address := prefix.Addr().Unmap()
if !prefix.IsValid() || !address.IsValid() || address.IsUnspecified() || address.IsMulticast() || address.Zone() != "" {
return nil, errors.New("mipstack: invalid local address")
}
bits := prefix.Bits()
if prefix.Addr().Is6() && address.Is4() {
bits -= 96
}
if bits < 0 || bits > address.BitLen() {
return nil, errors.New("mipstack: invalid local prefix")
}
if address.Is4() && isIPv4Broadcast(prefix, address, bits) {
return nil, errors.New("mipstack: IPv4 broadcast address cannot be local")
}
// LocalAddresses describes final state rather than a sequence of address
// additions, so repeated identical entries are idempotent.
configuredPrefix := netip.PrefixFrom(address, bits)
if _, duplicate := configuredPrefixes[configuredPrefix]; duplicate {
continue
}
configuredPrefixes[configuredPrefix] = struct{}{}
if _, exists := state.local[address]; !exists {
state.local[address] = struct{}{}
state.sources = append(state.sources, address)
state.sourcePrefixBits = append(state.sourcePrefixBits, bits)
} else {
// One source candidate represents every prefix of an address. Retaining
// the longest makes RFC 6724 rule 8 independent of prefix order.
for index, source := range state.sources {
if source == address {
if bits > state.sourcePrefixBits[index] {
state.sourcePrefixBits[index] = bits
}
break
}
}
}
masked := netip.PrefixFrom(address, bits).Masked()
state.localPrefixes = append(state.localPrefixes, masked)
if broadcast, ok := ipv4BroadcastAddress(masked); ok {
if state.broadcast == nil {
state.broadcast = make(map[netip.Addr]struct{}, len(config.LocalAddresses))
}
state.broadcast[broadcast] = struct{}{}
}
}
for address := range state.local {
if _, broadcast := state.broadcast[address]; broadcast {
return nil, errors.New("mipstack: IPv4 broadcast address cannot be local")
}
}
if len(config.AddressProperties) != 0 {
state.addressProperties = make(map[netip.Addr]AddressProperties, len(config.AddressProperties))
for address, properties := range config.AddressProperties {
normalized := address.Unmap()
if !address.IsValid() || address.Zone() != "" || !normalized.IsValid() || normalized.IsUnspecified() || normalized.IsMulticast() {
return nil, errors.New("mipstack: invalid address-properties key")
}
if _, local := state.local[normalized]; !local {
return nil, errors.New("mipstack: address properties refer to a nonlocal address")
}
if properties.Temporary && normalized.Is4() {
return nil, errors.New("mipstack: temporary source property requires IPv6")
}
if existing, duplicate := state.addressProperties[normalized]; duplicate && existing != properties {
return nil, errors.New("mipstack: conflicting address properties")
}
state.addressProperties[normalized] = properties
}
}
addressless := len(state.local) == 0
if addressless && !state.promiscuous {
return nil, errors.New("mipstack: at least one local address is required")
}
var haveLocal4, haveLocal6 bool
for _, source := range state.sources {
if source.Is4() {
haveLocal4 = true
} else {
haveLocal6 = true
}
}
state.routes = make([]Route, 0, len(config.Routes)+2)
haveIPv6Output := haveLocal6
for _, route := range config.Routes {
destination, err := normalizeRoutePrefix(route.Destination)
if err != nil {
return nil, err
}
source := route.Source.Unmap()
if route.Source.IsValid() {
if !source.IsValid() || source.IsUnspecified() || source.IsMulticast() || source.Zone() != "" || source.Is6() != destination.Addr().Is6() {
return nil, errors.New("mipstack: invalid route source")
}
if _, exists := state.local[source]; !exists {
return nil, errors.New("mipstack: route source is not local")
}
} else {
source = netip.Addr{}
}
familyAvailable := haveLocal4
if destination.Addr().Is6() {
familyAvailable = haveLocal6
haveIPv6Output = true
}
if !familyAvailable && !state.promiscuous {
return nil, errors.New("mipstack: route has no local address in its family")
}
state.routes = append(state.routes, Route{Destination: destination, Source: source, Metric: route.Metric})
}
if config.Routes == nil {
default4, default6 := haveLocal4, haveLocal6
if addressless {
// Promiscuous admission supports both IP versions. Source-less
// defaults let intercepted flows return over the single embedding
// link without granting either family to ordinary sockets.
default4, default6 = true, true
}
if default4 {
state.routes = append(state.routes, Route{Destination: netip.PrefixFrom(netip.IPv4Unspecified(), 0)})
}
if default6 {
state.routes = append(state.routes, Route{Destination: netip.PrefixFrom(netip.IPv6Unspecified(), 0)})
haveIPv6Output = true
}
}
if mtu < ipv6MinimumMTU && haveIPv6Output {
return nil, errors.New("mipstack: IPv6 requires an MTU of at least 1280")
}
return state, nil
}
// normalizeUDPSocketDefaults validates and normalizes the shared datagram
// policies inherited by UDP sockets.
func normalizeUDPSocketDefaults(value UDPSocketDefaults) (UDPSocketDefaults, error) {
defaults, err := normalizeDatagramSocketDefaults(value.DatagramSocketDefaults, udpDefaultReceiveCapacity, udpDatagramMetadataSize)
if err != nil {
return UDPSocketDefaults{}, err
}
value.DatagramSocketDefaults = defaults
return value, nil
}
// normalizeIPSocketDefaults validates the shared datagram policies while
// preserving the IP-specific representation defaults.
func normalizeIPSocketDefaults(value IPSocketDefaults) (IPSocketDefaults, error) {
defaults, err := normalizeDatagramSocketDefaults(value.DatagramSocketDefaults, ipDefaultReceiveCapacity, ipDatagramMetadataSize)
if err != nil {
return IPSocketDefaults{}, err
}
value.DatagramSocketDefaults = defaults
return value, nil
}
// acceptsInboundDestination reports whether one unicast destination may enter
// transport dispatch. Promiscuous admission deliberately remains separate
// from local ownership, source selection, and loopback routing.
func (state *networkState) acceptsInboundDestination(address netip.Addr) bool {
address = address.Unmap()
if _, local := state.local[address]; local {
return true
}
return state.acceptsNonlocalDestination(address)
}
// acceptsNonlocalDestination applies only the promiscuous branch after the
// caller has already established that address is not locally owned.
func (state *networkState) acceptsNonlocalDestination(address netip.Addr) bool {
address = address.Unmap()
if !state.promiscuous || !address.IsValid() || address.IsUnspecified() || address.IsMulticast() || address.IsLoopback() {
return false
}
return !state.broadcastDestination(address)
}
// normalizeTCPSocketDefaults validates optional limits and fills the policy
// used by new sockets without changing Config's useful zero value.
func normalizeTCPSocketDefaults(value TCPSocketDefaults) (TCPSocketDefaults, error) {
if value.CongestionControlFactory != nil {
if value.CongestionControl != "" {
return TCPSocketDefaults{}, errors.New("mipstack: TCP congestion control name and factory are mutually exclusive")
}
if !value.CongestionControlFactory.valid() {
return TCPSocketDefaults{}, errors.New("mipstack: invalid TCP congestion control factory")
}
} else {
if value.CongestionControl == "" {
value.CongestionControl = CongestionControlCUBIC
}
factory, exists := registeredCongestionControlFactory(value.CongestionControl)
if !exists {
return TCPSocketDefaults{}, errors.New("mipstack: unsupported congestion control")
}
value.CongestionControl = ""
value.CongestionControlFactory = factory
}
if value.ReceiveBuffer < 0 || value.MaximumReceiveBuffer < 0 || value.SendBuffer < 0 || value.MaximumSendBuffer < 0 ||
value.AcceptQueue < 0 || value.SYNBacklog < 0 || value.IdleTimeout < 0 || value.UserTimeout < 0 {
return TCPSocketDefaults{}, errors.New("mipstack: TCP socket defaults cannot be negative")
}
if value.FlowLabel > ipv6MaximumFlowLabel {
return TCPSocketDefaults{}, errors.New("mipstack: TCP flow label exceeds 20 bits")
}
if value.ReceiveBuffer == 0 {
value.ReceiveBuffer = tcpReceiveCapacity
}
if value.MaximumReceiveBuffer == 0 {
value.MaximumReceiveBuffer = tcpMaximumReceiveCapacity
}
if value.SendBuffer == 0 {
value.SendBuffer = tcpSendCapacity
}
if value.MaximumSendBuffer == 0 {
value.MaximumSendBuffer = tcpMaximumSendCapacity
}
if value.MaximumReceiveBuffer < value.ReceiveBuffer || value.MaximumSendBuffer < value.SendBuffer {
return TCPSocketDefaults{}, errors.New("mipstack: TCP automatic buffer maximum is below its initial size")
}
if uint64(value.MaximumReceiveBuffer) > uint64(tcpMaximumScaledWindow) {
return TCPSocketDefaults{}, errors.New("mipstack: TCP receive buffer maximum exceeds the RFC 7323 window limit")
}
if value.AcceptQueue == 0 {
value.AcceptQueue = tcpAcceptQueue
}
if value.SYNBacklog == 0 {
value.SYNBacklog = tcpSYNBacklog
}
if value.KeepAliveConfig.Idle == 0 {
value.KeepAliveConfig.Idle = tcpDefaultKeepAliveIdle
}
if value.KeepAliveConfig.Interval == 0 {
value.KeepAliveConfig.Interval = tcpDefaultKeepAliveInterval
}
if value.KeepAliveConfig.Count == 0 {
value.KeepAliveConfig.Count = tcpDefaultKeepAliveCount
}
if value.KeepAliveConfig.Idle < 0 || value.KeepAliveConfig.Interval < 0 || value.KeepAliveConfig.Count < 0 {
return TCPSocketDefaults{}, errors.New("mipstack: TCP keepalive defaults cannot be negative")
}
value.TrafficClass &= 0xfc
return value, nil
}
// normalizeDatagramSocketDefaults validates one UDP or IP default policy.
func normalizeDatagramSocketDefaults(value DatagramSocketDefaults, defaultReceiveBuffer, minimumReceiveBuffer int) (DatagramSocketDefaults, error) {
if value.ReceiveBuffer < 0 || value.HopLimit < 0 || value.HopLimit > 255 || value.MulticastHopLimit < 0 || value.MulticastHopLimit > 255 {
return DatagramSocketDefaults{}, errors.New("receive buffer and hop limit must be valid")
}
if !value.PathMTUDiscovery.valid() {
return DatagramSocketDefaults{}, errors.New("unsupported path MTU discovery mode")
}
if value.FlowLabel > ipv6MaximumFlowLabel {
return DatagramSocketDefaults{}, errors.New("flow label exceeds 20 bits")
}
if value.ReceiveBuffer == 0 {
value.ReceiveBuffer = defaultReceiveBuffer
} else if value.ReceiveBuffer < minimumReceiveBuffer {
value.ReceiveBuffer = minimumReceiveBuffer
}
if value.HopLimit == 0 {
value.HopLimit = 64
}
if value.MulticastHopLimit == 0 {
value.MulticastHopLimit = 1
}
return value, nil
}
// invalidInboundSource reports source addresses that RFC 1122 forbids on an
// incoming datagram. Generic multicast, unspecified, and limited-broadcast
// checks are performed by the caller; this method recognizes a directed
// broadcast on one of the stack's configured IPv4 subnets.
func (state *networkState) invalidInboundSource(address netip.Addr) bool {
_, broadcast := state.broadcast[address.Unmap()]
return broadcast
}
// broadcastDestination reports limited broadcast and directed broadcast for
// one of the configured IPv4 prefixes.
func (state *networkState) broadcastDestination(address netip.Addr) bool {
address = address.Unmap()
if !address.Is4() {
return false
}
if address == netip.AddrFrom4([4]byte{255, 255, 255, 255}) {
return true
}
_, broadcast := state.broadcast[address]
return broadcast
}
// ipv4BroadcastAddress returns the directed broadcast for prefixes that have
// a host field. RFC 3021 /31 and host /32 prefixes have no broadcast address;
// RFC 1122 loopback space must never select the embedding link.
func ipv4BroadcastAddress(prefix netip.Prefix) (netip.Addr, bool) {
if !prefix.IsValid() || !prefix.Addr().Is4() || prefix.Addr().IsLoopback() || prefix.Bits() >= 31 {
return netip.Addr{}, false
}
networkBytes := prefix.Masked().Addr().As4()
network := binary.BigEndian.Uint32(networkBytes[:])
hostMask := uint32((uint64(1) << (32 - prefix.Bits())) - 1)
var address [4]byte
binary.BigEndian.PutUint32(address[:], network|hostMask)
return netip.AddrFrom4(address), true
}
// isIPv4Broadcast reports limited broadcast and subnet broadcast addresses.
// Prefixes /31 and /32 do not reserve a subnet broadcast address.
func isIPv4Broadcast(prefix netip.Prefix, address netip.Addr, bits int) bool {
addressBytes := address.As4()
value := binary.BigEndian.Uint32(addressBytes[:])
if value == ^uint32(0) {
return true
}
if bits >= 31 {
return false
}
networkBytes := prefix.Masked().Addr().Unmap().As4()
network := binary.BigEndian.Uint32(networkBytes[:])
hostMask := uint32((uint64(1) << (32 - bits)) - 1)
return value == network|hostMask
}
// normalizeRoutePrefix converts mapped IPv4 prefixes and rejects malformed
// or zone-bearing route keys.
func normalizeRoutePrefix(prefix netip.Prefix) (netip.Prefix, error) {
if !prefix.IsValid() || prefix.Addr().Zone() != "" {
return netip.Prefix{}, errors.New("mipstack: invalid route destination")
}
address := prefix.Addr().Unmap()
bits := prefix.Bits()
if prefix.Addr().Is6() && address.Is4() {
bits -= 96
}
if bits < 0 || bits > address.BitLen() {
return netip.Prefix{}, errors.New("mipstack: invalid route destination")
}
return netip.PrefixFrom(address, bits).Masked(), nil
}
// routeFor returns the longest-prefix, lowest-metric route for destination.
func (state *networkState) routeFor(destination netip.Addr) (Route, bool) {
destination = destination.Unmap()
if _, local := state.local[destination]; local {
return Route{Destination: netip.PrefixFrom(destination, destination.BitLen()), Source: destination}, true
}
var selected Route
selectedIndex := -1
for index, route := range state.routes {
if route.Destination.Addr().Is6() != destination.Is6() || !route.Destination.Contains(destination) {
continue
}
if selectedIndex < 0 || route.Destination.Bits() > selected.Destination.Bits() ||
route.Destination.Bits() == selected.Destination.Bits() && route.Metric < selected.Metric {
selected, selectedIndex = route, index
}
}
return selected, selectedIndex >= 0
}
// sourceForUnicast selects a route-admitted local address using the applicable
// RFC 6724 rules for a single interface. The caller has already excluded
// multicast and broadcast.
func (state *networkState) sourceForUnicast(destination, requested netip.Addr) (netip.Addr, error) {
destination = destination.Unmap()
if !destination.IsValid() || destination.IsUnspecified() || destination.IsMulticast() || destination.Zone() != "" {
return netip.Addr{}, syscall.EINVAL
}
route, exists := state.routeFor(destination)
if !exists {
return netip.Addr{}, syscall.ENETUNREACH
}
if destination.IsLoopback() {
if _, local := state.local[destination]; !local {
return netip.Addr{}, syscall.ENETUNREACH
}
}
requested = requested.Unmap()
if requested.IsValid() && !requested.IsUnspecified() {
if requested.Is6() != destination.Is6() {
return netip.Addr{}, syscall.EAFNOSUPPORT
}
if _, local := state.local[requested]; !local {
return netip.Addr{}, syscall.EADDRNOTAVAIL
}
return requested, nil
}
if route.Source.IsValid() {
return route.Source, nil
}
var selected netip.Addr
selectedPrefixBits := 0
for index, candidate := range state.sources {
if candidate.Is6() != destination.Is6() {
continue
}
candidatePrefixBits := state.sourcePrefixBits[index]
if !selected.IsValid() || state.preferSource(candidate, candidatePrefixBits, selected, selectedPrefixBits, destination) {
selected = candidate
selectedPrefixBits = candidatePrefixBits
}
}
if !selected.IsValid() {
return netip.Addr{}, syscall.EADDRNOTAVAIL
}
return selected, nil
}
// sourceForNonUnicast selects the source of output constrained to mipstack's
// single embedding interface. Broadcast and multicast do not use the unicast
// route table: Linux represents their selected output interface separately,
// while mipstack has exactly one such interface.
func (state *networkState) sourceForNonUnicast(destination, requested netip.Addr) (netip.Addr, error) {
destination = destination.Unmap()
if !destination.IsValid() || destination.IsUnspecified() || destination.Zone() != "" ||
!destination.IsMulticast() && !state.broadcastDestination(destination) {
return netip.Addr{}, syscall.EINVAL
}
if destination.IsMulticast() && !validMulticastGroup(destination) {
return netip.Addr{}, syscall.EINVAL
}
requested = requested.Unmap()
if requested.IsValid() && !requested.IsUnspecified() {
if requested.Zone() != "" || requested.IsMulticast() || requested.Is6() != destination.Is6() {
return netip.Addr{}, syscall.EAFNOSUPPORT
}
if _, local := state.local[requested]; !local {
return netip.Addr{}, syscall.EADDRNOTAVAIL
}
if state.broadcastDestination(destination) && requested.IsLoopback() {
return netip.Addr{}, syscall.ENETUNREACH
}
if destination.IsMulticast() && !sourceScopeUsable(requested, destination) {
return netip.Addr{}, syscall.ENETUNREACH
}
return requested, nil
}
if state.broadcastDestination(destination) {
// Prefer an address from the directed-broadcast subnet. Limited
// broadcast falls through to the first configured IPv4 address.
if destination != netip.AddrFrom4([4]byte{255, 255, 255, 255}) {
for _, prefix := range state.localPrefixes {
if !prefix.Addr().Is4() || !isIPv4Broadcast(prefix, destination, prefix.Bits()) {
continue
}
for _, candidate := range state.sources {
if candidate.Is4() && !candidate.IsLoopback() && prefix.Contains(candidate) {
return candidate, nil
}
}
}
}
for _, candidate := range state.sources {
if candidate.Is4() && !candidate.IsLoopback() {
return candidate, nil
}
}
return netip.Addr{}, syscall.EADDRNOTAVAIL
}
if destination.Is4() {
// Without IP_MULTICAST_IF, Linux uses the selected interface's
// primary IPv4 address. Configuration order defines that primary
// address for mipstack's single interface.
for _, candidate := range state.sources {
if candidate.Is4() && !candidate.IsLoopback() {
return candidate, nil
}
}
return netip.Addr{}, syscall.EADDRNOTAVAIL
}
var selected netip.Addr
selectedPrefixBits := 0
for index, candidate := range state.sources {
if candidate.Is6() != destination.Is6() {
continue
}
candidatePrefixBits := state.sourcePrefixBits[index]
if !selected.IsValid() || state.preferSource(candidate, candidatePrefixBits, selected, selectedPrefixBits, destination) {
selected = candidate
selectedPrefixBits = candidatePrefixBits
}
}
if !selected.IsValid() {
return netip.Addr{}, syscall.EADDRNOTAVAIL
}
return selected, nil
}
// inboundIPv4PacketInfoSource selects ipi_spec_dst for one received IPv4
// packet. A local unicast destination selects itself. Other destinations use
// the packet-source route's preferred source, then an address on the source's
// configured prefix, and finally the first usable address, matching Linux's
// fib_compute_spec_dst behavior on this single embedding link. The result is
// computed when receive ancillary data is produced; queued datagrams retain
// only their wire addresses. Linux computes and stores fib_compute_spec_dst
// during ingress, so a configuration change before a read can produce a
// different ipi_spec_dst here. Deriving the value on demand keeps queued
// datagrams compact and avoids packet-info source selection on ordinary reads.
func (state *networkState) inboundIPv4PacketInfoSource(source, destination netip.Addr) netip.Addr {
source, destination = source.Unmap(), destination.Unmap()
if !destination.Is4() {
return netip.Addr{}
}
if _, local := state.local[destination]; local {
return destination
}
if source.Is4() && !source.IsUnspecified() {
if selected, err := state.sourceForUnicast(source, netip.Addr{}); err == nil {
return selected
}
for index, candidate := range state.sources {
if !candidate.Is4() || candidate.IsLoopback() || index >= len(state.sourcePrefixBits) {
continue
}
prefix := netip.PrefixFrom(candidate, state.sourcePrefixBits[index])
if prefix.Contains(source) {
return candidate
}
}
}
for _, candidate := range state.sources {
if candidate.Is4() && !candidate.IsLoopback() {
return candidate
}
}
return netip.Addr{}
}
// hasOutputPath reports whether an established connectionless socket can
// still select this stack's only output interface after a configuration
// change. Non-unicast interface selection is independent of unicast routes.
func (state *networkState) hasOutputPath(destination netip.Addr) bool {
destination = destination.Unmap()
if destination.IsMulticast() || state.broadcastDestination(destination) {
return networkStateHasFamily(state, destination.Is6())
}
_, routed := state.routeFor(destination)
return routed
}
// preferSource applies the relevant RFC 6724 rules in order. Home-address and
// outgoing-interface rules are ties because one Stack represents one
// interface and exposes no mobile home-address state. Stable configuration
// order resolves complete ties.
func (state *networkState) preferSource(candidate netip.Addr, candidatePrefixBits int, current netip.Addr, currentPrefixBits int, destination netip.Addr) bool {
if candidate == destination || current == destination {
return candidate == destination
}
candidateScope, currentScope, destinationScope := addressScope(candidate), addressScope(current), addressScope(destination)
if candidateScope != currentScope {
candidateAppropriate := candidateScope >= destinationScope
currentAppropriate := currentScope >= destinationScope
if candidateAppropriate != currentAppropriate {
return candidateAppropriate
}
if candidateAppropriate {
return candidateScope < currentScope
}
return candidateScope > currentScope
}
candidateProperties, currentProperties := state.addressProperties[candidate], state.addressProperties[current]
if candidateProperties.Deprecated != currentProperties.Deprecated {
return !candidateProperties.Deprecated
}
if (addressLabel(candidate) == addressLabel(destination)) != (addressLabel(current) == addressLabel(destination)) {
return addressLabel(candidate) == addressLabel(destination)
}
if candidateProperties.Temporary != currentProperties.Temporary {
return candidateProperties.Temporary == state.preferTemporary
}
return commonPrefixBits(candidate, destination, candidatePrefixBits) > commonPrefixBits(current, destination, currentPrefixBits)
}
// sourceScopeUsable reports whether an explicitly selected source has enough
// scope for a non-unicast destination. Automatic RFC 6724 selection does not
// discard insufficient candidates because one must still win when every
// configured address has insufficient scope.
func sourceScopeUsable(source, destination netip.Addr) bool {
return addressScope(source) >= addressScope(destination) || destination.IsLoopback()
}
// validMulticastGroup rejects malformed group addresses that netip still
// classifies by prefix. It applies RFC 4291/RFC 7346 reserved flag and scope
// rules plus the RFC 3306/RFC 3956 dependencies between R, P, and T. Embedded
// fields are deliberately not validated here because RFC 3956 requires
// receivers to ignore some sender-reserved values.
func validMulticastGroup(address netip.Addr) bool {
address = address.Unmap()
if !address.IsValid() || !address.IsMulticast() || address.Zone() != "" {
return false
}
if address.Is4() {
return true
}
raw := address.As16()
flags, scope := raw[1]>>4, raw[1]&0x0f
if scope == 0 || scope == 0x0f || flags&8 != 0 {
return false
}
transient, prefixBased, embeddedRP := flags&1 != 0, flags&2 != 0, flags&4 != 0
if prefixBased && !transient || embeddedRP && !prefixBased {
return false
}
return true
}
// isInterfaceLocalMulticast identifies IPv6 scope one, which may traverse
// mipstack's internal loopback path but must never arrive from or leave via
// the embedding link.
func isInterfaceLocalMulticast(address netip.Addr) bool {
address = address.Unmap()
return address.Is6() && address.IsMulticast() && address.As16()[1]&0x0f == 1
}
// addressScope returns the RFC 6724 scope used to compare unicast and
// multicast candidates. The values match IPv6 multicast's scope field.
func addressScope(address netip.Addr) uint8 {
address = address.Unmap()
if address.IsLoopback() {
return 2
}
if address.IsMulticast() {
if address.Is4() {
value := address.As4()
if value[0] == 224 && value[1] == 0 && value[2] == 0 {
return 2
}
if value[0] == 239 && value[1] == 255 {
return 3
}
if value[0] == 239 && value[1]&0xfc == 192 {
return 8
}
return 14
}
return address.As16()[1] & 0x0f
}
if address.IsLinkLocalUnicast() {
return 2
}
if address.Is6() {
value := address.As16()
if value[0] == 0xfe && value[1]&0xc0 == 0xc0 {
return 5
}
}
return 14
}
// addressLabel returns the relevant RFC 6724 default-policy label.
func addressLabel(address netip.Addr) uint8 {
address = address.Unmap()
if address.Is4() {
return 4
}
if address.IsLoopback() {
return 0
}
value := address.As16()
if value[0] == 0x20 && value[1] == 0x02 {
return 2
}
if value[0] == 0x20 && value[1] == 0x01 && value[2] == 0 && value[3] == 0 {
return 5
}
if value[0]&0xfe == 0xfc {
return 13
}
if value[0] == 0xfe && value[1]&0xc0 == 0xc0 {
return 11
}
if value[0] == 0x3f && value[1] == 0xfe {
return 12
}
if binary.BigEndian.Uint64(value[:8]) == 0 && binary.BigEndian.Uint32(value[8:12]) == 0 {
return 3
}
return 1
}
// commonPrefixBits counts equal high-order address bits up to the source
// address's configured prefix length, as required by RFC 6724 rule 8.
func commonPrefixBits(left, right netip.Addr, limit int) int {
left, right = left.Unmap(), right.Unmap()
if !left.IsValid() || !right.IsValid() || left.Is4() != right.Is4() || limit <= 0 {
return 0
}
leftValue, rightValue := left.As16(), right.As16()
start := 0
if left.Is4() {
start = 12
}
leftBytes, rightBytes := leftValue[start:], rightValue[start:]
result := 0
for index := range leftBytes {
difference := leftBytes[index] ^ rightBytes[index]
if difference == 0 {
result += 8
continue
}
for mask := byte(0x80); difference&mask == 0; mask >>= 1 {
result++
}
break
}
if result > limit {
return limit
}
return result
}