Repository navigation
Expand file tree
/
Copy pathmulticast.go
More file actions
2809 lines (2667 loc) · 94 KB
/
Copy pathmulticast.go
File metadata and controls
2809 lines (2667 loc) · 94 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
988
989
990
991
992
993
994
995
996
997
998
999
1000
package mipstack
import (
"context"
"encoding/binary"
"net"
"net/netip"
"sort"
"sync"
"sync/atomic"
"syscall"
"time"
)
const (
// multicastDefaultRobustness is the RFC 9776/RFC 3810 default.
multicastDefaultRobustness = 2
// multicastDefaultQueryInterval is the default Querier's Query Interval.
multicastDefaultQueryInterval = 125 * time.Second
// multicastDefaultResponseInterval is the default Query Response Interval.
multicastDefaultResponseInterval = 10 * time.Second
// multicastUnsolicitedReportInterval bounds state-change retransmission
// jitter in both IGMPv3 and MLDv2.
multicastUnsolicitedReportInterval = time.Second
// multicastMaximumQuerySources bounds state retained from untrusted
// Group-and-Source-Specific Queries. It exceeds RFC 9776's mandatory
// service-API minimum while keeping one hostile query memory-bounded.
multicastMaximumQuerySources = 4096
)
const (
// igmpMembershipQuery is the IGMP Membership Query message type.
igmpMembershipQuery = 0x11
// igmpV1MembershipReport is the IGMPv1 Membership Report message type.
igmpV1MembershipReport = 0x12
// igmpV2MembershipReport is the IGMPv2 Membership Report message type.
igmpV2MembershipReport = 0x16
// igmpV2LeaveGroup is the IGMPv2 Leave Group message type.
igmpV2LeaveGroup = 0x17
// igmpV3MembershipReport is the IGMPv3 Membership Report message type.
igmpV3MembershipReport = 0x22
// mldMembershipQuery is the MLD Multicast Listener Query message type.
mldMembershipQuery = 130
// mldV1MembershipReport is the MLDv1 Multicast Listener Report type.
mldV1MembershipReport = 131
// mldV1ListenerDone is the MLDv1 Multicast Listener Done message type.
mldV1ListenerDone = 132
// mldV2MembershipReport is the MLDv2 Multicast Listener Report type.
mldV2MembershipReport = 143
// multicastRecordModeIsInclude reports the current INCLUDE source state.
multicastRecordModeIsInclude = 1
// multicastRecordModeIsExclude reports the current EXCLUDE source state.
multicastRecordModeIsExclude = 2
// multicastRecordChangeToIncludeMode announces a transition to INCLUDE.
multicastRecordChangeToIncludeMode = 3
// multicastRecordChangeToExcludeMode announces a transition to EXCLUDE.
multicastRecordChangeToExcludeMode = 4
// multicastRecordAllowNewSources adds sources accepted by the interface.
multicastRecordAllowNewSources = 5
// multicastRecordBlockOldSources removes sources accepted by the interface.
multicastRecordBlockOldSources = 6
)
// MulticastSourceFilterMode identifies an RFC 3678 full-state source policy.
type MulticastSourceFilterMode uint8
const (
// MulticastSourceFilterExclude receives packets from every source except
// those listed. An empty EXCLUDE list is an any-source membership. Its
// value matches Linux and RFC 3678's MCAST_EXCLUDE.
MulticastSourceFilterExclude MulticastSourceFilterMode = iota
// MulticastSourceFilterInclude receives packets only from listed sources.
// An empty INCLUDE list is equivalent to leaving the group. Its value
// matches Linux and RFC 3678's MCAST_INCLUDE.
MulticastSourceFilterInclude
)
// MulticastSourceFilter is the complete per-socket RFC 3678 filter state for
// one group. SetMulticastSourceFilter copies Sources before returning, and
// MulticastSourceFilter returns an independent, address-sorted snapshot.
type MulticastSourceFilter struct {
// Mode selects an INCLUDE or EXCLUDE source set.
Mode MulticastSourceFilterMode
// Sources is copied by SetMulticastSourceFilter and may be reused by the
// caller as soon as that method returns.
Sources []netip.Addr
}
// multicastFilterMode is the RFC 9776/RFC 3810 internal source-filter mode.
// It is deliberately independent of the Linux-compatible public constants,
// so zero-initialized protocol state remains INCLUDE as required by the
// interface-state merge rules.
type multicastFilterMode uint8
const (
// multicastFilterInclude accepts only sources present in the filter.
multicastFilterInclude multicastFilterMode = iota
// multicastFilterExclude accepts every source absent from the filter.
multicastFilterExclude
)
// multicastMembershipOperation identifies one RFC 3678 delta operation.
type multicastMembershipOperation uint8
const (
// multicastJoinAnySource creates an EXCLUDE {} membership.
multicastJoinAnySource multicastMembershipOperation = iota
// multicastLeaveGroup removes every membership for the group.
multicastLeaveGroup
// multicastJoinSource adds one source to an INCLUDE membership.
multicastJoinSource
// multicastLeaveSource removes one source from an INCLUDE membership.
multicastLeaveSource
// multicastExcludeSource adds one source to an EXCLUDE membership.
multicastExcludeSource
// multicastIncludeSource removes one source from an EXCLUDE membership.
multicastIncludeSource
)
// multicastFilter is one socket's source policy. Published filters and their
// source maps are immutable; delta operations replace them copy-on-write so
// lock-free dispatch snapshots can share the maps safely.
type multicastFilter struct {
mode multicastFilterMode
sources map[netip.Addr]struct{}
}
// multicastEndpoint is implemented only by datagram sockets that can own an
// IP multicast membership. The marker keeps membership storage type-safe.
type multicastEndpoint interface {
// multicastEndpoint marks a UDP or raw IP socket as a membership owner.
multicastEndpoint()
}
// multicastEndpoints is the optional multicast dispatcher retained by Stack.
// Its concrete state is reachable only when an application joins a group.
type multicastEndpoints interface {
// acceptsDestination reports whether the interface has an active
// membership for a destination group.
acceptsDestination(netip.Addr) bool
// acceptsSource applies the aggregate interface filter for a group.
acceptsSource(netip.Addr, netip.Addr) bool
// deliverUDP fans one multicast datagram out to matching UDP memberships.
deliverUDP(ipPacket, uint16, uint16)
// deliverIP fans one multicast payload out to matching raw IP memberships.
deliverIP(ipPacket) bool
// deliverImplicitIP applies explicit filters while preserving the implicit
// all-hosts delivery inherited by raw IP sockets.
deliverImplicitIP(ipPacket, ipEndpoints) bool
// handleControl processes one validated IGMP or MLD control packet.
handleControl(ipPacket, time.Time, bool)
// removeEndpoint drops every membership owned by a closing socket.
removeEndpoint(multicastEndpoint)
// updateConfig reconciles memberships with a new interface configuration.
updateConfig(*networkState)
// close stops background work and releases retained membership state.
close()
}
// multicastGroupState owns the socket filters and their RFC-derived aggregate
// interface state for one IP group.
type multicastGroupState struct {
members map[multicastEndpoint]*multicastFilter
aggregate multicastFilter
dispatch atomic.Pointer[multicastDispatchGroup]
query multicastPendingQuery
// lastReporter is used only by IGMPv1/v2 and MLDv1 suppression and leave
// behavior. Version 3/2 reports are deliberately never suppressed.
lastReporter bool
}
// multicastDispatchSnapshot is an immutable address index. Each indexed group
// publishes its own immutable dispatch entry independently.
type multicastDispatchSnapshot struct {
groups map[netip.Addr]*multicastGroupState
}
// multicastDispatchGroup separates endpoint types so packet delivery does
// not allocate or perform interface assertions.
type multicastDispatchGroup struct {
filter multicastFilter
udp []multicastUDPDispatch
ip []multicastIPDispatch
}
// multicastUDPDispatch is one immutable UDP membership entry.
type multicastUDPDispatch struct {
connection *UDPConn
filter multicastFilter
}
// multicastIPDispatch is one immutable raw-IP membership entry.
type multicastIPDispatch struct {
connection *IPConn
filter multicastFilter
}
// multicastPendingQuery is one group-specific delayed response. sourceQuery
// distinguishes an empty source intersection from a Group-Specific Query.
type multicastPendingQuery struct {
deadline time.Time
sources map[netip.Addr]struct{}
sourceQuery bool
}
// multicastQuery carries both the current-version and legacy linear response
// delay interpretations needed when a newer wire Query arrives while the
// interface remains in an older host compatibility mode.
type multicastQuery struct {
v6 bool
version uint8
group netip.Addr
sources []netip.Addr
maximum time.Duration
legacyMaximum time.Duration
robustness uint8
queryInterval time.Duration
}
// multicastRetransmission holds the RFC 9776 section 5.1 merge state for one
// interface group. Source counters survive successive changes until the
// configured robustness number of reports has carried each transition.
type multicastRetransmission struct {
filter multicastFilter
exists bool
lastReporter bool
modeRemaining uint8
allow map[netip.Addr]uint8
block map[netip.Addr]uint8
due time.Time
}
// multicastReportRecord is one IGMPv3 or MLDv2 group record snapshot.
type multicastReportRecord struct {
recordType byte
group netip.Addr
sources []netip.Addr
}
// multicastReportBatch is produced under the state lock and emitted without
// it, so bounded device-queue work never stalls membership or query handling.
type multicastReportBatch struct {
v6 bool
legacy uint8
group netip.Addr
exists bool
lastReporter bool
records []multicastReportRecord
cancel <-chan struct{}
}
// multicastQuerierState is the interface-wide querier state shared by the
// lightweight pre-membership seed and the complete membership dispatcher.
// Keeping it independent prevents an inbound Query by itself from retaining
// the report worker and serializers in binaries that never use multicast.
type multicastQuerierState struct {
robustness [2]uint8
queryInterval [2]time.Duration
responseInterval [2]time.Duration
compatibility [2]uint8
igmpV1Until time.Time
igmpV2Until time.Time
mldV1Until time.Time
}
// multicastQuerierSeed retains Queries received before the first membership.
// Stack.mu protects it; it has no goroutine, timer, or membership state.
type multicastQuerierSeed struct {
multicastQuerierState
}
// multicastState owns memberships for mipstack's single embedding interface.
// Stack.mu protects publication; mu protects the state after publication.
type multicastState struct {
stack *Stack
multicastQuerierState
mu sync.Mutex
groups map[netip.Addr]*multicastGroupState
retransmissions map[netip.Addr]*multicastRetransmission
familyGroups [2]int
generalQuery [2]time.Time
random uint64
wake chan struct{}
done chan struct{}
closeOnce sync.Once
closed bool
dispatch atomic.Pointer[multicastDispatchSnapshot]
reportCancel [2]chan struct{}
}
// defaultMulticastQuerierState returns the RFC default host variables.
func defaultMulticastQuerierState() multicastQuerierState {
return multicastQuerierState{
robustness: [2]uint8{multicastDefaultRobustness, multicastDefaultRobustness},
queryInterval: [2]time.Duration{multicastDefaultQueryInterval, multicastDefaultQueryInterval},
responseInterval: [2]time.Duration{multicastDefaultResponseInterval, multicastDefaultResponseInterval},
compatibility: [2]uint8{3, 2},
}
}
// newMulticastState constructs the lazily published membership dispatcher.
// The caller holds stack.mu, which also protects migration of multicastSeed.
func newMulticastState(stack *Stack) *multicastState {
querier := defaultMulticastQuerierState()
if stack.multicastSeed != nil {
querier = stack.multicastSeed.multicastQuerierState
querier.refresh(time.Now())
stack.multicastSeed = nil
}
state := &multicastState{
stack: stack, groups: make(map[netip.Addr]*multicastGroupState), retransmissions: make(map[netip.Addr]*multicastRetransmission),
multicastQuerierState: querier,
random: uint64(time.Now().UnixNano()) ^ sipHash24(stack.flowLabelSecret, []byte("multicast-report")),
wake: make(chan struct{}, 1), done: make(chan struct{}),
reportCancel: [2]chan struct{}{make(chan struct{}), make(chan struct{})},
}
state.dispatch.Store(&multicastDispatchSnapshot{groups: make(map[netip.Addr]*multicastGroupState)})
go state.run()
return state
}
// ListenMulticastUDP creates a reusable UDP socket, disables multicast
// loopback like net.ListenMulticastUDP, and joins group. Mipstack has one
// embedding interface, so no interface selector is required. Source-specific
// groups return EINVAL; use ListenConfig with SocketOptions.ReuseAddress and
// JoinSourceSpecificGroup.
func (s *Stack) ListenMulticastUDP(ctx context.Context, network string, group netip.AddrPort) (*UDPConn, error) {
group = netip.AddrPortFrom(group.Addr().Unmap(), group.Port())
target := net.UDPAddrFromAddrPort(group)
wrap := func(err error) (*UDPConn, error) {
return nil, socketOperationError("listen", network, nil, target, err)
}
if !group.IsValid() || !validMulticastGroup(group.Addr()) {
return wrap(syscall.EINVAL)
}
if err := validateListenNetwork(network, "udp", group.Addr()); err != nil {
return wrap(err)
}
localAddress := netip.IPv4Unspecified()
listenNetwork := network
if group.Addr().Is6() {
localAddress = netip.IPv6Unspecified()
if network == "udp" {
listenNetwork = "udp6"
}
} else if network == "udp" {
listenNetwork = "udp4"
}
listenConfig := ListenConfig{Options: []SocketOption{SocketOptions.ReuseAddress(true)}}
packetConnection, err := listenConfig.ListenUDP(ctx, s, listenNetwork, netip.AddrPortFrom(localAddress, group.Port()))
if err != nil {
return nil, err
}
connection := packetConnection.(*UDPConn)
if err = connection.SetMulticastLoopback(false); err == nil {
err = connection.JoinGroup(group.Addr())
}
if err != nil {
_ = connection.Close()
return wrap(err)
}
return connection, nil
}
// JoinGroup joins an any-source multicast group. It is the single-interface
// equivalent of MCAST_JOIN_GROUP and x/net's JoinGroup. RFC 4604 SSM groups
// return EINVAL and require JoinSourceSpecificGroup.
func (c *UDPConn) JoinGroup(group netip.Addr) error {
return c.changeMulticastMembership(multicastJoinAnySource, group, netip.Addr{})
}
// LeaveGroup leaves a multicast group regardless of its source-filter mode.
func (c *UDPConn) LeaveGroup(group netip.Addr) error {
return c.changeMulticastMembership(multicastLeaveGroup, group, netip.Addr{})
}
// JoinSourceSpecificGroup adds source to an INCLUDE-mode membership, creating
// the membership when this is its first source.
func (c *UDPConn) JoinSourceSpecificGroup(group, source netip.Addr) error {
return c.changeMulticastMembership(multicastJoinSource, group, source)
}
// LeaveSourceSpecificGroup removes source from an INCLUDE-mode membership. It
// leaves the group when source was its final entry.
func (c *UDPConn) LeaveSourceSpecificGroup(group, source netip.Addr) error {
return c.changeMulticastMembership(multicastLeaveSource, group, source)
}
// ExcludeSourceSpecificGroup blocks source on an existing any-source
// membership. It returns EINVAL for an SSM group.
func (c *UDPConn) ExcludeSourceSpecificGroup(group, source netip.Addr) error {
return c.changeMulticastMembership(multicastExcludeSource, group, source)
}
// IncludeSourceSpecificGroup removes a source block from an existing
// any-source membership. It returns EINVAL for an SSM group.
func (c *UDPConn) IncludeSourceSpecificGroup(group, source netip.Addr) error {
return c.changeMulticastMembership(multicastIncludeSource, group, source)
}
// SetBroadcast changes the SO_BROADCAST-equivalent output permission.
func (c *UDPConn) SetBroadcast(enabled bool) error {
c.mu.Lock()
defer c.mu.Unlock()
select {
case <-c.closed:
return c.setOperationError(net.ErrClosed)
default:
c.broadcast = enabled
return nil
}
}
// Broadcast reports the SO_BROADCAST-equivalent output permission.
func (c *UDPConn) Broadcast() (bool, error) {
c.mu.Lock()
defer c.mu.Unlock()
select {
case <-c.closed:
return false, c.setOperationError(net.ErrClosed)
default:
return c.broadcast, nil
}
}
// SetMulticastHopLimit changes the IPv4 multicast TTL or IPv6 multicast Hop
// Limit. Zero confines output to this host.
func (c *UDPConn) SetMulticastHopLimit(hopLimit int) error {
if hopLimit < 0 || hopLimit > 255 {
return c.setOperationError(syscall.EINVAL)
}
c.mu.Lock()
defer c.mu.Unlock()
select {
case <-c.closed:
return c.setOperationError(net.ErrClosed)
default:
c.multicastHopLimit = byte(hopLimit)
return nil
}
}
// MulticastHopLimit returns the IPv4 multicast TTL or IPv6 multicast Hop
// Limit used by subsequent writes.
func (c *UDPConn) MulticastHopLimit() (int, error) {
c.mu.Lock()
defer c.mu.Unlock()
select {
case <-c.closed:
return 0, c.setOperationError(net.ErrClosed)
default:
return int(c.multicastHopLimit), nil
}
}
// SetMulticastLoopback controls delivery of transmitted multicast packets to
// matching local memberships.
func (c *UDPConn) SetMulticastLoopback(enabled bool) error {
c.mu.Lock()
defer c.mu.Unlock()
select {
case <-c.closed:
return c.setOperationError(net.ErrClosed)
default:
c.multicastLoopback = enabled
return nil
}
}
// MulticastLoopback reports whether transmitted multicast packets are copied
// to matching local memberships.
func (c *UDPConn) MulticastLoopback() (bool, error) {
c.mu.Lock()
defer c.mu.Unlock()
select {
case <-c.closed:
return false, c.setOperationError(net.ErrClosed)
default:
return c.multicastLoopback, nil
}
}
// SetMulticastSourceFilter atomically replaces the complete INCLUDE/EXCLUDE
// source policy for a previously joined group. An empty INCLUDE filter leaves
// that membership, matching Linux MCAST_MSFILTER behavior. EXCLUDE returns
// EINVAL for an RFC 4604 SSM group.
func (c *UDPConn) SetMulticastSourceFilter(group netip.Addr, filter MulticastSourceFilter) error {
if c == nil || c.stack == nil {
return net.ErrClosed
}
if err := c.stack.setMulticastSourceFilter(c, group, filter); err != nil {
return c.setOperationError(err)
}
return nil
}
// MulticastSourceFilter returns the complete source policy for group.
func (c *UDPConn) MulticastSourceFilter(group netip.Addr) (MulticastSourceFilter, error) {
if c == nil || c.stack == nil {
return MulticastSourceFilter{}, net.ErrClosed
}
filter, err := c.stack.multicastSourceFilter(c, group)
if err != nil {
return MulticastSourceFilter{}, c.setOperationError(err)
}
return filter, nil
}
// JoinGroup joins an any-source multicast group for a raw protocol socket.
// RFC 4604 SSM groups return EINVAL and require JoinSourceSpecificGroup.
func (c *IPConn) JoinGroup(group netip.Addr) error {
return c.changeMulticastMembership(multicastJoinAnySource, group, netip.Addr{})
}
// LeaveGroup leaves a raw protocol socket's multicast group.
func (c *IPConn) LeaveGroup(group netip.Addr) error {
return c.changeMulticastMembership(multicastLeaveGroup, group, netip.Addr{})
}
// JoinSourceSpecificGroup adds source to an INCLUDE-mode raw membership,
// creating the membership when this is its first source.
func (c *IPConn) JoinSourceSpecificGroup(group, source netip.Addr) error {
return c.changeMulticastMembership(multicastJoinSource, group, source)
}
// LeaveSourceSpecificGroup removes source from an INCLUDE-mode raw membership.
// It leaves the group when source was its final entry.
func (c *IPConn) LeaveSourceSpecificGroup(group, source netip.Addr) error {
return c.changeMulticastMembership(multicastLeaveSource, group, source)
}
// ExcludeSourceSpecificGroup blocks source on an existing any-source raw
// membership. It returns EINVAL for an SSM group.
func (c *IPConn) ExcludeSourceSpecificGroup(group, source netip.Addr) error {
return c.changeMulticastMembership(multicastExcludeSource, group, source)
}
// IncludeSourceSpecificGroup removes a source block from an existing
// any-source raw membership. It returns EINVAL for an SSM group.
func (c *IPConn) IncludeSourceSpecificGroup(group, source netip.Addr) error {
return c.changeMulticastMembership(multicastIncludeSource, group, source)
}
// SetBroadcast changes the raw socket's SO_BROADCAST-equivalent permission.
func (c *IPConn) SetBroadcast(enabled bool) error {
c.mu.Lock()
defer c.mu.Unlock()
select {
case <-c.closed:
return c.setOperationError(net.ErrClosed)
default:
c.broadcast = enabled
return nil
}
}
// Broadcast reports the raw socket's SO_BROADCAST-equivalent permission.
func (c *IPConn) Broadcast() (bool, error) {
c.mu.Lock()
defer c.mu.Unlock()
select {
case <-c.closed:
return false, c.setOperationError(net.ErrClosed)
default:
return c.broadcast, nil
}
}
// SetMulticastHopLimit changes the raw socket's multicast TTL or Hop Limit.
func (c *IPConn) SetMulticastHopLimit(hopLimit int) error {
if hopLimit < 0 || hopLimit > 255 {
return c.setOperationError(syscall.EINVAL)
}
c.mu.Lock()
defer c.mu.Unlock()
select {
case <-c.closed:
return c.setOperationError(net.ErrClosed)
default:
c.multicastHopLimit = byte(hopLimit)
return nil
}
}
// MulticastHopLimit returns the raw socket's multicast TTL or Hop Limit.
func (c *IPConn) MulticastHopLimit() (int, error) {
c.mu.Lock()
defer c.mu.Unlock()
select {
case <-c.closed:
return 0, c.setOperationError(net.ErrClosed)
default:
return int(c.multicastHopLimit), nil
}
}
// SetMulticastLoopback controls raw multicast delivery to local memberships.
func (c *IPConn) SetMulticastLoopback(enabled bool) error {
c.mu.Lock()
defer c.mu.Unlock()
select {
case <-c.closed:
return c.setOperationError(net.ErrClosed)
default:
c.multicastLoopback = enabled
return nil
}
}
// MulticastLoopback reports whether raw multicast output is delivered locally.
func (c *IPConn) MulticastLoopback() (bool, error) {
c.mu.Lock()
defer c.mu.Unlock()
select {
case <-c.closed:
return false, c.setOperationError(net.ErrClosed)
default:
return c.multicastLoopback, nil
}
}
// SetMulticastSourceFilter atomically replaces a raw socket's complete
// INCLUDE/EXCLUDE source policy for a previously joined group. An empty
// INCLUDE filter leaves that membership. EXCLUDE returns EINVAL for an RFC
// 4604 SSM group.
func (c *IPConn) SetMulticastSourceFilter(group netip.Addr, filter MulticastSourceFilter) error {
if c == nil || c.stack == nil {
return net.ErrClosed
}
if err := c.stack.setMulticastSourceFilter(c, group, filter); err != nil {
return c.setOperationError(err)
}
return nil
}
// MulticastSourceFilter returns a raw socket's complete source policy.
func (c *IPConn) MulticastSourceFilter(group netip.Addr) (MulticastSourceFilter, error) {
if c == nil || c.stack == nil {
return MulticastSourceFilter{}, net.ErrClosed
}
filter, err := c.stack.multicastSourceFilter(c, group)
if err != nil {
return MulticastSourceFilter{}, c.setOperationError(err)
}
return filter, nil
}
// multicastEndpoint marks UDPConn as a membership owner.
func (*UDPConn) multicastEndpoint() {}
// multicastEndpoint marks IPConn as a membership owner.
func (*IPConn) multicastEndpoint() {}
// changeMulticastMembership applies one UDP membership operation.
func (c *UDPConn) changeMulticastMembership(operation multicastMembershipOperation, group, source netip.Addr) error {
if c == nil || c.stack == nil {
return net.ErrClosed
}
if err := c.stack.changeMulticastMembership(c, operation, group, source); err != nil {
return c.setOperationError(err)
}
return nil
}
// changeMulticastMembership applies one raw IP membership operation.
func (c *IPConn) changeMulticastMembership(operation multicastMembershipOperation, group, source netip.Addr) error {
if c == nil || c.stack == nil {
return net.ErrClosed
}
if err := c.stack.changeMulticastMembership(c, operation, group, source); err != nil {
return c.setOperationError(err)
}
return nil
}
// changeMulticastMembership validates endpoint ownership and serializes a
// membership update with socket removal.
func (s *Stack) changeMulticastMembership(endpoint multicastEndpoint, operation multicastMembershipOperation, group, source netip.Addr) error {
group, source = group.Unmap(), source.Unmap()
if !validMulticastGroup(group) {
return syscall.EINVAL
}
if isSourceSpecificMulticast(group) &&
(operation == multicastJoinAnySource || operation == multicastExcludeSource || operation == multicastIncludeSource) {
return syscall.EINVAL
}
if source.IsValid() && !validMulticastSourceSyntax(source, group.Is6()) {
return syscall.EINVAL
}
if operation >= multicastJoinSource && !source.IsValid() {
return syscall.EINVAL
}
s.mu.Lock()
if s.closed || !s.multicastEndpointRegisteredLocked(endpoint) {
s.mu.Unlock()
return net.ErrClosed
}
if !multicastEndpointSupportsGroup(endpoint, group) {
s.mu.Unlock()
return syscall.EAFNOSUPPORT
}
if source.IsValid() && !validMulticastSourceAddress(s.network.Load(), source, group.Is6()) {
s.mu.Unlock()
return syscall.EINVAL
}
state, ok := s.multicast.(*multicastState)
if !ok {
switch operation {
case multicastJoinAnySource, multicastJoinSource:
case multicastLeaveGroup:
s.mu.Unlock()
return syscall.EADDRNOTAVAIL
default:
s.mu.Unlock()
return syscall.EINVAL
}
state = newMulticastState(s)
s.multicast = state
}
err := state.change(endpoint, operation, group, source)
s.mu.Unlock()
if err == nil {
s.pruneFragments(s.network.Load())
}
return err
}
// setMulticastSourceFilter validates and installs one complete socket state.
func (s *Stack) setMulticastSourceFilter(endpoint multicastEndpoint, group netip.Addr, filter MulticastSourceFilter) error {
group = group.Unmap()
if !validMulticastGroup(group) ||
filter.Mode != MulticastSourceFilterInclude && filter.Mode != MulticastSourceFilterExclude {
return syscall.EINVAL
}
if filter.Mode == MulticastSourceFilterExclude && isSourceSpecificMulticast(group) {
return syscall.EINVAL
}
sources := make(map[netip.Addr]struct{}, len(filter.Sources))
for _, source := range filter.Sources {
source = source.Unmap()
if !validMulticastSourceSyntax(source, group.Is6()) {
return syscall.EINVAL
}
sources[source] = struct{}{}
}
mode := multicastFilterInclude
if filter.Mode == MulticastSourceFilterExclude {
mode = multicastFilterExclude
}
s.mu.Lock()
if s.closed || !s.multicastEndpointRegisteredLocked(endpoint) {
s.mu.Unlock()
return net.ErrClosed
}
if !multicastEndpointSupportsGroup(endpoint, group) {
s.mu.Unlock()
return syscall.EAFNOSUPPORT
}
network := s.network.Load()
for source := range sources {
if !validMulticastSourceAddress(network, source, group.Is6()) {
s.mu.Unlock()
return syscall.EINVAL
}
}
state, ok := s.multicast.(*multicastState)
if !ok {
s.mu.Unlock()
if mode == multicastFilterInclude && len(sources) == 0 {
return syscall.EADDRNOTAVAIL
}
return syscall.EINVAL
}
err := state.set(endpoint, group, mode, sources)
s.mu.Unlock()
if err == nil {
s.pruneFragments(s.network.Load())
}
return err
}
// validMulticastSourceAddress recognizes an RFC 3678 unicast source in the
// requested family, including the IPv4 broadcast exclusions known to this
// single interface.
func validMulticastSourceAddress(network *networkState, source netip.Addr, v6 bool) bool {
if !validMulticastSourceSyntax(source, v6) {
return false
}
source = source.Unmap()
if source.Is4() && network.broadcastDestination(source) {
return false
}
return true
}
// validMulticastSourceSyntax recognizes an unzoned unicast address in one
// address family without consulting configuration-dependent broadcast state.
func validMulticastSourceSyntax(source netip.Addr, v6 bool) bool {
source = source.Unmap()
return source.IsValid() && !source.IsUnspecified() && !source.IsMulticast() && source.Zone() == "" && source.Is6() == v6
}
// isSourceSpecificMulticast recognizes the IANA SSM ranges from RFC 4607:
// IPv4 232/8 and every valid IPv6 FF3x::/32 scope.
func isSourceSpecificMulticast(group netip.Addr) bool {
group = group.Unmap()
if !group.IsMulticast() {
return false
}
if group.Is4() {
return group.As4()[0] == 232
}
raw := group.As16()
return raw[1]>>4 == 3 && raw[2] == 0 && raw[3] == 0
}
// multicastSourceFilter snapshots one socket's current group state.
func (s *Stack) multicastSourceFilter(endpoint multicastEndpoint, group netip.Addr) (MulticastSourceFilter, error) {
group = group.Unmap()
if !validMulticastGroup(group) {
return MulticastSourceFilter{}, syscall.EINVAL
}
s.mu.RLock()
if s.closed || !s.multicastEndpointRegisteredLocked(endpoint) {
s.mu.RUnlock()
return MulticastSourceFilter{}, net.ErrClosed
}
state, ok := s.multicast.(*multicastState)
if !ok {
s.mu.RUnlock()
return MulticastSourceFilter{}, syscall.EADDRNOTAVAIL
}
state.mu.Lock()
s.mu.RUnlock()
groupState := state.groups[group]
var current *multicastFilter
if groupState != nil {
current = groupState.members[endpoint]
}
if current == nil {
state.mu.Unlock()
return MulticastSourceFilter{}, syscall.EADDRNOTAVAIL
}
mode := MulticastSourceFilterInclude
if current.mode == multicastFilterExclude {
mode = MulticastSourceFilterExclude
}
result := MulticastSourceFilter{Mode: mode, Sources: make([]netip.Addr, 0, len(current.sources))}
for source := range current.sources {
result.Sources = append(result.Sources, source)
}
state.mu.Unlock()
sort.Slice(result.Sources, func(left, right int) bool { return result.Sources[left].Compare(result.Sources[right]) < 0 })
return result, nil
}
// multicastEndpointRegisteredLocked reports whether endpoint is still owned
// by this stack while Stack.mu is held.
func (s *Stack) multicastEndpointRegisteredLocked(endpoint multicastEndpoint) bool {
switch connection := endpoint.(type) {
case *UDPConn:
key := udpKey{address: connection.local, port: connection.port}
if s.udp[key] == connection {
return true
}
flow := udpFlowKey{local: netip.AddrPortFrom(connection.local, connection.port), remote: connection.remote}
if s.udpForwarded[flow] == connection {
return true
}
return s.udpReuse != nil && s.udpReuse.contains(connection)
case *IPConn:
state, ok := s.ip.(*ipEndpointState)
return ok && state.contains(connection)
}
return false
}
// multicastEndpointSupportsGroup checks the immutable socket family policy.
func multicastEndpointSupportsGroup(endpoint multicastEndpoint, group netip.Addr) bool {
switch connection := endpoint.(type) {
case *UDPConn:
return connection.dual || connection.v6 == group.Is6()
case *IPConn:
return connection.dual || connection.v6 == group.Is6()
default:
return false
}
}
// change applies one membership delta and recomputes the RFC interface filter.
func (s *multicastState) change(endpoint multicastEndpoint, operation multicastMembershipOperation, group, source netip.Addr) error {
s.mu.Lock()
defer s.mu.Unlock()
groupState := s.groups[group]
old, oldExists := multicastInterfaceFilter(groupState)
oldLastReporter := groupState != nil && groupState.lastReporter
filter := (*multicastFilter)(nil)
if groupState != nil {
filter = groupState.members[endpoint]
}
existingFilter := filter != nil
switch operation {
case multicastJoinAnySource:
if filter != nil {
return syscall.EADDRINUSE
}
filter = &multicastFilter{mode: multicastFilterExclude, sources: make(map[netip.Addr]struct{})}
case multicastLeaveGroup:
if filter == nil {
return syscall.EADDRNOTAVAIL
}
case multicastJoinSource:
if filter == nil {
filter = &multicastFilter{mode: multicastFilterInclude, sources: make(map[netip.Addr]struct{})}
} else if filter.mode != multicastFilterInclude {
return syscall.EINVAL
}
if _, exists := filter.sources[source]; exists {
return syscall.EADDRINUSE
}
case multicastLeaveSource:
if filter == nil || filter.mode != multicastFilterInclude {
return syscall.EINVAL
}
if _, exists := filter.sources[source]; !exists {
return syscall.EADDRNOTAVAIL
}
case multicastExcludeSource:
if filter == nil || filter.mode != multicastFilterExclude {
return syscall.EINVAL
}
if _, exists := filter.sources[source]; exists {
return syscall.EADDRINUSE
}
case multicastIncludeSource:
if filter == nil || filter.mode != multicastFilterExclude {
return syscall.EINVAL
}
if _, exists := filter.sources[source]; !exists {
return syscall.EADDRNOTAVAIL
}
default:
return syscall.EINVAL
}
if existingFilter && operation != multicastLeaveGroup {
copied := cloneMulticastFilter(*filter)
if copied.sources == nil {
copied.sources = make(map[netip.Addr]struct{})
}
filter = &copied
}
if groupState == nil {
groupState = &multicastGroupState{members: make(map[multicastEndpoint]*multicastFilter)}
s.groups[group] = groupState
if multicastGroupNeedsReport(group) {
s.familyGroups[multicastFamilyIndex(group)]++
}
}
switch operation {
case multicastLeaveGroup:
delete(groupState.members, endpoint)
case multicastJoinSource, multicastExcludeSource:
filter.sources[source] = struct{}{}
groupState.members[endpoint] = filter
case multicastLeaveSource:
delete(filter.sources, source)
if len(filter.sources) == 0 {
delete(groupState.members, endpoint)
} else {
groupState.members[endpoint] = filter
}
case multicastIncludeSource:
delete(filter.sources, source)
groupState.members[endpoint] = filter
default:
groupState.members[endpoint] = filter
}
if len(groupState.members) == 0 {
s.removeGroupLocked(group)
} else {
groupState.aggregate = aggregateMulticastFilter(groupState.members)
}
s.interfaceStateChangedLocked(group, old, oldExists, oldLastReporter)
s.rebuildGroupDispatchLocked(group)
return nil
}
// set replaces one endpoint's complete filter and recomputes interface state.
func (s *multicastState) set(endpoint multicastEndpoint, group netip.Addr, mode multicastFilterMode, sources map[netip.Addr]struct{}) error {
s.mu.Lock()
defer s.mu.Unlock()
groupState := s.groups[group]
if groupState == nil || groupState.members[endpoint] == nil {
if mode == multicastFilterInclude && len(sources) == 0 {
return syscall.EADDRNOTAVAIL
}
// Linux's full-state source-filter API requires a prior ASM or SSM
// join before either filter mode can be installed.