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/// Bind a TCP listener, making an IPv6 socket dual-stack so it also serves IPv4.
35///
36/// The returned listener is non-blocking, ready for
37/// [`axum_server::from_tcp`](https://docs.rs/axum-server).
38pub fn tcp(addr: SocketAddr) -> std::io::Result<TcpListener> {
39	let domain = if addr.is_ipv4() { Domain::IPV4 } else { Domain::IPV6 };
40	let socket = Socket::new(domain, Type::STREAM, Some(Protocol::TCP))?;
41	make_dual_stack(&socket, addr);
42	// Match std's TcpListener, which sets SO_REUSEADDR on Unix (not Windows) so a
43	// restarted relay can rebind a port still in TIME_WAIT.
44	#[cfg(not(windows))]
45	socket.set_reuse_address(true)?;
46	// Enable keepalive on the listening socket so every accepted connection
47	// inherits it (accept() carries socket options across on Linux, macOS, and
48	// Windows). axum_server owns the accept loop, so this is the one hook we have
49	// to reach the HTTP/HTTPS/WebSocket connections it serves. Best-effort: a
50	// platform that rejects the option keeps the connection rather than failing.
51	let keepalive = TcpKeepalive::new()
52		.with_time(KEEPALIVE_IDLE)
53		.with_interval(KEEPALIVE_INTERVAL);
54	if let Err(err) = socket.set_tcp_keepalive(&keepalive) {
55		tracing::warn!(%err, "failed to enable TCP keepalive; dead peers may linger");
56	}
57	socket.bind(&addr.into())?;
58	socket.listen(1024)?;
59	let listener: TcpListener = socket.into();
60	listener.set_nonblocking(true)?;
61	Ok(listener)
62}
63
64/// Clear `IPV6_V6ONLY` so an IPv6 socket also accepts IPv4. Best-effort: a
65/// platform that rejects the option keeps its default rather than failing the
66/// bind. No-op for IPv4 sockets.
67fn make_dual_stack(socket: &Socket, addr: SocketAddr) {
68	if addr.is_ipv6()
69		&& let Err(err) = socket.set_only_v6(false)
70	{
71		tracing::warn!(%err, "failed to enable dual-stack IPv6 socket; IPv4 clients may be unreachable");
72	}
73}
74
75#[cfg(test)]
76mod tests {
77	use super::*;
78
79	/// Skip a test when the host has no IPv6 stack (some CI sandboxes and
80	/// containers). Creating or binding an IPv6 socket then fails with an
81	/// address-family error, which is an environment limitation rather than a
82	/// bug in the dual-stack logic. The dual-stack assertion only has meaning
83	/// once a socket exists, so there's nothing to verify when IPv6 is absent.
84	fn skip_if_no_ipv6(err: &std::io::Error) -> bool {
85		// EAFNOSUPPORT / EADDRNOTAVAIL / EPROTONOSUPPORT on Unix, and the WSA*
86		// equivalents on Windows. The matching ErrorKinds round out the rest.
87		const NO_IPV6_ERRNOS: &[i32] = &[97, 99, 93, 10047, 10049, 10043];
88		let no_ipv6 = matches!(
89			err.kind(),
90			std::io::ErrorKind::AddrNotAvailable | std::io::ErrorKind::Unsupported
91		) || err.raw_os_error().is_some_and(|code| NO_IPV6_ERRNOS.contains(&code));
92		if no_ipv6 {
93			eprintln!("skipping: host has no IPv6 support ({err})");
94		}
95		no_ipv6
96	}
97
98	#[test]
99	fn udp_ipv6_is_dual_stack() {
100		// An IPv6 wildcard bind should come back dual-stack so IPv4 traffic
101		// reaches it. socket2 lets us read the option back to confirm.
102		let socket = match udp("[::]:0".parse().unwrap()) {
103			Ok(socket) => socket,
104			Err(err) if skip_if_no_ipv6(&err) => return,
105			Err(err) => panic!("failed to bind IPv6 UDP socket: {err}"),
106		};
107		let socket = Socket::from(socket);
108		assert!(!socket.only_v6().unwrap(), "IPv6 socket should be dual-stack");
109	}
110
111	#[test]
112	fn udp_ipv4_still_binds() {
113		let socket = udp("127.0.0.1:0".parse().unwrap()).unwrap();
114		assert!(socket.local_addr().unwrap().is_ipv4());
115	}
116
117	#[test]
118	fn tcp_ipv6_is_dual_stack() {
119		let listener = match tcp("[::]:0".parse().unwrap()) {
120			Ok(listener) => listener,
121			Err(err) if skip_if_no_ipv6(&err) => return,
122			Err(err) => panic!("failed to bind IPv6 TCP listener: {err}"),
123		};
124		let socket = Socket::from(listener);
125		assert!(!socket.only_v6().unwrap(), "IPv6 listener should be dual-stack");
126	}
127}