Skip to main content

moq_native/
bind.rs

1//! Dual-stack socket binding.
2//!
3//! Quinn uses a single socket and relies on the OS to route both address
4//! families. On Linux an `[::]` socket accepts IPv4 too, but Windows defaults
5//! `IPV6_V6ONLY` to on, so an IPv6 socket silently drops every IPv4 packet. The
6//! helpers here clear that before binding, so a relay on `[::]` is reachable
7//! over IPv4 and a dual-stack client can dial IPv4 servers (via IPv4-mapped
8//! addresses; the client's address-family matching lives in `util::pick_addr`).
9//! See <https://github.com/moq-dev/moq/issues/1375>.
10
11use socket2::{Domain, Protocol, Socket, TcpKeepalive, Type};
12use std::net::{SocketAddr, TcpListener, UdpSocket};
13use std::time::Duration;
14
15/// TCP keepalive idle period before the kernel starts probing a silent peer, and
16/// the interval between probes. A long-lived connection (a parked WebSocket, an
17/// idle HTTP/2 session) can otherwise sit in a `read` forever, so a peer that
18/// vanished without a FIN/RST (a yanked cable, a crashed NAT) would pin its
19/// socket and any resources behind it. Keepalive lets the kernel surface the dead
20/// peer as a read error and tear the connection down. The values are generous
21/// enough not to disturb a healthy but momentarily quiet connection.
22const KEEPALIVE_IDLE: Duration = Duration::from_secs(30);
23const KEEPALIVE_INTERVAL: Duration = Duration::from_secs(10);
24
25/// Bind a UDP socket, making an IPv6 socket dual-stack so it also serves IPv4.
26pub fn udp(addr: SocketAddr) -> std::io::Result<UdpSocket> {
27	let domain = if addr.is_ipv4() { Domain::IPV4 } else { Domain::IPV6 };
28	let socket = Socket::new(domain, Type::DGRAM, Some(Protocol::UDP))?;
29	make_dual_stack(&socket, addr);
30	socket.bind(&addr.into())?;
31	Ok(socket.into())
32}
33
34/// Whether `socket` also reaches IPv4, through IPv4-mapped addresses.
35///
36/// [`udp`] clears `IPV6_V6ONLY` best-effort, so this reads back what the
37/// platform actually did rather than assuming it took. A socket that stayed
38/// v6-only can't send to a mapped destination, and it looks identical from the
39/// outside: `local_addr` reads `[::]` either way. Always false for an IPv4
40/// socket, which reaches IPv4 natively rather than through mapping.
41pub(crate) fn udp_is_dual_stack(socket: &UdpSocket) -> bool {
42	match socket.local_addr() {
43		Ok(addr) if addr.is_ipv6() => socket2::SockRef::from(socket).only_v6().is_ok_and(|only| !only),
44		_ => false,
45	}
46}
47
48/// Bind a TCP listener, making an IPv6 socket dual-stack so it also serves IPv4.
49///
50/// The returned listener is non-blocking, ready for
51/// [`axum_server::from_tcp`](https://docs.rs/axum-server).
52pub fn tcp(addr: SocketAddr) -> std::io::Result<TcpListener> {
53	let domain = if addr.is_ipv4() { Domain::IPV4 } else { Domain::IPV6 };
54	let socket = Socket::new(domain, Type::STREAM, Some(Protocol::TCP))?;
55	make_dual_stack(&socket, addr);
56	// Match std's TcpListener, which sets SO_REUSEADDR on Unix (not Windows) so a
57	// restarted relay can rebind a port still in TIME_WAIT.
58	#[cfg(not(windows))]
59	socket.set_reuse_address(true)?;
60	// Enable keepalive on the listening socket so every accepted connection
61	// inherits it (accept() carries socket options across on Linux, macOS, and
62	// Windows). axum_server owns the accept loop, so this is the one hook we have
63	// to reach the HTTP/HTTPS/WebSocket connections it serves. Best-effort: a
64	// platform that rejects the option keeps the connection rather than failing.
65	let keepalive = TcpKeepalive::new()
66		.with_time(KEEPALIVE_IDLE)
67		.with_interval(KEEPALIVE_INTERVAL);
68	if let Err(err) = socket.set_tcp_keepalive(&keepalive) {
69		tracing::warn!(%err, "failed to enable TCP keepalive; dead peers may linger");
70	}
71	socket.bind(&addr.into())?;
72	socket.listen(1024)?;
73	let listener: TcpListener = socket.into();
74	listener.set_nonblocking(true)?;
75	Ok(listener)
76}
77
78/// Clear `IPV6_V6ONLY` so an IPv6 socket also accepts IPv4. Best-effort: a
79/// platform that rejects the option keeps its default rather than failing the
80/// bind. No-op for IPv4 sockets.
81fn make_dual_stack(socket: &Socket, addr: SocketAddr) {
82	if addr.is_ipv6()
83		&& let Err(err) = socket.set_only_v6(false)
84	{
85		tracing::warn!(%err, "failed to enable dual-stack IPv6 socket; IPv4 clients may be unreachable");
86	}
87}
88
89#[cfg(test)]
90mod tests {
91	use super::*;
92
93	/// Skip a test when the host has no IPv6 stack (some CI sandboxes and
94	/// containers). Creating or binding an IPv6 socket then fails with an
95	/// address-family error, which is an environment limitation rather than a
96	/// bug in the dual-stack logic. The dual-stack assertion only has meaning
97	/// once a socket exists, so there's nothing to verify when IPv6 is absent.
98	fn skip_if_no_ipv6(err: &std::io::Error) -> bool {
99		// EAFNOSUPPORT / EADDRNOTAVAIL / EPROTONOSUPPORT on Unix, and the WSA*
100		// equivalents on Windows. The matching ErrorKinds round out the rest.
101		const NO_IPV6_ERRNOS: &[i32] = &[97, 99, 93, 10047, 10049, 10043];
102		let no_ipv6 = matches!(
103			err.kind(),
104			std::io::ErrorKind::AddrNotAvailable | std::io::ErrorKind::Unsupported
105		) || err.raw_os_error().is_some_and(|code| NO_IPV6_ERRNOS.contains(&code));
106		if no_ipv6 {
107			eprintln!("skipping: host has no IPv6 support ({err})");
108		}
109		no_ipv6
110	}
111
112	#[test]
113	fn udp_ipv6_is_dual_stack() {
114		// An IPv6 wildcard bind should come back dual-stack so IPv4 traffic
115		// reaches it. socket2 lets us read the option back to confirm.
116		let socket = match udp("[::]:0".parse().unwrap()) {
117			Ok(socket) => socket,
118			Err(err) if skip_if_no_ipv6(&err) => return,
119			Err(err) => panic!("failed to bind IPv6 UDP socket: {err}"),
120		};
121		let socket = Socket::from(socket);
122		assert!(!socket.only_v6().unwrap(), "IPv6 socket should be dual-stack");
123	}
124
125	#[test]
126	fn udp_ipv4_still_binds() {
127		let socket = udp("127.0.0.1:0".parse().unwrap()).unwrap();
128		assert!(socket.local_addr().unwrap().is_ipv4());
129	}
130
131	#[test]
132	fn tcp_ipv6_is_dual_stack() {
133		let listener = match tcp("[::]:0".parse().unwrap()) {
134			Ok(listener) => listener,
135			Err(err) if skip_if_no_ipv6(&err) => return,
136			Err(err) => panic!("failed to bind IPv6 TCP listener: {err}"),
137		};
138		let socket = Socket::from(listener);
139		assert!(!socket.only_v6().unwrap(), "IPv6 listener should be dual-stack");
140	}
141}