Documentation
¶
Index ¶
- Constants
- Variables
- func BuildAMTRelayRdata(precedence uint8, dFlag bool, relayAddr netip.Addr) []byte
- func BuildDRIADQuery(sourceAddr netip.Addr) (string, error)
- func CGOVersion() string
- func CloseRelayManager(relayAddr net.UDPAddr) error
- func ControlMessageOOBLen() int
- func DiscoverRelay(ctx context.Context, config DRIADConfig) (*net.UDPAddr, error)
- func DiscoverRelays(ctx context.Context, config DRIADConfig) ([]*net.UDPAddr, error)
- func IsCGOAvailable() bool
- func ListenMulticastUDP4(network string, ifi *net.Interface, saddr netip.Addr, gaddr *net.UDPAddr, ...) (*ipv4.PacketConn, error)
- func ListenMulticastUDP6(network string, ifi *net.Interface, saddr netip.Addr, gaddr *net.UDPAddr, ...) (*ipv6.PacketConn, error)
- func MaxSegmentsPerSend(segmentSize int) int
- func PlatformInfo() string
- func PlatformUDPAvailable() bool
- func PureGoVersion() string
- func RegisterProtocol(typ ProtocolType, factory func() (AMTProtocol, error))
- func RegisterTransport(typ TransportType, factory func(TransportConfig) (Transport, error))
- func SegmentSize(oob []byte) int
- func SetForcedReceiveBuffer(fd int, bytes int) error
- func SetForcedSendBuffer(fd int, bytes int) error
- func ValidateConfiguration(cfg TransportConfig) error
- func Version() string
- func WaitRelayLeaves(ctx context.Context) error
- type AMTMode
- type AMTProtocol
- type AMTRelayRecord
- type AMTState
- type BufferClampedError
- type CGOProtocol
- func (p *CGOProtocol) Close()
- func (p *CGOProtocol) CreateDiscoveryMessage() ([]byte, error)
- func (p *CGOProtocol) CreateIGMPJoinReport(source, group netip.Addr) ([]byte, error)
- func (p *CGOProtocol) CreateIGMPJoinReportMulti(source netip.Addr, groups []netip.Addr) ([]byte, error)
- func (p *CGOProtocol) CreateIGMPLeaveReport(source, group netip.Addr) ([]byte, error)
- func (p *CGOProtocol) CreateIGMPSourceLeaveReport(source, group netip.Addr) ([]byte, error)
- func (p *CGOProtocol) CreateMembershipUpdate(igmpReport []byte) ([]byte, error)
- func (p *CGOProtocol) CreateRequestMessage(preferNative bool) ([]byte, error)
- func (p *CGOProtocol) CreateTeardownMessage() ([]byte, error)
- func (p *CGOProtocol) HandleAdvertisement(data []byte) error
- func (p *CGOProtocol) HandleQuery(data []byte) ([]byte, time.Duration, error)
- func (p *CGOProtocol) Initialize(relayAddr string, relayPort uint16) error
- func (p *CGOProtocol) Reset()
- func (p *CGOProtocol) State() AMTState
- type DRIADConfig
- type DataPacket
- type DecapStats
- type Gateway
- type ManagedConn
- func (mc *ManagedConn) Close() error
- func (mc *ManagedConn) IsUsingTunnel() bool
- func (mc *ManagedConn) LocalAddr() net.Addr
- func (mc *ManagedConn) Open() error
- func (mc *ManagedConn) ReadBatch(ms []ipv4.Message, flags int) (int, error)
- func (mc *ManagedConn) ReadFrom(p []byte) (n int, addr net.Addr, err error)
- func (mc *ManagedConn) ReadFromWithControlMessage(buf []byte) (n int, cm *ipv4.ControlMessage, src net.Addr, err error)
- func (mc *ManagedConn) RelayManager() *RelayManager
- func (mc *ManagedConn) SetDeadline(t time.Time) error
- func (mc *ManagedConn) SetReadDeadline(t time.Time) error
- func (mc *ManagedConn) SetWriteDeadline(t time.Time) error
- func (mc *ManagedConn) Stats() *ManagedConnStats
- func (mc *ManagedConn) Subscription() *Subscription
- func (mc *ManagedConn) WriteBatch(msg []ipv4.Message, flags int) (int, error)
- func (mc *ManagedConn) WriteTo(p []byte, addr net.Addr) (n int, err error)
- func (mc *ManagedConn) WriteToWithControlMessage(p []byte, cm *ipv4.ControlMessage, addr net.Addr) (n int, err error)
- type ManagedConnStats
- type MulticastConn
- func (mc *MulticastConn) Close() error
- func (mc *MulticastConn) EnableGRO() error
- func (mc *MulticastConn) IsUsingTunnel() bool
- func (mc *MulticastConn) LocalAddr() net.Addr
- func (mc *MulticastConn) Open() error
- func (mc *MulticastConn) ReadBatch(ms []ipv4.Message, flags int) (int, error)
- func (mc *MulticastConn) ReadFrom(p []byte) (n int, addr net.Addr, err error)
- func (mc *MulticastConn) ReadFromWithControlMessage(buf []byte) (n int, cm *ipv4.ControlMessage, src net.Addr, err error)
- func (mc *MulticastConn) SetDeadline(t time.Time) error
- func (mc *MulticastConn) SetMulticastLoopback(on bool) error
- func (mc *MulticastConn) SetReadDeadline(t time.Time) error
- func (mc *MulticastConn) SetWriteDeadline(t time.Time) error
- func (mc *MulticastConn) WriteBatch(msg []ipv4.Message, i int) (int, error)
- func (mc *MulticastConn) WriteSegments(b []byte, segmentSize int, cm *ipv4.ControlMessage, dst net.Addr) (int, error)
- func (mc *MulticastConn) WriteTo(p []byte, addr net.Addr) (n int, err error)
- func (mc *MulticastConn) WriteToWithControlMessage(b []byte, cm *ipv4.ControlMessage, dst net.Addr) (n int, err error)
- type Platform
- type PlatformCapabilities
- type ProtocolError
- type ProtocolFactory
- type ProtocolType
- type PureGoProtocol
- func (p *PureGoProtocol) Close()
- func (p *PureGoProtocol) CreateDiscoveryMessage() ([]byte, error)
- func (p *PureGoProtocol) CreateIGMPJoinReport(source, group netip.Addr) ([]byte, error)
- func (p *PureGoProtocol) CreateIGMPJoinReportMulti(source netip.Addr, groups []netip.Addr) ([]byte, error)
- func (p *PureGoProtocol) CreateIGMPLeaveReport(source, group netip.Addr) ([]byte, error)
- func (p *PureGoProtocol) CreateIGMPSourceLeaveReport(source, group netip.Addr) ([]byte, error)
- func (p *PureGoProtocol) CreateMembershipUpdate(igmpReport []byte) ([]byte, error)
- func (p *PureGoProtocol) CreateRequestMessage(preferNative bool) ([]byte, error)
- func (p *PureGoProtocol) CreateTeardownMessage() ([]byte, error)
- func (p *PureGoProtocol) HandleAdvertisement(data []byte) error
- func (p *PureGoProtocol) HandleQuery(data []byte) ([]byte, time.Duration, error)
- func (p *PureGoProtocol) Initialize(relayAddr string, relayPort uint16) error
- func (p *PureGoProtocol) Reset()
- func (p *PureGoProtocol) State() AMTState
- type RelayManager
- func (rm *RelayManager) Close() error
- func (rm *RelayManager) Open(ctx context.Context) error
- func (rm *RelayManager) State() RelayState
- func (rm *RelayManager) Stats() RelayManagerStats
- func (rm *RelayManager) Subscribe(key SubscriptionKey, callbacks SubscriptionCallbacks) (*Subscription, error)
- func (rm *RelayManager) Unsubscribe(key SubscriptionKey) error
- func (rm *RelayManager) WaitLeaves(ctx context.Context) error
- type RelayManagerConfig
- type RelayManagerStats
- type RelayState
- type SourceSpecificLeaveReporter
- type Subscription
- type SubscriptionCallbacks
- type SubscriptionKey
- type SubscriptionState
- type SubscriptionStats
- type Transport
- type TransportConfig
- type TransportError
- type TransportType
- type UDPTransport
- func (t *UDPTransport) AdoptAdvertisedRelay(data []byte)
- func (t *UDPTransport) Close() error
- func (t *UDPTransport) Conn() *ipv4.PacketConn
- func (t *UDPTransport) LocalAddr() net.Addr
- func (t *UDPTransport) Open(ctx context.Context) error
- func (t *UDPTransport) ReadBatch(ms []ipv4.Message, flags int) (int, error)
- func (t *UDPTransport) Receive(buf []byte) (n int, addr net.Addr, err error)
- func (t *UDPTransport) RelayAddr() net.Addr
- func (t *UDPTransport) Send(data []byte) error
- func (t *UDPTransport) SetReadDeadline(deadline time.Time) error
- func (t *UDPTransport) SupportsTimestamp() bool
- func (t *UDPTransport) Type() TransportType
- func (t *UDPTransport) WriteBatch(ms []ipv4.Message, flags int) (int, error)
Constants ¶
const ( ControlFlags4 ipv4.ControlFlags = ipv4.FlagDst | ipv4.FlagInterface | ipv4.FlagTTL ControlFlags6 ipv6.ControlFlags = ipv6.FlagDst | ipv6.FlagInterface | ipv6.FlagHopLimit )
ControlFlags4 and ControlFlags6 are the control-message flag sets every native group join in this package requests. They are exported because a caller cannot size the OOB buffer it hands ReadBatch without them, and every listen call here consumes these constants rather than a local copy.
Getting that buffer too small fails silently, which is why this is exported rather than documented: the kernel sets MSG_CTRUNC and drops whichever cmsgs did not fit. The first casualty is Dst, so a receiver filtering datagrams by destination group then discards all of them, with no error on any surface. Restating the sets at the caller works right up until a flag is added here — no build break, because there was never a shared symbol for the compiler to check. multicast's lct.ControlMessageOOBLen carried exactly that copy, and its v6 arm summed to 96 bytes against a 96-byte buffer: one more v6 cmsg upstream and IPv6 goes dark (BLO-34983).
These are the IP-level cmsgs only. To size a buffer, use ControlMessageOOBLen, which adds the SOL_SOCKET and IPPROTO_UDP terms these flags cannot reach.
Untagged on purpose. The listen calls that consume these are behind platform and cgo constraints, but the callers that must size a buffer are not, and a consumer whose own build tags do not line up with conn.go's would otherwise be pushed straight back to a local copy.
const ( // AMTRELAY DNS record type (RFC 8777) DNSTypeAMTRELAY uint16 = 260 // Default DNS timeout DefaultDNSDTimeout = 5 * time.Second // DRIAD domain suffix DRIADSuffix = "in-addr.arpa." )
DRIAD constants per RFC 8777
const DefaultOpenTimeout = 10 * time.Second
DefaultOpenTimeout bounds the relay handshake when Gateway.Timeout is unset.
const GROControlMessageLen = 24
GROControlMessageLen is the OOB space the UDP_GRO control message occupies on a socket MulticastConn.EnableGRO succeeded on.
A third exported term for the same reason TimestampControlMessageLen is a second one: the option is IPPROTO_UDP, so it is as unreachable from ipv4.ControlFlags and ipv6.ControlFlags as the SOL_SOCKET one is. A caller sizing from the flag sets alone is short by exactly this much and the kernel truncates silently.
Counted unconditionally, even though GRO is opt-in per connection, on the same grounds as the timestamp term: 24 bytes per slot costs nothing, and a length that varied by which options a caller had enabled would put the caller back in the business of tracking what this package set. It also means EnableGRO can be called on an already-running receiver without every OOB buffer in the process having to be resized first -- which, since the cost of getting that ordering wrong is MSG_CTRUNC and a silently dark group filter, is the difference between an opt-in and a flag day.
24 is CmsgSpace(4) on a 64-bit ABI: udp_cmsg_recv reports the segment size as an int. TestGROControlMessageLenMatchesTheABI checks that against unix.CmsgSpace instead of trusting the literal.
const MinRelayHandshakeTimeout = 2 * handshakeRetransmit
MinRelayHandshakeTimeout is the shortest value of the operator's relay timeout that is plausibly a handshake bound rather than a typo.
amt_relay_timeout is an overloaded knob: it sized the native probe window and was also handed to Gateway.Timeout as the AMT relay handshake bound. The production 50ms therefore did double damage — it destroyed the native join and then gave the relay handshake 50ms to complete a round trip, so the tunnel that replaced native could not come up either.
It is two retransmit intervals, not one. The first resend is due one interval in, and a bound that ends there fails the handshake before it fires, so one lost datagram would fail Open again (BLO-43016).
const MinUsefulProbeWindow = 10 * time.Second
MinUsefulProbeWindow is the shortest read window that can distinguish "native multicast does not work here" from "the next packet has not arrived yet".
The signalling sender emits the SLT once per interval and floors that interval at 5s (multicast/lls/server.go:29-31). A window shorter than one full interval therefore proves nothing: it expires in the gap between two packets of a perfectly healthy stream. Two intervals gives a healthy native path a second chance to be seen if the first packet is missed.
The latency this can add is only ever paid when native is genuinely dead: a working native path answers the probe as soon as its next packet arrives, and content channels carry data far faster than the signalling cadence.
const SegmentSizeUnreadable = -1
SegmentSizeUnreadable is returned by SegmentSize when a slot carries a UDP_GRO control message whose payload is not the size this package knows how to read.
It is a distinct value from 0 because the two demand opposite handling and confusing them corrupts the stream silently. 0 means no GRO cmsg was present, so the buffer is one datagram and reading it whole is correct. This value means the kernel DID coalesce -- the buffer holds several datagrams back-to-back -- but the segment size could not be read, so reading it whole would hand the caller one oversized frame built from several real ones, with no error on any surface. A caller seeing this must fail the read, not fall back.
Reaching it requires the kernel's cmsg payload to stop being a 4-byte int, which is an ABI change rather than a runtime condition; TestGROControlMessageLenMatchesTheABI and TestGROCmsgPayloadIsFourBytes pin both halves of that against the running kernel so the drift is caught in CI rather than here. It exists anyway because this is a parse of kernel-supplied bytes on the path that frames every received datagram, and the failure direction without it is silent.
const TimestampControlMessageLen = 32
TimestampControlMessageLen is the OOB space the one timestamp control message occupies on a socket opened with MulticastConfig.Timestamp set.
It is a separate exported term, rather than another bit in the sets above, because it is structurally unreachable from them. The option this package sets is SOL_SOCKET — SO_TIMESTAMPNS with an SO_TIMESTAMP fallback on linux, SO_TIMESTAMP on darwin and mobile — while ipv4.ControlFlags and ipv6.ControlFlags are closed types carrying only IP-level bits (x/net/ipv6 has exactly FlagTrafficClass, FlagHopLimit, FlagSrc, FlagDst, FlagInterface, FlagPathMTU). There is no value a caller could OR in to account for it, so a caller sizing from the flag sets alone is short by exactly this much and the kernel silently truncates — which is the failure BLO-34983 exists to close, surviving inside the fix for it until this term was exported too.
32 is CmsgSpace(16) on a 64-bit ABI: both options carry a 16-byte payload, timespec for SCM_TIMESTAMPNS and timeval for SCM_TIMESTAMP. TestTimestampControlMessageLenMatchesTheABI checks that against unix.CmsgSpace instead of trusting the literal, and TestTimestampSockoptsAreAllAccountedFor fails if a listen file starts setting one this number does not cover — SO_TIMESTAMPING is the live example, three timespecs at CmsgSpace(48) = 64.
const ( // UDPMaxSegments is the kernel's cap on segments per GSO send. Measured on // the staging sender node (Talos, kernel 6.18) by bisecting the boundary: // 128 x 400B succeeded in one call, 129 x 400B returned EINVAL. Linux has // historically documented 64; do not substitute that value without // re-measuring. // // A kernel whose real cap is lower stays correct: its EINVAL is classified // as ErrSegmentsUnsupported and the caller falls back, with nothing on the // wire either time. But it is not free -- every batch above its real cap // then pays a doomed syscall before falling back, which is the per-packet // syscall cost this whole path exists to remove. That is why // TestUDPMaxSegmentsMatchesKernel asserts this value against the running // kernel in both directions and fails rather than skipping: a silently // overstated cap is a permanent slow path that no other test can see. UDPMaxSegments = 128 )
Variables ¶
var ErrGROUnsupported = errors.New("amt: udp gro unsupported")
ErrGROUnsupported reports that UDP GRO could not be enabled on this connection. It is the caller's signal to read datagram-per-slot as it always has; it never means the socket was left in a half-configured state. Callers select that fallback with errors.Is rather than by string match, the same way ErrSegmentsUnsupported works on the send side.
GRO is the receive-side counterpart of the UDP_SEGMENT write in gso.go and has the same justification: both are IPPROTO_UDP socket options, and x/net's ipv4.ControlMessage marshals IP-level options only, so neither can be expressed through the ReadBatch/WriteBatch signatures themselves.
var ErrSegmentsPartial = errors.New("amt: segmented write partially accepted")
ErrSegmentsPartial reports that the kernel accepted only part of a segmented buffer. It is NOT retryable: the accepted prefix is already on the wire, so re-sending the same buffer would duplicate those datagrams on a live group. A caller seeing this must surface it, not fall back.
No probe on kernel 6.18 has produced this — sendmsg(2) on a datagram socket is all-or-nothing — but the analogous partial accept on sendmmsg(2) is real (a count and an error can be returned together), so this is reported as its own condition rather than silently rounded to success.
var ErrSegmentsUnsupported = errors.New("amt: segmented write unsupported")
ErrSegmentsUnsupported reports that a segmented (UDP GSO) write cannot be attempted for this connection or this batch. It is the caller's signal to fall back to WriteBatch or per-datagram WriteTo; it never means the write half-happened. Every refusal below returns an error wrapping this sentinel, so callers select the fallback with errors.Is rather than by string match.
Functions ¶
func BuildAMTRelayRdata ¶
BuildAMTRelayRdata builds AMTRELAY RDATA for a relay address
func BuildDRIADQuery ¶
BuildDRIADQuery builds the DNS query name for DRIAD discovery (RFC 8777) For IPv4 source 192.0.2.1, returns: 1.2.0.192.in-addr.arpa. For IPv6 source, returns: nibble-reversed format in ip6.arpa.
func CloseRelayManager ¶
CloseRelayManager closes and removes a RelayManager from the registry
func ControlMessageOOBLen ¶
func ControlMessageOOBLen() int
ControlMessageOOBLen returns the per-slot OOB buffer length a ReadBatch caller must allocate to receive everything a socket opened by this package can emit.
This, not the flag sets, is what a caller should size from. Every term is owned here — the IP-level cmsgs by ControlFlags4/6, the SOL_SOCKET one by TimestampControlMessageLen and the IPPROTO_UDP one by GROControlMessageLen — so a cmsg added on any axis reaches the caller's buffer on its next pin bump with no edit at the caller, which is the whole point (BLO-34983). Exporting only the flag sets left the timestamp term as a hand-mirror at the caller, i.e. one instance of the drift class the export was meant to retire.
The larger of the two families, because a caller allocating one buffer size for slots it will hand to either family cannot know the family in advance. v6's cmsgs are 8 bytes wider, so sizing from v4 alone truncates Dst on a v6 datagram and a group filter then discards all of it.
Unconditionally includes the timestamp and GRO terms, even though both are per-config: over-allocating 56 bytes per slot costs nothing, and a length that varied by config would put the caller back in the business of tracking which options this package set.
A function and not an exported var. It cannot be a const — len of a call is not constant — and an exported var is assignable by any importer, which is the one way a consumer silently un-sizes every OOB buffer in the process and lands back on the exact MSG_CTRUNC path this symbol exists to close. Nothing would catch that: not the compiler, not vet, not the guards in control_oob_len_test.go, which read the same var the assignment clobbered. A package that exports a length to stop a silent truncation does not get to leave a one-assignment hole into it.
func DiscoverRelay ¶
DiscoverRelay performs DRIAD discovery for the given source address Returns the discovered relay address and port
func DiscoverRelays ¶
DiscoverRelays performs DRIAD discovery and returns every relay the source advertises, in the order a gateway should try them (see OrderRelays). DiscoverRelay returns only the first, which leaves a gateway with no answer when that relay is down even though the source listed others; a caller that walks the whole slice gets precedence-respecting failover.
That failover is connect-time only. RelayManager.Open walks these candidates until one completes a handshake; once a tunnel is up, a relay that dies mid-session is retried by reconnectWithBackoff against the same address rather than falling through to the next candidate. A caller that needs the steady state to move relays has to re-run discovery itself.
func IsCGOAvailable ¶
func IsCGOAvailable() bool
IsCGOAvailable returns true if CGO protocol is available
func ListenMulticastUDP4 ¶
func ListenMulticastUDP4(network string, ifi *net.Interface, saddr netip.Addr, gaddr *net.UDPAddr, f []bpf.RawInstruction, timestamp bool, ttl int, flags4 ipv4.ControlFlags, rcvBufBytes int, sndBufBytes int) (*ipv4.PacketConn, error)
ListenMulticastUDP4 listens for multicast UDP packets sent to gaddr. It binds gaddr itself, not 0.0.0.0, and receives only the group it joins (see IP_MULTICAST_ALL and the bind below).
func ListenMulticastUDP6 ¶
func ListenMulticastUDP6(network string, ifi *net.Interface, saddr netip.Addr, gaddr *net.UDPAddr, f []bpf.RawInstruction, timestamp bool, hoplimit int, flags6 ipv6.ControlFlags, rcvBufBytes int, sndBufBytes int) (*ipv6.PacketConn, error)
ListenMulticastUDP6 is the IPv6 counterpart of ListenMulticastUDP4. It binds an AF_INET6 UDP socket and issues a source-specific (MLDv2) join for the given (source, group) pair, falling back to an any-source (ASM) join when no source is supplied.
func MaxSegmentsPerSend ¶
MaxSegmentsPerSend reports how many segments of segmentSize one WriteSegments call may carry. A caller with more packets than that splits them across several segmented sends; it does not drop to a per-datagram fallback, which is for GSO being unavailable, not for a batch being large.
This is exported rather than the two constants behind it because both bounds bind at once -- UDPMaxSegments on the count and maxSegmentedPayloadBytes on the aggregate -- and which one binds depends on segmentSize. At 400B the count binds (128 segments, 51,200B); at 1366B the aggregate binds (47 segments, 64,202B, where 128 would be 174,848B). A caller handed only UDPMaxSegments would build a batch the kernel refuses with EMSGSIZE at every segment size above 511 bytes -- correct, because WriteSegments rejects it and nothing reaches the wire, but it pays a doomed syscall per batch, which is the per-packet syscall cost this path exists to remove.
Returns 0 when no segmented send is possible on aggregate grounds, i.e. segmentSize is non-positive or on its own exceeds the aggregate limit. MTU is a third way a size is unsendable and this function cannot see it: MaxSegmentsPerSend(8192) is 7, while WriteSegments on a 1500-byte path refuses 8192 outright, so a nonzero return is not on its own permission to send. Treat 0 as "do not segment" and never as a count -- as a loop stride it does not misbehave, it hangs.
func PlatformInfo ¶
func PlatformInfo() string
PlatformInfo returns a human-readable description of the platform
func PlatformUDPAvailable ¶
func PlatformUDPAvailable() bool
PlatformUDPAvailable returns true - UDP is available on all platforms
func PureGoVersion ¶
func PureGoVersion() string
PureGoVersion returns version info for the pure Go implementation
func RegisterProtocol ¶
func RegisterProtocol(typ ProtocolType, factory func() (AMTProtocol, error))
RegisterProtocol registers a protocol factory
func RegisterTransport ¶
func RegisterTransport(typ TransportType, factory func(TransportConfig) (Transport, error))
RegisterTransport registers a transport factory
func SegmentSize ¶
SegmentSize reports the UDP GRO segment size for one ReadBatch slot, read from the control message the kernel attaches when it coalesced several datagrams into that slot. oob is the slot's control buffer truncated to the length the read reported, i.e. ms[i].OOB[:ms[i].NN].
Returns 0 when the slot carries no GRO control message. That is the common case and it means exactly one datagram arrived, so the whole buffer is that datagram -- the kernel attaches the cmsg only when it actually coalesced. A caller therefore needs no "is GRO on" flag at the read site: 0 and "GRO disabled" are the same instruction.
That reading of 0 holds only on a slot whose read did not set MSG_CTRUNC, and the caller must check ms[i].Flags for it. Truncation is reported out of band, never inside oob: the kernel drops whole control messages and shortens msg_controllen, so what survives still parses and a dropped GRO cmsg is indistinguishable here from one that was never attached. Acting on 0 after a truncated read frames a coalesced run as one oversized datagram -- the same silent corruption SegmentSizeUnreadable exists to prevent on the malformed payload path, reached by a route this parse cannot see. Sizing the buffer with ControlMessageOOBLen makes it unreachable; a caller that hand-mirrors that length is short by exactly GROControlMessageLen.
A positive n means the slot holds ceil(len/n) datagrams laid out back-to-back, every one exactly n bytes except the last, which may be shorter. That is the same layout WriteSegments sends, by construction.
Returns SegmentSizeUnreadable when a GRO cmsg is present but its payload is not readable; see that constant for why this is not folded into 0.
func SetForcedReceiveBuffer ¶
SetForcedReceiveBuffer raises the socket receive buffer so the kernel accepts a setsockopt input of at least bytes. It is a no-op when bytes <= 0 or when the socket already holds that much.
It first tries SO_RCVBUFFORCE, which bypasses net.core.rmem_max but requires CAP_NET_ADMIN in the socket's network namespace user namespace. On EPERM it falls back to SO_RCVBUF (capped at net.core.rmem_max). If the fallback is clamped below the request, the error is a *BufferClampedError so callers can choose to warn-and-continue.
func SetForcedSendBuffer ¶
SetForcedSendBuffer is the send-side counterpart of SetForcedReceiveBuffer.
func ValidateConfiguration ¶
func ValidateConfiguration(cfg TransportConfig) error
ValidateConfiguration validates a configuration for the current platform
func WaitRelayLeaves ¶
WaitRelayLeaves runs WaitLeaves on every registered RelayManager.
Types ¶
type AMTMode ¶
type AMTMode int
AMTMode selects how MulticastConn.Open chooses between a native multicast join and an AMT tunnel.
This file deliberately carries no build tags. The decision it encodes is pure policy — no sockets, no cgo — so it compiles and is unit-tested under every build configuration, including the CGO_ENABLED=0 and purego CI jobs that deselect conn.go entirely.
const ( // AMTModeAuto keeps the historical inference: a configured relay makes the // native join provisional, and Open falls back to an AMT tunnel when the // native path produces no traffic inside the probe window. This is the zero // value, so callers that do not set Mode keep the previous behaviour. AMTModeAuto AMTMode = iota // AMTModeNative never tunnels. The native join is kept unconditionally and a // configured relay address is treated as "a relay exists here", not "use it". // Use this when the operator knows native multicast is deliverable. AMTModeNative // AMTModeTunnel goes straight to the AMT tunnel without probing, because a // probe cannot tell the operator anything they have not already decided. // A relay address is required; without one this degrades to native. AMTModeTunnel )
type AMTProtocol ¶
type AMTProtocol interface {
// Initialize sets up the protocol state for a relay
Initialize(relayAddr string, relayPort uint16) error
// CreateDiscoveryMessage creates an AMT Relay Discovery message
CreateDiscoveryMessage() ([]byte, error)
// HandleAdvertisement processes an AMT Relay Advertisement response
HandleAdvertisement(data []byte) error
// CreateRequestMessage creates an AMT Request message
CreateRequestMessage(preferNative bool) ([]byte, error)
// HandleQuery processes an AMT Membership Query and returns IGMP data
HandleQuery(data []byte) (igmpData []byte, intervalTime time.Duration, err error)
// CreateIGMPJoinReport creates an IGMPv3 SSM join report for a single (S,G)
CreateIGMPJoinReport(source, group netip.Addr) ([]byte, error)
// CreateIGMPJoinReportMulti creates an IGMPv3 report for multiple groups from same source
CreateIGMPJoinReportMulti(source netip.Addr, groups []netip.Addr) ([]byte, error)
// CreateIGMPLeaveReport creates an IGMPv3 report that leaves one (S,G) pair.
CreateIGMPLeaveReport(source, group netip.Addr) ([]byte, error)
// CreateMembershipUpdate creates an AMT Membership Update message with IGMP report
//
// Precondition, and it is the same for both implementations: a Membership
// Query must have been processed by HandleQuery, so a response MAC is
// available. There is deliberately NO further state precondition — an
// Update is valid for every membership change on a live tunnel, not just
// the first one after a Query. RFC 7450 §4.2.1.2: the nonce and MAC are
// taken from the last Membership Query, and subsequent report/leave
// messages are "immediately encapsulated and transmitted to the relay".
//
// This contract is stated here because the two implementations disagreed
// on it (BLO-28805): the Rust FFI path guarded on Querying and consumed it,
// making the call single-shot per Query, so every leave and every second
// join failed with InvalidState while the pure-Go path succeeded.
//
// "The same for both implementations" is a claim about this precondition,
// not blanket parity. The IGMP encapsulation is not fully in agreement: a
// join report's IPv4 destination is the multicast group on the Rust path
// and 224.0.0.22 on the pure-Go one (BLO-29419). The IHL, Router Alert
// option, total length and header checksum are pinned across
// implementations by TestIGMPEnvelopeParityAcrossImplementations; the TTL,
// protocol byte and source address are asserted nowhere, so they are not
// pinned either.
//
// igmpReport must be non-empty. The implementations diverge on an empty
// slice rather than agreeing on an error: the cgo path takes
// &igmpReport[0] (protocol_cgo.go:279) and panics, where pure-Go marshals
// it into an empty Encapsulated field. No caller can reach it today —
// every CreateIGMP*Report builder returns a non-empty slice on success —
// so this is a documented precondition rather than a latent panic, and a
// new caller should treat it as one.
CreateMembershipUpdate(igmpReport []byte) ([]byte, error)
// CreateTeardownMessage creates an AMT Teardown message
CreateTeardownMessage() ([]byte, error)
// Reset resets the protocol state to idle
Reset()
// State returns the current protocol state
State() AMTState
// Close frees protocol resources
Close()
}
AMTProtocol abstracts the AMT protocol implementation. Implementations: - CGOProtocol: Uses Rust library via CGO (Linux/macOS desktop) - PureGoProtocol: Pure Go implementation (all platforms)
func DefaultProtocol ¶
func DefaultProtocol() (AMTProtocol, error)
DefaultProtocol creates the default protocol for the current platform
func NewProtocol ¶
func NewProtocol(typ ProtocolType) (AMTProtocol, error)
NewProtocol creates a protocol of the specified type
type AMTRelayRecord ¶
type AMTRelayRecord struct {
// Precedence indicates priority (lower = higher priority)
Precedence uint8
// DFlag indicates if the relay supports DRIAD discovery itself
DFlag bool
// RelayType indicates the type of relay address
// 0 = reserved, 1 = IPv4, 2 = IPv6, 3 = domain name
RelayType uint8
// RelayAddr is the relay address (IP or domain name)
RelayAddr string
// ResolvedAddr is the resolved IP address (if RelayType is domain name)
ResolvedAddr netip.Addr
}
AMTRelayRecord represents a parsed AMTRELAY DNS record (RFC 8777)
func OrderRelays ¶
func OrderRelays(records []AMTRelayRecord, shuffle func(n int, swap func(i, j int))) []AMTRelayRecord
OrderRelays returns the records in the order a gateway should try them: lowest precedence first, with the order randomized within each precedence. RFC 8777 §3.1.2 has a gateway choose non-deterministically among equal-precedence relays so that DNS configurations listing several relays can spread load. Taking the first relay in wire order instead sends every gateway behind one resolver cache to the same relay. Walking the result in order also gives precedence-respecting failover. shuffle has the signature of rand.Shuffle. records is not modified.
func ParseAMTRelayRdata ¶
func ParseAMTRelayRdata(rdata []byte) (*AMTRelayRecord, error)
ParseAMTRelayRdata parses raw AMTRELAY RDATA bytes
type BufferClampedError ¶
BufferClampedError reports that a socket buffer size request was accepted but clamped below what was asked for — typically because the process lacks CAP_NET_ADMIN (so SO_RCVBUFFORCE/SO_SNDBUFFORCE returned EPERM) AND net.core.rmem_max / net.core.wmem_max is below the request. Callers can errors.As to detect this and log a warning while continuing.
Requested is the setsockopt input. Got is the raw getsockopt readback, which on Linux is TWICE the accepted input — so Got can exceed Requested and still be a clamp. EffectiveCeiling unhalves it into the same units as Requested, which is the number an operator compares against rmem_max.
Darwin has no FORCE variant. Its kernel clamps an oversized SO_RCVBUF/SO_SNDBUF to kern.ipc.maxsockbuf without an error on macOS 14.4 and later, and refuses it with ENOBUFS on earlier releases. setXNUBufferAtLeast handles both and reads the size back, and returns this error with Got set to that readback. Darwin's getsockopt does not double, so there EffectiveCeiling is Got itself.
func (*BufferClampedError) EffectiveCeiling ¶
func (e *BufferClampedError) EffectiveCeiling() int
EffectiveCeiling is the accepted setsockopt input implied by the readback — i.e. the net.core.{r,w}mem_max (Linux) or kern.ipc.maxsockbuf-derived (Darwin) limit the kernel held the request to — in the same units as Requested.
func (*BufferClampedError) Error ¶
func (e *BufferClampedError) Error() string
type CGOProtocol ¶
type CGOProtocol struct {
// contains filtered or unexported fields
}
CGOProtocol implements AMTProtocol using the Rust library via CGO. Only available on Linux/macOS desktop (not iOS/Android).
func NewCGOProtocol ¶
func NewCGOProtocol() (*CGOProtocol, error)
NewCGOProtocol creates a new CGO-based protocol instance
func (*CGOProtocol) Close ¶
func (p *CGOProtocol) Close()
func (*CGOProtocol) CreateDiscoveryMessage ¶
func (p *CGOProtocol) CreateDiscoveryMessage() ([]byte, error)
func (*CGOProtocol) CreateIGMPJoinReport ¶
func (p *CGOProtocol) CreateIGMPJoinReport(source, group netip.Addr) ([]byte, error)
func (*CGOProtocol) CreateIGMPJoinReportMulti ¶
func (*CGOProtocol) CreateIGMPLeaveReport ¶
func (p *CGOProtocol) CreateIGMPLeaveReport(source, group netip.Addr) ([]byte, error)
func (*CGOProtocol) CreateIGMPSourceLeaveReport ¶
func (p *CGOProtocol) CreateIGMPSourceLeaveReport(source, group netip.Addr) ([]byte, error)
func (*CGOProtocol) CreateMembershipUpdate ¶
func (p *CGOProtocol) CreateMembershipUpdate(igmpReport []byte) ([]byte, error)
func (*CGOProtocol) CreateRequestMessage ¶
func (p *CGOProtocol) CreateRequestMessage(preferNative bool) ([]byte, error)
func (*CGOProtocol) CreateTeardownMessage ¶
func (p *CGOProtocol) CreateTeardownMessage() ([]byte, error)
func (*CGOProtocol) HandleAdvertisement ¶
func (p *CGOProtocol) HandleAdvertisement(data []byte) error
func (*CGOProtocol) HandleQuery ¶
func (*CGOProtocol) Initialize ¶
func (p *CGOProtocol) Initialize(relayAddr string, relayPort uint16) error
func (*CGOProtocol) Reset ¶
func (p *CGOProtocol) Reset()
func (*CGOProtocol) State ¶
func (p *CGOProtocol) State() AMTState
type DRIADConfig ¶
type DRIADConfig struct {
// SourceAddr is the multicast source address to discover relay for
SourceAddr netip.Addr
// DNSServers is a list of DNS servers to query (optional, uses system default if empty)
DNSServers []string
// Timeout for DNS queries
Timeout time.Duration
}
DRIADConfig contains configuration for DRIAD discovery
func DefaultDRIADConfig ¶
func DefaultDRIADConfig(sourceAddr netip.Addr) DRIADConfig
DefaultDRIADConfig returns a config with sensible defaults
type DataPacket ¶
DataPacket represents a received multicast data packet
type DecapStats ¶
type DecapStats struct {
// Fragments is the inner IPv4 fragments received. The relay sends each
// fragment of a datagram larger than the path MTU as its own data message.
Fragments uint64
// Reassembled is the UDP datagrams rebuilt from them.
Reassembled uint64
// ReassemblyExpired is the datagrams dropped incomplete: a fragment did not
// arrive within reassemblyTimeout, or the datagram was evicted to stay under
// maxReassemblies.
ReassemblyExpired uint64
// ReassemblyInvalid is the datagrams dropped whole for overlapping,
// inconsistent or oversized fragments.
ReassemblyInvalid uint64
// Truncated is the inner packets cut short of, or inconsistent with, the
// lengths their IP and UDP headers give. None is delivered.
Truncated uint64
// Unsupported is the inner packets that are not UDP, and the IPv6 ones
// with an extension header between the fixed header and UDP. A Fragment
// header is one of those, so an IPv6 fragment is counted here rather than
// reassembled.
Unsupported uint64
}
DecapStats counts the inner packets of AMT Multicast Data messages that the data path reassembled or could not deliver as they arrived.
type Gateway ¶
type Gateway struct {
RelayAddr net.Addr
SourceAddr net.IP
GroupAddr net.IP
MTU int
// RcvBufBytes and SndBufBytes are forwarded to the AMT relay UDP socket;
// see MulticastConn for semantics.
RcvBufBytes int
SndBufBytes int
// Timeout bounds the relay handshake in Open: discovery is sent, then the
// relay advertisement and membership query must arrive within it. Zero
// selects DefaultOpenTimeout. Without a bound, a relay that never answers
// blocks Open forever — the caller has no way to recover, because the
// blocking read is internal to it.
Timeout time.Duration
// contains filtered or unexported fields
}
Gateway implements AMT (RFC 7450) using Rust-backed protocol logic. Public fields maintain compatibility with conn.go.
type ManagedConn ¶
type ManagedConn struct {
// Configuration (same fields as MulticastConn for compatibility)
RelayAddr net.UDPAddr
SrcAddr netip.Addr
GroupAddr netip.Addr
GroupPort uint16
TTL int
IFace *net.Interface
// Timeout is deprecated. It seeds ProbeWindow and RelayHandshakeTimeout when
// either explicit field is unset.
Timeout time.Duration
ProbeWindow time.Duration
RelayHandshakeTimeout time.Duration
Timestamp bool
// RcvBufBytes and SndBufBytes are forwarded to the native multicast
// socket; see MulticastConn for semantics.
RcvBufBytes int
SndBufBytes int
// Mode selects native-vs-tunnel, and mirrors MulticastConn.Mode field for
// field. The zero value (AMTModeAuto) keeps the historical inference, where a
// configured RelayAddr makes the native join provisional. Set it explicitly
// to stop a relay address that was inherited by configuration clone from
// deciding the delivery path (BLO-28640).
Mode AMTMode
// DRIAD discovery configuration (RFC 8777)
// When EnableDRIAD is true and RelayAddr is empty, discovers relay via DNS
EnableDRIAD bool
DNSServers []string // Optional, uses system default if empty
// contains filtered or unexported fields
}
ManagedConn provides a backward-compatible wrapper around RelayManager subscriptions. It implements net.PacketConn and can be used as a drop-in replacement for MulticastConn.
Key differences from MulticastConn: - Shares a single socket per relay across multiple (S,G) subscriptions - Automatic reconnection with exponential backoff - Supports DRIAD discovery (RFC 8777) when EnableDRIAD is true
func (*ManagedConn) IsUsingTunnel ¶
func (mc *ManagedConn) IsUsingTunnel() bool
IsUsingTunnel returns true if the connection is using AMT tunneling
func (*ManagedConn) LocalAddr ¶
func (mc *ManagedConn) LocalAddr() net.Addr
LocalAddr returns the local address
func (*ManagedConn) Open ¶
func (mc *ManagedConn) Open() error
Open initializes the connection, trying native multicast first, then AMT relay
Open can take seconds to return — up to MinUsefulProbeWindow proving the native join, plus the relay handshake — but it holds mc.mu only for short sections at each end. That split is deliberate: when the probe window ran inside the exclusive lock, Close() had to wait the whole window out with no cancellation path, and because Go's RWMutex queues new readers behind a waiting writer, one pending Close also stalled every IsUsingTunnel/LocalAddr/ Stats reader for the remainder of it.
Two consequences of that split are worth stating rather than leaving to be discovered. The observers — IsUsingTunnel, LocalAddr, Stats — may return a provisional value while Open is in flight, which is deliberate: a stale-but- immediate answer beats a ten-second stall. The data-plane methods do NOT get that treatment; they call waitOpen first, because a reader that snapshots a half-built connection can park forever rather than merely read a stale field.
The deadline setters — SetDeadline, SetReadDeadline, SetWriteDeadline — wait too. They look like small setters but they belong with the data plane, not the observers, because they MUTATE the connection and no provisional answer is available to them: racing Open they would find nativeConn nil, fall through to the tunnel branch, and return nil having set nothing. Open then installs the native socket with no deadline on it, so a caller that opened in a goroutine and set a deadline on the main path gets a socket that blocks forever on a group that goes idle — and a nil error, so there is nothing to retry on. On the tunnel branch returning nil without setting anything remains a documented limitation; on the native branch it used to work, because mu was held for the whole of Open, and narrowing it exposed these three alongside the six.
Close does not *cancel* an in-flight Open, it marks the connection. The probe has no cancellation path plumbed into it, so after Close returns, a concurrent Open can still hold the native socket and its IGMP join for the remainder of the probe window before noticing and undoing its own work. Nothing leaks and every commit point re-checks closed, but a caller cannot treat Close returning as proof the join is already gone.
func (*ManagedConn) ReadBatch ¶
ReadBatch reads multiple packets efficiently.
The return count describes the contiguous filled prefix: exactly ms[:count] received a packet, so a caller must iterate that prefix and must not inspect ms[count:]. On the tunnel path a message with no room — no Buffers, or a zero-length Buffers[0] — ends the batch and returns the count filled so far, rather than being skipped over. That keeps the prefix honest and, because a packet already taken off the subscription channel cannot be put back, is what stops a no-room slot from silently destroying a packet (BLO-29454). A batch whose first message has no room therefore reads (0, nil) without consuming anything, the same shape as an empty ms.
func (*ManagedConn) ReadFrom ¶
ReadFrom reads a packet from the connection.
On the AMT tunnel path, a zero-length buffer returns (0, nil) without consuming the queued packet. A non-zero buffer that is shorter than the packet follows net.PacketConn semantics: the packet is consumed and its payload is truncated to fit. The native path delegates to the underlying connection and retains its standard-library behavior.
func (*ManagedConn) ReadFromWithControlMessage ¶
func (mc *ManagedConn) ReadFromWithControlMessage(buf []byte) (n int, cm *ipv4.ControlMessage, src net.Addr, err error)
ReadFromWithControlMessage reads a packet with control message.
On the AMT tunnel path, a zero-length buffer returns (0, nil, nil) without consuming the queued packet. A non-zero buffer that is shorter than the packet follows net.PacketConn semantics: the packet is consumed and its payload is truncated to fit. The native path delegates to the underlying connection and retains its standard-library behavior. An IPv6 group returns a nil control message, as the tunnel does: its control message is an ipv6.ControlMessage.
func (*ManagedConn) RelayManager ¶
func (mc *ManagedConn) RelayManager() *RelayManager
RelayManager returns the underlying RelayManager (for advanced use)
func (*ManagedConn) SetDeadline ¶
func (mc *ManagedConn) SetDeadline(t time.Time) error
SetDeadline sets the read and write deadlines.
Waits for Open for the reason given on Open: racing it, this would find nativeConn nil, fall through, and return nil having set nothing.
func (*ManagedConn) SetReadDeadline ¶
func (mc *ManagedConn) SetReadDeadline(t time.Time) error
SetReadDeadline sets the read deadline. Waits for Open; see SetDeadline.
func (*ManagedConn) SetWriteDeadline ¶
func (mc *ManagedConn) SetWriteDeadline(t time.Time) error
SetWriteDeadline sets the write deadline. Waits for Open; see SetDeadline.
func (*ManagedConn) Stats ¶
func (mc *ManagedConn) Stats() *ManagedConnStats
Stats returns connection statistics
func (*ManagedConn) Subscription ¶
func (mc *ManagedConn) Subscription() *Subscription
Subscription returns the underlying Subscription (for advanced use)
func (*ManagedConn) WriteBatch ¶
WriteBatch writes multiple packets (not supported for AMT tunnel)
func (*ManagedConn) WriteToWithControlMessage ¶
func (mc *ManagedConn) WriteToWithControlMessage(p []byte, cm *ipv4.ControlMessage, addr net.Addr) (n int, err error)
WriteToWithControlMessage writes a packet with an IPv4 control message. On an IPv6 group's socket the control message does not apply and is not sent.
type ManagedConnStats ¶
type ManagedConnStats struct {
UsingTunnel bool
PacketsReceived uint64
BytesReceived uint64
LastPacketTime time.Time
RelayState string
ReconnectCount uint64
TransportType string
// Decap is the relay's data path, shared by every ManagedConn to it.
Decap DecapStats
}
ManagedConnStats contains connection statistics
type MulticastConn ¶
type MulticastConn struct {
RelayAddr net.UDPAddr
SrcAddr netip.Addr
GroupAddr netip.Addr
GroupPort uint16
TTL int
IFace *net.Interface
// Timeout is deprecated. It seeds ProbeWindow and RelayHandshakeTimeout when
// either explicit field is unset.
Timeout time.Duration
// ProbeWindow controls how long native multicast is probed before fallback.
ProbeWindow time.Duration
// RelayHandshakeTimeout bounds the AMT relay handshake.
RelayHandshakeTimeout time.Duration
Timestamp bool
// RcvBufBytes, if > 0, requests this size on the underlying UDP socket via
// SetForcedReceiveBuffer (SO_RCVBUFFORCE on Linux, SO_RCVBUF on Darwin).
// SO_RCVBUFFORCE requires CAP_NET_ADMIN; on EPERM it falls back to
// SO_RCVBUF, which is capped at 2*net.core.rmem_max.
RcvBufBytes int
// SndBufBytes is the send-side counterpart of RcvBufBytes.
SndBufBytes int
// Mode selects native-vs-tunnel. The zero value (AMTModeAuto) keeps the
// historical inference, where a configured RelayAddr makes the native join
// provisional. Set it explicitly to stop a relay address that was inherited
// by configuration clone from deciding the delivery path (BLO-28640).
Mode AMTMode
// Filter, if non-empty, is attached to the native socket with
// SO_ATTACH_FILTER before the group join, so it governs every datagram the
// socket sees, including the one the native probe waits for. A filter that
// drops all traffic for the probe window therefore reads as "native not
// deliverable"; callers sharding one group across several sockets should
// set Mode to AMTModeNative on the shards that may see nothing. The AMT
// tunnel reads one unicast socket and cannot apply it, so Open rejects a
// Filter whenever the plan could fall back to the tunnel (BLO-40191).
Filter []bpf.RawInstruction
// contains filtered or unexported fields
}
func (*MulticastConn) Close ¶
func (mc *MulticastConn) Close() error
func (*MulticastConn) EnableGRO ¶
func (mc *MulticastConn) EnableGRO() error
EnableGRO turns on UDP GRO for the native receive socket, so the kernel coalesces consecutive same-size datagrams from one source into a single ReadBatch slot and the receiver pays one syscall per run instead of one per datagram. It is the receive-side counterpart of WriteSegments.
Opt-in, and called after Open rather than configured on it, because it changes how a read must be framed: once a slot can hold several datagrams, a caller that reads the buffer whole silently mis-frames every coalesced run. Enabling it is therefore a statement that the caller consults SegmentSize per slot, which no configuration flag could promise on its behalf. The buffer sizing needs no coordination -- ControlMessageOOBLen already counts GROControlMessageLen unconditionally.
An error wrapping ErrGROUnsupported means the socket is unchanged and still delivers one datagram per slot, which is what the caller was already doing; it is a capability report, not a failure. Any other error is real.
Call it once Open has returned, not concurrently with it. The socket fields read below are published under pathMu by Open's tunnel-fallback path and are read here unlocked, as WriteBatch and WriteSegments read them. (The "already running receiver" in GROControlMessageLen's note is about buffer sizing -- no flag day needed -- not a licence to race Open.) An RLock here would not be the cheap fix it looks: IsUsingTunnel RLocks pathMu already, so wrapping this body makes it a recursive read lock, which sync.RWMutex documents as deadlock-prone whenever a writer is waiting between the two.
func (*MulticastConn) IsUsingTunnel ¶
func (mc *MulticastConn) IsUsingTunnel() bool
func (*MulticastConn) LocalAddr ¶
func (mc *MulticastConn) LocalAddr() net.Addr
func (*MulticastConn) Open ¶
func (mc *MulticastConn) Open() error
func (*MulticastConn) ReadFromWithControlMessage ¶
func (mc *MulticastConn) ReadFromWithControlMessage(buf []byte) (n int, cm *ipv4.ControlMessage, src net.Addr, err error)
func (*MulticastConn) SetDeadline ¶
func (mc *MulticastConn) SetDeadline(t time.Time) error
func (*MulticastConn) SetMulticastLoopback ¶
func (mc *MulticastConn) SetMulticastLoopback(on bool) error
SetMulticastLoopback sets IP_MULTICAST_LOOP (IPV6_MULTICAST_LOOP on a v6 group) on the native socket. Open turns it on, which a receiver needs and a sender pays for: every datagram the socket sends is also copied back into this host's stack and delivered to every local socket joined to the group, the sender's own socket included, which nothing reads, so each copy is queued and then dropped as RcvbufErrors inside the sender's own sendmsg (BLO-47236). A send-only caller turns it off after Open.
Off affects only sends from this socket, and only the copy into this host: datagrams still leave on the interface, and a socket on the loopback device still receives them, because there the device itself delivers them. A receiver on the same host but a real interface stops hearing this socket.
Call it once Open has returned, as EnableGRO. An AMT tunnel has no native socket to set it on and reports an error.
func (*MulticastConn) SetReadDeadline ¶
func (mc *MulticastConn) SetReadDeadline(t time.Time) error
func (*MulticastConn) SetWriteDeadline ¶
func (mc *MulticastConn) SetWriteDeadline(t time.Time) error
func (*MulticastConn) WriteBatch ¶
func (*MulticastConn) WriteSegments ¶
func (mc *MulticastConn) WriteSegments(b []byte, segmentSize int, cm *ipv4.ControlMessage, dst net.Addr) (int, error)
WriteSegments writes b to dst as a single sendmsg(2) carrying UDP_SEGMENT (UDP GSO), so the kernel emits ceil(len(b)/segmentSize) separate datagrams instead of costing one syscall each. b must be the segments laid out back-to-back, every one exactly segmentSize except the last, which may be shorter.
It exists because UDP_SEGMENT is an IPPROTO_UDP control message and x/net's ipv4.ControlMessage marshals IP-level options only, so the option cannot be expressed through WriteTo or WriteBatch. cm still supplies the IP-level half (source address and egress interface) and is marshalled here.
An error wrapping ErrSegmentsUnsupported means nothing was written and the caller should fall back to WriteBatch or per-datagram WriteTo -- a refused segmented send emits zero frames, so the fallback cannot duplicate traffic. ErrSegmentsPartial is the one error that must NOT be retried.
func (*MulticastConn) WriteToWithControlMessage ¶
func (mc *MulticastConn) WriteToWithControlMessage(b []byte, cm *ipv4.ControlMessage, dst net.Addr) (n int, err error)
type Platform ¶
type Platform string
Platform represents the detected runtime platform
func DetectPlatform ¶
func DetectPlatform() Platform
DetectPlatform returns the current runtime platform
type PlatformCapabilities ¶
type PlatformCapabilities struct {
Platform Platform
SupportsUDP bool // Raw UDP sockets available
SupportsCGO bool // CGO (C bindings) available
SupportsBPF bool // BPF filtering available
SupportsTimestamp bool // Packet timestamps available
}
PlatformCapabilities describes what features are available on this platform
func GetPlatformCapabilities ¶
func GetPlatformCapabilities() PlatformCapabilities
GetPlatformCapabilities returns the capabilities for the current platform
type ProtocolError ¶
ProtocolError represents an AMT protocol error
func (*ProtocolError) Error ¶
func (e *ProtocolError) Error() string
func (*ProtocolError) Unwrap ¶
func (e *ProtocolError) Unwrap() error
type ProtocolFactory ¶
type ProtocolFactory interface {
// Create creates a new protocol instance
Create() (AMTProtocol, error)
// Type returns the protocol implementation type
Type() ProtocolType
}
ProtocolFactory creates protocol implementations based on platform
type ProtocolType ¶
type ProtocolType string
ProtocolType identifies the protocol implementation
const ( ProtocolTypeCGO ProtocolType = "cgo" ProtocolTypePureGo ProtocolType = "pure-go" )
func BestProtocolType ¶
func BestProtocolType() ProtocolType
BestProtocolType returns the recommended protocol type for this platform
type PureGoProtocol ¶
type PureGoProtocol struct {
// contains filtered or unexported fields
}
PureGoProtocol implements AMTProtocol in pure Go. Works on all platforms including iOS, Android, and WASM.
func NewPureGoProtocol ¶
func NewPureGoProtocol() (*PureGoProtocol, error)
NewPureGoProtocol creates a new pure Go protocol instance
func (*PureGoProtocol) Close ¶
func (p *PureGoProtocol) Close()
func (*PureGoProtocol) CreateDiscoveryMessage ¶
func (p *PureGoProtocol) CreateDiscoveryMessage() ([]byte, error)
func (*PureGoProtocol) CreateIGMPJoinReport ¶
func (p *PureGoProtocol) CreateIGMPJoinReport(source, group netip.Addr) ([]byte, error)
func (*PureGoProtocol) CreateIGMPJoinReportMulti ¶
func (*PureGoProtocol) CreateIGMPLeaveReport ¶
func (p *PureGoProtocol) CreateIGMPLeaveReport(source, group netip.Addr) ([]byte, error)
func (*PureGoProtocol) CreateIGMPSourceLeaveReport ¶
func (p *PureGoProtocol) CreateIGMPSourceLeaveReport(source, group netip.Addr) ([]byte, error)
func (*PureGoProtocol) CreateMembershipUpdate ¶
func (p *PureGoProtocol) CreateMembershipUpdate(igmpReport []byte) ([]byte, error)
func (*PureGoProtocol) CreateRequestMessage ¶
func (p *PureGoProtocol) CreateRequestMessage(preferNative bool) ([]byte, error)
func (*PureGoProtocol) CreateTeardownMessage ¶
func (p *PureGoProtocol) CreateTeardownMessage() ([]byte, error)
func (*PureGoProtocol) HandleAdvertisement ¶
func (p *PureGoProtocol) HandleAdvertisement(data []byte) error
func (*PureGoProtocol) HandleQuery ¶
func (*PureGoProtocol) Initialize ¶
func (p *PureGoProtocol) Initialize(relayAddr string, relayPort uint16) error
func (*PureGoProtocol) Reset ¶
func (p *PureGoProtocol) Reset()
func (*PureGoProtocol) State ¶
func (p *PureGoProtocol) State() AMTState
type RelayManager ¶
type RelayManager struct {
// contains filtered or unexported fields
}
RelayManager manages a shared AMT relay connection for multiple subscriptions
func GetOrCreateRelayManager ¶
func GetOrCreateRelayManager(relayAddr net.UDPAddr, config *RelayManagerConfig) (*RelayManager, error)
GetOrCreateRelayManager returns an existing or creates a new RelayManager for the relay address
func NewRelayManager ¶
func NewRelayManager(config RelayManagerConfig) *RelayManager
NewRelayManager creates a new RelayManager
func (*RelayManager) Close ¶
func (rm *RelayManager) Close() error
Close shuts down the relay manager
func (*RelayManager) Open ¶
func (rm *RelayManager) Open(ctx context.Context) error
Open initializes and connects the relay manager
func (*RelayManager) State ¶
func (rm *RelayManager) State() RelayState
State returns the current relay state
func (*RelayManager) Stats ¶
func (rm *RelayManager) Stats() RelayManagerStats
Stats returns relay manager statistics
func (*RelayManager) Subscribe ¶
func (rm *RelayManager) Subscribe(key SubscriptionKey, callbacks SubscriptionCallbacks) (*Subscription, error)
func (*RelayManager) Unsubscribe ¶
func (rm *RelayManager) Unsubscribe(key SubscriptionKey) error
Unsubscribe removes a subscription.
The subscription is always torn down and removed, regardless of the returned error: a non-nil return reports that the leave could not be delivered to the relay, not that the caller still holds the subscription. Retrying is pointless — a second call short-circuits to nil because the entry is already gone. Callers should log the error (the relay will keep forwarding until its membership times out) rather than loop on it.
func (*RelayManager) WaitLeaves ¶
func (rm *RelayManager) WaitLeaves(ctx context.Context) error
WaitLeaves blocks until every leave retransmission Unsubscribe scheduled has been sent or abandoned, or ctx is done. A process that exits right after unsubscribing calls it, or its retransmissions die with it.
type RelayManagerConfig ¶
type RelayManagerConfig struct {
// RelayAddr is the AMT relay address (can be empty if EnableDRIAD is true)
RelayAddr net.UDPAddr
// EnableDRIAD enables DRIAD discovery (RFC 8777) when RelayAddr is empty
EnableDRIAD bool
// SourceAddr is the multicast source address (required for DRIAD discovery)
SourceAddr netip.Addr
// DNSServers is a list of DNS servers for DRIAD discovery (optional)
DNSServers []string
// DNSTimeout is the timeout for DRIAD DNS queries
DNSTimeout time.Duration
// MTU is the maximum transmission unit. It sizes the handshake's read
// buffer; the data read loop uses tunnelReadBuffer, since the relay's
// fragmented data messages reach it reassembled past any MTU.
MTU int
// TransportConfig for transport layer
TransportConfig TransportConfig
// BackoffConfig for reconnection
InitialBackoff time.Duration
MaxBackoff time.Duration
BackoffMultiplier float64
// DataChannelSize is the buffer size for subscription data channels
DataChannelSize int
// KeepaliveInterval is the interval for sending keepalive requests
KeepaliveInterval time.Duration
// TransportFactory, when non-nil, constructs the Transport in place of
// CreatePlatformTransport. Production callers leave it nil; it exists so a
// test can wrap or replace the transport, which is otherwise unreachable
// because Open assigns rm.transport itself and swapping the field afterwards
// races the running readLoop.
//
// Open calls it once per relay candidate it tries, so a DRIAD config whose
// first relay is unreachable calls it again for the next one. Reconnection
// reuses the Transport that succeeded through its Close/Open methods rather
// than building a new one, so a decorator installed here observes every
// generation, including the reconnect handshake.
TransportFactory func(TransportConfig) (Transport, error)
}
RelayManagerConfig contains configuration for RelayManager
func DefaultRelayManagerConfig ¶
func DefaultRelayManagerConfig(relayAddr net.UDPAddr) RelayManagerConfig
DefaultRelayManagerConfig returns a config with sensible defaults
func DefaultRelayManagerConfigWithDRIAD ¶
func DefaultRelayManagerConfigWithDRIAD(sourceAddr netip.Addr) RelayManagerConfig
DefaultRelayManagerConfigWithDRIAD returns a config with DRIAD discovery enabled
type RelayManagerStats ¶
type RelayManagerStats struct {
State RelayState
SubscriptionCount int
TotalPackets uint64
TotalBytes uint64
ReconnectCount uint64
LastReconnectTime time.Time
TransportType TransportType
ProtocolType ProtocolType
Decap DecapStats
}
RelayManagerStats contains relay manager statistics
type RelayState ¶
type RelayState int
RelayState represents the AMT relay connection state
const ( RelayStateIdle RelayState = iota RelayStateDiscovering RelayStateRequesting RelayStateQuerying RelayStateActive RelayStateReconnecting RelayStateClosed RelayStateError )
func (RelayState) String ¶
func (s RelayState) String() string
type SourceSpecificLeaveReporter ¶
type SourceSpecificLeaveReporter interface {
CreateIGMPSourceLeaveReport(source, group netip.Addr) ([]byte, error)
}
SourceSpecificLeaveReporter preserves other sources in a group when one local (S,G) subscription is removed.
type Subscription ¶
type Subscription struct {
// contains filtered or unexported fields
}
Subscription represents a single (S,G) multicast subscription
func (*Subscription) DataChan ¶
func (s *Subscription) DataChan() <-chan *DataPacket
DataChan returns the channel for receiving data packets
func (*Subscription) Key ¶
func (s *Subscription) Key() SubscriptionKey
Key returns the subscription key
func (*Subscription) State ¶
func (s *Subscription) State() SubscriptionState
State returns the current subscription state
func (*Subscription) Stats ¶
func (s *Subscription) Stats() SubscriptionStats
Stats returns subscription statistics
type SubscriptionCallbacks ¶
type SubscriptionCallbacks struct {
// OnPacket is called when data is received for this subscription
OnPacket func(data []byte, src net.Addr) error
// OnStateChange is called when subscription state changes
OnStateChange func(old, new SubscriptionState)
// OnError is called when an error occurs
OnError func(err error)
}
SubscriptionCallbacks defines callbacks for subscription events
type SubscriptionKey ¶
SubscriptionKey uniquely identifies a multicast subscription
func (SubscriptionKey) String ¶
func (k SubscriptionKey) String() string
type SubscriptionState ¶
type SubscriptionState int
SubscriptionState represents a subscription's state
const ( SubscriptionStateInitializing SubscriptionState = iota SubscriptionStateJoining SubscriptionStateActive SubscriptionStateSuspended SubscriptionStateClosed SubscriptionStateError )
func (SubscriptionState) String ¶
func (s SubscriptionState) String() string
type SubscriptionStats ¶
type SubscriptionStats struct {
PacketsReceived uint64
BytesReceived uint64
LastPacketTime time.Time
State SubscriptionState
}
SubscriptionStats contains subscription statistics
type Transport ¶
type Transport interface {
// Open initializes the transport connection
Open(ctx context.Context) error
// Close shuts down the transport
Close() error
// Send sends data to the relay
Send(data []byte) error
// Receive reads data from the relay with optional deadline
// Returns the data, source address (if applicable), and any error
Receive(buf []byte) (n int, addr net.Addr, err error)
// SetReadDeadline sets the deadline for receive operations
SetReadDeadline(t time.Time) error
// LocalAddr returns the local address if applicable
LocalAddr() net.Addr
// RelayAddr returns the relay address currently being sent to. Before an
// advertisement is adopted this is the configured (discovery) address.
RelayAddr() net.Addr
// AdoptAdvertisedRelay points subsequent sends at the relay named in a
// Relay Advertisement, when it names one this transport can plausibly
// reach. Takes the raw advertisement, already validated by the protocol.
// A no-op when the advertisement is unusable; see advertisedRelayDest.
AdoptAdvertisedRelay(data []byte)
// SupportsTimestamp returns true if the transport supports packet timestamps
SupportsTimestamp() bool
// Type returns the transport type for logging/debugging
Type() TransportType
}
Transport abstracts the underlying network transport for AMT relay communication. UDPTransport is the primary implementation for all platforms.
func CreatePlatformTransport ¶
func CreatePlatformTransport(cfg TransportConfig) (Transport, error)
CreatePlatformTransport creates UDP transport (the default for all platforms)
func NewTransport ¶
func NewTransport(typ TransportType, cfg TransportConfig) (Transport, error)
NewTransport creates a transport of the specified type
type TransportConfig ¶
type TransportConfig struct {
// RelayAddr is the AMT relay address
RelayAddr net.UDPAddr
// Timeout bounds the AMT relay handshake, retransmissions included. Zero
// selects the default, 10 s. ManagedConn sets it from
// RelayHandshakeTimeout.
Timeout time.Duration
// EnableTimestamp enables packet timestamping (if supported)
EnableTimestamp bool
// MTU is the maximum transmission unit
MTU int
// RcvBufBytes and SndBufBytes, if > 0, are applied to the relay UDP socket
// via applyForcedBuffers (SO_RCVBUFFORCE/SO_SNDBUFFORCE on Linux,
// SO_RCVBUF/SO_SNDBUF on Darwin); see MulticastConn / Gateway for semantics.
RcvBufBytes int
SndBufBytes int
}
TransportConfig contains configuration for UDP transport
func DefaultTransportConfig ¶
func DefaultTransportConfig(relayAddr net.UDPAddr) TransportConfig
DefaultTransportConfig returns a config with sensible defaults
type TransportError ¶
type TransportError struct {
Type TransportType
Message string
Cause error
}
TransportError represents a transport-level error
func (*TransportError) Error ¶
func (e *TransportError) Error() string
func (*TransportError) Unwrap ¶
func (e *TransportError) Unwrap() error
type TransportType ¶
type TransportType string
TransportType identifies the transport implementation
const (
TransportTypeUDP TransportType = "udp"
)
func BestTransportType ¶
func BestTransportType() TransportType
BestTransportType returns the recommended transport type for this platform
type UDPTransport ¶
type UDPTransport struct {
// contains filtered or unexported fields
}
UDPTransport implements Transport using UDP sockets. This is the primary transport for all platforms.
func NewUDPTransport ¶
func NewUDPTransport(cfg TransportConfig) (*UDPTransport, error)
NewUDPTransport creates a new UDP transport
func (*UDPTransport) AdoptAdvertisedRelay ¶
func (t *UDPTransport) AdoptAdvertisedRelay(data []byte)
AdoptAdvertisedRelay redirects Send at the relay the advertisement names, so the Request and every keepalive after it reach the relay that actually answered rather than the anycast address the Discovery went to. The plausibility tests are in advertisedRelayDest, shared with Gateway.
func (*UDPTransport) Close ¶
func (t *UDPTransport) Close() error
func (*UDPTransport) Conn ¶
func (t *UDPTransport) Conn() *ipv4.PacketConn
Conn returns the underlying ipv4.PacketConn for advanced operations
func (*UDPTransport) LocalAddr ¶
func (t *UDPTransport) LocalAddr() net.Addr
func (*UDPTransport) RelayAddr ¶
func (t *UDPTransport) RelayAddr() net.Addr
func (*UDPTransport) Send ¶
func (t *UDPTransport) Send(data []byte) error
func (*UDPTransport) SetReadDeadline ¶
func (t *UDPTransport) SetReadDeadline(deadline time.Time) error
func (*UDPTransport) SupportsTimestamp ¶
func (t *UDPTransport) SupportsTimestamp() bool
func (*UDPTransport) Type ¶
func (t *UDPTransport) Type() TransportType
func (*UDPTransport) WriteBatch ¶
WriteBatch writes multiple messages for efficiency
Source Files
¶
- amtmode.go
- conn.go
- control_flags.go
- driad.go
- fragment.go
- gateway.go
- gro.go
- gro_linux.go
- gso.go
- gso_linux.go
- listen_multicast6_linux.go
- listen_multicast_linux.go
- listen_seam.go
- listen_seam6.go
- managed_conn.go
- managed_conn_native.go
- managed_conn_native6.go
- platform.go
- probe.go
- protocol.go
- protocol_cgo.go
- protocol_pure.go
- relay_manager.go
- sockbuf.go
- sockbuf_linux.go
- sockbuf_maxsockbuf.go
- transport.go
- transport_udp.go
- transport_udp_posix.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Package broker defines the gateway-to-session-broker control-plane wire contract for bcast-shred-gw.
|
Package broker defines the gateway-to-session-broker control-plane wire contract for bcast-shred-gw. |
|
gwclient
Package gwclient is the gateway side of the broker control plane: it assembles a broker.Heartbeat from the receiver's live state and POSTs it.
|
Package gwclient is the gateway side of the broker control plane: it assembles a broker.Heartbeat from the receiver's live state and POSTs it. |
|
cmd
|
|
|
amt_bridge
command
Command amt_bridge joins one SSM (S,G) group through an AMT relay and re-emits each received datagram's payload to a local UDP address.
|
Command amt_bridge joins one SSM (S,G) group through an AMT relay and re-emits each received datagram's payload to a local UDP address. |
|
amt_gw
command
|
|
|
blockcast-shreds
command
Command blockcast-shreds is the zero-account demo receiver and verifier.
|
Command blockcast-shreds is the zero-account demo receiver and verifier. |
|
shred-merger
command
shred-merger merges two independent Solana turbine shred streams into one deduplicated stream, the union feed (BLO-22812), and emits it on one or more outputs.
|
shred-merger merges two independent Solana turbine shred streams into one deduplicated stream, the union feed (BLO-22812), and emits it on one or more outputs. |
|
shred-soak
command
Command shred-soak drives blockcast-shreds with a sustained feed of UNIQUE shred identities, so the receiver process can be observed reaching a steady state rather than growing for as long as it runs.
|
Command shred-soak drives blockcast-shreds with a sustained feed of UNIQUE shred identities, so the receiver process can be observed reaching a steady state rather than growing for as long as it runs. |
|
shred-txfeed
command
shred-txfeed decodes the shred union into Solana transactions and emits them on partition groups (BLO-41705), one per datagram, or in chunks when a transaction would not fit in txfeed.MaxDatagram, so that no datagram is IP-fragmented.
|
shred-txfeed decodes the shred union into Solana transactions and emits them on partition groups (BLO-41705), one per datagram, or in chunks when a transaction would not fit in txfeed.MaxDatagram, so that no datagram is IP-fragmented. |
|
txfeed-sub
command
txfeed-sub subscribes to shred-txfeed partition groups and prints the transactions it receives, a demo of the feed (BLO-41705).
|
txfeed-sub subscribes to shred-txfeed partition groups and prints the transactions it receives, a demo of the feed (BLO-41705). |
|
Package erasure tracks receiver-observed Solana FEC-set completion.
|
Package erasure tracks receiver-observed Solana FEC-set completion. |
|
internal
|
|
|
amtrelay
Package amtrelay parses the AMT relay address that blockcast-shreds' ssm:// feeds (?relay=) and txfeed-sub (-relay) hand to amt.ManagedConn, so both commands accept and refuse the same relays.
|
Package amtrelay parses the AMT relay address that blockcast-shreds' ssm:// feeds (?relay=) and txfeed-sub (-relay) hand to amt.ManagedConn, so both commands accept and refuse the same relays. |
|
Package metrics exposes the AMT relay drop counter contract.
|
Package metrics exposes the AMT relay drop counter contract. |
|
Package receiver implements the unicast receive and fan-out path used by bcast-shred-gw.
|
Package receiver implements the unicast receive and fan-out path used by bcast-shred-gw. |
|
config
Package config parses and validates bcast-shred-gw configuration.
|
Package config parses and validates bcast-shred-gw configuration. |
|
delivery
Package delivery implements the delivery-session wire contract emitted by the unicast fan-out sender.
|
Package delivery implements the delivery-session wire contract emitted by the unicast fan-out sender. |
|
Package shred parses the Solana shred fields needed for delivery scoring.
|
Package shred parses the Solana shred fields needed for delivery scoring. |
|
Package txfeed turns the shred union into a feed of decoded Solana transactions, partitioned onto multicast groups: non-vote, and by program (BLO-41705).
|
Package txfeed turns the shred union into a feed of decoded Solana transactions, partitioned onto multicast groups: non-vote, and by program (BLO-41705). |