Skip to main content

moq_native/
quinn.rs

1//! The quinn QUIC backend, used for both WebTransport (`https://`) and raw QUIC (`moqt://`, `moql://`).
2
3use crate::client::ClientConfig;
4use crate::quic::CongestionControl;
5use crate::quic::Resolved;
6use crate::quic::ServerId;
7use crate::server::ServerConfig;
8use crate::tls::{FingerprintVerifier, ServeCerts};
9use std::net;
10use std::sync::Arc;
11use std::time::Duration;
12use url::Url;
13
14pub use web_transport_quinn;
15
16/// Attach a qlog stream writing into `dir`, if one was configured.
17///
18/// quinn's [`quinn::QlogStream`] is a shared handle: every connection on the endpoint
19/// writes into it, tagged with its own qlog `group_id`. So this is one file per
20/// endpoint rather than per connection, unlike the noq and quiche backends.
21fn apply_qlog(transport: &mut quinn::TransportConfig, quic: &Resolved, role: &str) -> Result<()> {
22	// `Client::validate` already rejected a directory this build can't honor, so the
23	// block below is only reached where capture actually works.
24	let Some(dir) = quic.qlog_dir() else {
25		return Ok(());
26	};
27
28	#[cfg(feature = "qlog")]
29	{
30		// The pid keeps concurrent processes sharing a directory from clobbering each other.
31		let path = dir.join(format!("moq-{role}-{}.sqlog", std::process::id()));
32		let file = std::fs::File::create(&path).map_err(Error::CreateQlog)?;
33
34		// Deliberately unbuffered: qlog's streamer only flushes on `finish_log`, which
35		// quinn never calls per event, so a BufWriter would hold every trace in memory
36		// until the endpoint drops and lose the lot if the process is killed. Killing a
37		// stuck process is exactly when these traces are worth having.
38		let mut config = quinn::QlogConfig::default();
39		config.writer(Box::new(file)).title(Some(format!("moq-native {role}")));
40
41		transport.qlog_stream(config.into_stream());
42		tracing::info!(path = %path.display(), "writing qlog");
43	}
44
45	#[cfg(not(feature = "qlog"))]
46	let _ = (transport, dir, role);
47
48	Ok(())
49}
50
51/// Apply the resolved quic knobs to a quinn transport config.
52fn apply_transport(transport: &mut quinn::TransportConfig, quic: &Resolved) {
53	transport.max_idle_timeout(Some(quic.idle_timeout.try_into().expect("idle timeout out of range")));
54	transport.keep_alive_interval(quic.keep_alive);
55
56	// quinn enables MTU discovery by default; disable it unless asked.
57	if !quic.mtu_discovery {
58		transport.mtu_discovery_config(None);
59	}
60
61	let max_streams = quinn::VarInt::from_u64(quic.max_streams).unwrap_or(quinn::VarInt::MAX);
62	transport.max_concurrent_bidi_streams(max_streams);
63	transport.max_concurrent_uni_streams(max_streams);
64
65	// GSO is on by default; only the quinn/noq backends can turn it off.
66	if let Some(gso) = quic.gso {
67		transport.enable_segmentation_offload(gso);
68	}
69
70	transport.congestion_controller_factory(congestion_factory(congestion_control(quic)));
71}
72
73/// The congestion control family to install, defaulting to delay-based.
74///
75/// Live media wants a steady send rate an encoder can track, not CUBIC's sawtooth,
76/// so override quinn's own CUBIC default.
77fn congestion_control(quic: &Resolved) -> CongestionControl {
78	quic.congestion_control.unwrap_or(CongestionControl::Delay)
79}
80
81/// The quinn controller factory for a congestion control family. quinn's BBR is v1.
82fn congestion_factory(family: CongestionControl) -> Arc<dyn quinn::congestion::ControllerFactory + Send + Sync> {
83	match family {
84		CongestionControl::Loss => Arc::new(quinn::congestion::CubicConfig::default()),
85		CongestionControl::Delay => Arc::new(quinn::congestion::BbrConfig::default()),
86	}
87}
88
89/// Errors specific to the quinn QUIC backend.
90#[derive(Debug, thiserror::Error)]
91#[non_exhaustive]
92pub enum Error {
93	/// The UDP socket couldn't be bound, usually because the address is already in use.
94	#[error("failed to bind UDP socket")]
95	BindSocket(#[source] std::io::Error),
96
97	/// The bound socket couldn't be turned into a QUIC endpoint.
98	#[error("failed to create QUIC endpoint")]
99	CreateEndpoint(#[source] std::io::Error),
100
101	/// The qlog trace file couldn't be created, usually a missing directory.
102	#[error("failed to create qlog file")]
103	CreateQlog(#[source] std::io::Error),
104
105	/// Quinn found no async runtime. Construct the client or server from within a tokio context.
106	#[error("no async runtime")]
107	NoRuntime,
108
109	/// The endpoint's local address couldn't be read back from the OS.
110	#[error("failed to get local address")]
111	LocalAddr(#[source] std::io::Error),
112
113	/// The server's configured bind address couldn't be resolved.
114	#[error("failed to resolve bind address")]
115	ResolveBind(#[source] std::io::Error),
116
117	/// The URL has no host to connect to.
118	#[error("invalid DNS name")]
119	InvalidDnsName,
120
121	/// Resolving the URL's host failed.
122	#[error("failed DNS lookup")]
123	DnsLookup(#[source] std::io::Error),
124
125	/// DNS resolved the host to no addresses at all.
126	#[error("no DNS entries")]
127	NoDnsEntries,
128
129	/// The insecure `http://` bootstrap couldn't fetch `/certificate.sha256`.
130	#[error("failed to fetch fingerprint")]
131	FetchFingerprint(#[source] reqwest::Error),
132
133	/// The `/certificate.sha256` fetch returned a non-success status.
134	#[error("fingerprint request failed")]
135	FingerprintStatus(#[source] reqwest::Error),
136
137	/// The fingerprint response body couldn't be read.
138	#[error("failed to read fingerprint")]
139	ReadFingerprint(#[source] reqwest::Error),
140
141	/// The fetched fingerprint wasn't valid hex.
142	#[error("invalid fingerprint")]
143	InvalidFingerprint(#[from] hex::FromHexError),
144
145	/// The URL scheme isn't one this backend can dial.
146	#[error("url scheme must be 'https', 'moqt', or 'moql'")]
147	InvalidScheme,
148
149	/// The URL scheme passed the initial check but has no session type, which means it slipped through a scheme list.
150	#[error("unsupported URL scheme: {0}")]
151	UnsupportedScheme(String),
152
153	/// The connection came up without TLS handshake data, so the negotiated ALPN can't be read.
154	#[error("missing handshake data")]
155	MissingHandshake,
156
157	/// TLS negotiated no ALPN, so there's no protocol to speak.
158	#[error("missing ALPN")]
159	MissingAlpn,
160
161	/// The negotiated ALPN wasn't valid UTF-8.
162	#[error("failed to decode ALPN")]
163	DecodeAlpn(#[from] std::string::FromUtf8Error),
164
165	/// The peer negotiated an ALPN this endpoint doesn't handle.
166	#[error("unsupported ALPN: {0}")]
167	UnsupportedAlpn(String),
168
169	/// A raw QUIC client connected without SNI, so the server can't tell which host it wanted.
170	#[error("missing server name for raw QUIC connection")]
171	MissingServerName,
172
173	/// The client's SNI hostname didn't form a valid URL.
174	#[error("failed to construct URL from server name")]
175	BuildUrl(#[source] url::ParseError),
176
177	/// The configured QUIC-LB nonce is too short to be unguessable.
178	#[error("quic_lb_nonce must be at least 4")]
179	QuicLbNonceTooSmall,
180
181	/// The QUIC-LB server ID plus nonce doesn't fit in a connection ID. Shorten one of them.
182	#[error("connection ID length ({0}) exceeds maximum of 20")]
183	QuicLbCidTooLong(usize),
184
185	/// The mTLS client verifier couldn't be built from the configured roots.
186	#[error("failed to build client certificate verifier")]
187	ClientVerifier(#[source] rustls::server::VerifierBuilderError),
188
189	/// The rustls crypto provider offers no cipher suite usable for QUIC initial packets.
190	#[error(transparent)]
191	NoInitialCipherSuite(#[from] quinn::crypto::rustls::NoInitialCipherSuite),
192
193	/// Quinn refused to start the connection, before any packet was sent.
194	#[error(transparent)]
195	Connect(#[from] quinn::ConnectError),
196
197	/// The QUIC connection failed or was closed by the peer.
198	#[error(transparent)]
199	Connection(#[from] quinn::ConnectionError),
200
201	/// The WebTransport client handshake failed.
202	#[error(transparent)]
203	Client(#[from] web_transport_quinn::ClientError),
204
205	/// The server answered the WebTransport CONNECT with a rejection status.
206	#[error(transparent)]
207	ConnectRejected(#[from] crate::ConnectError),
208
209	/// The WebTransport server handshake failed while responding.
210	#[error(transparent)]
211	Server(#[from] web_transport_quinn::ServerError),
212
213	/// The QUIC handshake didn't complete for an incoming connection.
214	#[error("failed to establish QUIC connection")]
215	Establish(#[source] quinn::ConnectionError),
216
217	/// The client never sent a usable WebTransport CONNECT request.
218	#[error("failed to receive WebTransport request")]
219	RecvRequest(#[source] web_transport_quinn::ServerError),
220
221	/// The TLS configuration or certificates couldn't be loaded.
222	#[error(transparent)]
223	Tls(#[from] crate::tls::Error),
224
225	/// Two or more addresses were raced and every attempt failed, each paired
226	/// with its own error in dial order. All of them are kept: picking one to
227	/// report would bury a rejected certificate or a refused port behind
228	/// whichever address happened to be unroutable or to blackhole until its
229	/// timeout. A host with a single address reports that error directly instead.
230	#[error("all {} connection attempts failed: {}", .0.len(), crate::failover::describe(.0))]
231	Failover(Vec<crate::failover::Failure<Error>>),
232}
233
234impl crate::failover::Aggregate for Error {
235	fn aggregate(failures: Vec<crate::failover::Failure<Self>>) -> Self {
236		Self::Failover(failures)
237	}
238}
239
240type Result<T> = std::result::Result<T, Error>;
241
242// ── Client ──────────────────────────────────────────────────────────
243
244#[derive(Clone)]
245pub(crate) struct QuinnClient {
246	pub quic: quinn::Endpoint,
247	pub transport: Arc<quinn::TransportConfig>,
248	/// Whether an `http://` URL may bootstrap a pin (see [crate::tls::Client::allows_http_bootstrap]).
249	pub http_bootstrap: bool,
250	/// Optional TLS SNI / verification hostname override (from config).
251	pub host_name: Option<String>,
252	/// Stagger between Happy Eyeballs connection attempts (see [`crate::failover`]).
253	pub failover_delay: Duration,
254	/// Whether the bound socket really came back dual-stack, which decides
255	/// whether an IPv4 destination is reachable at all. Captured here because the
256	/// endpoint owns the socket from here on and `local_addr` can't tell us.
257	dual_stack: bool,
258}
259
260impl QuinnClient {
261	pub fn new(config: &ClientConfig) -> Result<Self> {
262		let socket = crate::bind::udp(config.bind).map_err(Error::BindSocket)?;
263		let dual_stack = crate::bind::udp_is_dual_stack(&socket);
264
265		let quic = config.quic.resolve();
266		let mut transport = quinn::TransportConfig::default();
267		apply_transport(&mut transport, &quic);
268		apply_qlog(&mut transport, &quic, "client")?;
269		let transport = Arc::new(transport);
270
271		// There's a bit more boilerplate to make a generic endpoint.
272		let runtime = quinn::default_runtime().ok_or(Error::NoRuntime)?;
273		let endpoint_config = quinn::EndpointConfig::default();
274
275		// Create the generic QUIC endpoint.
276		let quic = quinn::Endpoint::new(endpoint_config, None, socket, runtime).map_err(Error::CreateEndpoint)?;
277
278		Ok(Self {
279			quic,
280			transport,
281			http_bootstrap: config.tls.allows_http_bootstrap(),
282			host_name: config.tls.host_name.clone(),
283			failover_delay: config.effective_failover_delay(),
284			dual_stack,
285		})
286	}
287
288	pub async fn connect(
289		&self,
290		tls: &rustls::ClientConfig,
291		url: Url,
292		versions: &moq_net::Versions,
293	) -> Result<web_transport_quinn::Session> {
294		let mut url = url;
295		let mut config = tls.clone();
296
297		let host = url.host().ok_or(Error::InvalidDnsName)?.to_string();
298		let port = url.port().unwrap_or(443);
299
300		// Resolve every DNS entry, adapted to the local socket's family; the dial
301		// below races them Happy Eyeballs style so one broken family can't stall
302		// the connect.
303		let local = self.quic.local_addr().map_err(Error::LocalAddr)?;
304		let addrs = tokio::net::lookup_host((host.clone(), port))
305			.await
306			.map_err(Error::DnsLookup)?;
307		let candidates = crate::failover::match_local(addrs, local, self.dual_stack);
308		if candidates.is_empty() {
309			return Err(Error::NoDnsEntries);
310		}
311
312		if url.scheme() == "http" {
313			// Insecure per-connection bootstrap: only honored when no stronger
314			// verification is configured, so an attacker controlling the plaintext
315			// fetch can't weaken an explicit pin or re-enable disabled verification.
316			if self.http_bootstrap {
317				// Perform a HTTP request to fetch the certificate fingerprint.
318				let mut fingerprint = url.clone();
319				fingerprint.set_path("/certificate.sha256");
320				fingerprint.set_query(None);
321				fingerprint.set_fragment(None);
322
323				tracing::warn!(url = %fingerprint, "performing insecure HTTP request for certificate");
324
325				let resp = reqwest::get(fingerprint.as_str())
326					.await
327					.map_err(Error::FetchFingerprint)?
328					.error_for_status()
329					.map_err(Error::FingerprintStatus)?;
330
331				let fingerprint = resp.text().await.map_err(Error::ReadFingerprint)?;
332				let fingerprint = hex::decode(fingerprint.trim())?;
333
334				let verifier = FingerprintVerifier::new(config.crypto_provider().clone(), vec![fingerprint]);
335				config.dangerous().set_certificate_verifier(Arc::new(verifier));
336			} else {
337				tracing::warn!(
338					"ignoring insecure http:// fingerprint bootstrap; using the configured TLS verification"
339				);
340			}
341
342			url.set_scheme("https").expect("failed to set scheme");
343		}
344
345		let alpns: Vec<Vec<u8>> = match url.scheme() {
346			"https" => vec![web_transport_quinn::ALPN.as_bytes().to_vec()],
347			"moqt" | "moql" => versions.alpns().iter().map(|alpn| alpn.as_bytes().to_vec()).collect(),
348			_ => return Err(Error::InvalidScheme),
349		};
350
351		config.alpn_protocols = alpns;
352		config.key_log = Arc::new(rustls::KeyLogFile::new());
353
354		let config: quinn::crypto::rustls::QuicClientConfig = config.try_into()?;
355		let mut config = quinn::ClientConfig::new(Arc::new(config));
356		config.transport_config(self.transport.clone());
357
358		tracing::debug!(%url, ?candidates, "connecting");
359
360		// Use the configured host_name override for SNI + cert verification, else the URL host.
361		let host_name = self.host_name.clone().unwrap_or(host);
362
363		// Race only the QUIC handshake: the winner alone performs the WebTransport
364		// CONNECT below, so the server sees a single request no matter how many
365		// addresses were dialed.
366		let connection = crate::failover::race(candidates, self.failover_delay, |addr| {
367			let endpoint = self.quic.clone();
368			let config = config.clone();
369			let host_name = host_name.clone();
370			async move { Ok::<_, Error>(endpoint.connect_with(config, addr, &host_name)?.await?) }
371		})
372		.await?;
373		tracing::Span::current().record("id", connection.stable_id());
374
375		let mut request = web_transport_quinn::proto::ConnectRequest::new(url.clone());
376		for alpn in versions.alpns() {
377			request = request.with_protocol(alpn.to_string());
378		}
379
380		let session = match url.scheme() {
381			"https" => web_transport_quinn::Session::connect(connection, request)
382				.await
383				.map_err(map_client_error)?,
384			"moqt" | "moql" => {
385				let handshake = connection
386					.handshake_data()
387					.ok_or(Error::MissingHandshake)?
388					.downcast::<quinn::crypto::rustls::HandshakeData>()
389					.unwrap();
390
391				let alpn = handshake.protocol.ok_or(Error::MissingAlpn)?;
392				let alpn = String::from_utf8(alpn)?;
393
394				let response = web_transport_quinn::proto::ConnectResponse::OK.with_protocol(alpn);
395				web_transport_quinn::Session::raw(connection, request, response)
396			}
397			_ => return Err(Error::UnsupportedScheme(url.scheme().to_string())),
398		};
399
400		Ok(session)
401	}
402}
403
404impl Error {
405	pub(crate) fn connect_error(&self) -> Option<crate::ConnectError> {
406		match self {
407			Self::ConnectRejected(err) => Some(*err),
408			Self::Client(err) => classify_client_error(err),
409			Self::Failover(failures) => failures.iter().find_map(|failure| failure.error.connect_error()),
410			_ => None,
411		}
412	}
413}
414
415fn map_client_error(err: web_transport_quinn::ClientError) -> Error {
416	if let Some(err) = classify_client_error(&err) {
417		return err.into();
418	}
419
420	err.into()
421}
422
423fn classify_client_error(err: &web_transport_quinn::ClientError) -> Option<crate::ConnectError> {
424	match err {
425		web_transport_quinn::ClientError::HttpError(err) => classify_connect_error(err),
426		_ => None,
427	}
428}
429
430fn classify_connect_error(err: &web_transport_quinn::ConnectError) -> Option<crate::ConnectError> {
431	match err {
432		web_transport_quinn::ConnectError::ErrorStatus(status) => crate::ConnectError::from_status_u16(status.as_u16()),
433		web_transport_quinn::ConnectError::ProtoError(err) => classify_proto_error(err),
434		_ => None,
435	}
436}
437
438fn classify_proto_error(err: &web_transport_quinn::proto::ConnectError) -> Option<crate::ConnectError> {
439	match err {
440		web_transport_quinn::proto::ConnectError::ErrorStatus(status)
441		| web_transport_quinn::proto::ConnectError::WrongStatus(Some(status)) => {
442			crate::ConnectError::from_status_u16(status.as_u16())
443		}
444		_ => None,
445	}
446}
447
448// ── Server ──────────────────────────────────────────────────────────
449
450pub(crate) struct QuinnServer {
451	pub quic: quinn::Endpoint,
452	pub certs: Arc<ServeCerts>,
453}
454
455impl QuinnServer {
456	pub fn new(config: ServerConfig) -> Result<Self> {
457		let quic = config.quic.resolve();
458		let mut transport = quinn::TransportConfig::default();
459		apply_transport(&mut transport, &quic);
460		apply_qlog(&mut transport, &quic, "server")?;
461		let transport = Arc::new(transport);
462
463		let provider = crate::crypto::provider();
464
465		let certs = ServeCerts::new(provider.clone());
466		certs.load_certs(&config.tls)?;
467		let certs = Arc::new(certs);
468
469		let tls_builder = rustls::ServerConfig::builder_with_provider(provider.clone())
470			.with_protocol_versions(&[&rustls::version::TLS13])
471			.map_err(crate::tls::Error::from)?;
472
473		let mut tls = if config.tls.root.is_empty() {
474			tls_builder.with_no_client_auth().with_cert_resolver(certs.clone())
475		} else {
476			let roots = config.tls.load_roots()?;
477			let verifier = rustls::server::WebPkiClientVerifier::builder_with_provider(Arc::new(roots), provider)
478				.allow_unauthenticated()
479				.build()
480				.map_err(Error::ClientVerifier)?;
481			tls_builder
482				.with_client_cert_verifier(verifier)
483				.with_cert_resolver(certs.clone())
484		};
485
486		// H3 is last because it requires WebTransport framing which not all H3 endpoints support.
487		let mut alpns: Vec<Vec<u8>> = config
488			.versions()
489			.alpns()
490			.iter()
491			.map(|alpn| alpn.as_bytes().to_vec())
492			.collect();
493		alpns.push(web_transport_quinn::ALPN.as_bytes().to_vec());
494
495		tls.alpn_protocols = alpns;
496		tls.key_log = Arc::new(rustls::KeyLogFile::new());
497
498		let tls: quinn::crypto::rustls::QuicServerConfig = tls.try_into()?;
499		let mut tls = quinn::ServerConfig::with_crypto(Arc::new(tls));
500		tls.transport_config(transport);
501
502		// Advertise the preferred_address transport parameter (RFC 9000 §9.6).
503		// Quinn allocates a fresh CID + reset token for the address during the handshake.
504		if let Some(addr) = config.quic.preferred_v4 {
505			tls.preferred_address_v4(Some(addr));
506		}
507		if let Some(addr) = config.quic.preferred_v6 {
508			tls.preferred_address_v6(Some(addr));
509		}
510
511		// There's a bit more boilerplate to make a generic endpoint.
512		let runtime = quinn::default_runtime().ok_or(Error::NoRuntime)?;
513
514		let listen =
515			crate::util::resolve(config.bind.as_deref(), crate::server::DEFAULT_BIND).map_err(Error::ResolveBind)?;
516
517		// Configure connection ID generator with server ID if provided
518		let mut endpoint_config = quinn::EndpointConfig::default();
519		if let Some(server_id) = config.quic.quic_lb_id {
520			let nonce_len = config.quic.quic_lb_nonce.unwrap_or(8);
521			if nonce_len < 4 {
522				return Err(Error::QuicLbNonceTooSmall);
523			}
524
525			let cid_len = 1 + server_id.len() + nonce_len;
526			if cid_len > 20 {
527				return Err(Error::QuicLbCidTooLong(cid_len));
528			}
529
530			tracing::info!(
531				?server_id,
532				nonce_len,
533				"using QUIC-LB compatible connection ID generation"
534			);
535			endpoint_config.cid_generator(move || Box::new(ServerIdGenerator::new(server_id.clone(), nonce_len)));
536		}
537
538		let socket = crate::bind::udp(listen).map_err(Error::BindSocket)?;
539
540		// Create the generic QUIC endpoint.
541		let quic = quinn::Endpoint::new(endpoint_config, Some(tls), socket, runtime).map_err(Error::CreateEndpoint)?;
542
543		// Spawn the cert reload watcher only after endpoint creation succeeds,
544		// so we don't leave a dangling watcher on failure.
545		tokio::spawn(crate::tls::reload_certs(certs.clone(), config.tls.clone()));
546
547		Ok(Self { quic, certs })
548	}
549
550	pub fn accept(&self) -> impl std::future::Future<Output = Option<quinn::Incoming>> + '_ {
551		self.quic.accept()
552	}
553
554	pub fn certificates(&self) -> crate::tls::Certificates {
555		crate::tls::Certificates::new(self.certs.info.clone())
556	}
557
558	pub fn local_addr(&self) -> Result<net::SocketAddr> {
559		self.quic.local_addr().map_err(Error::LocalAddr)
560	}
561
562	pub fn close(&self) {
563		self.quic.close(quinn::VarInt::from_u32(0), b"server shutdown");
564	}
565}
566
567// ── QuinnRequest ────────────────────────────────────────────────────
568
569/// Accept a QUIC connection, negotiate WebTransport or raw moq, and complete the
570/// handshake (a `200 OK` for WebTransport). Returns the established session plus the
571/// request URL and validated mTLS identity, both captured before the response consumes
572/// the request. Raw QUIC carries no request URL (the path rides the SETUP instead).
573pub(crate) async fn accept(
574	conn: quinn::Incoming,
575	alpns: Vec<&'static str>,
576) -> Result<(
577	web_transport_quinn::Session,
578	Option<Url>,
579	Option<crate::tls::PeerIdentity>,
580)> {
581	let mut conn = conn.accept()?;
582
583	let handshake = conn
584		.handshake_data()
585		.await?
586		.downcast::<quinn::crypto::rustls::HandshakeData>()
587		.unwrap();
588
589	let alpn = handshake.protocol.ok_or(Error::MissingAlpn)?;
590	let alpn = String::from_utf8(alpn)?;
591	let host = handshake.server_name.unwrap_or_default();
592
593	tracing::debug!(%host, ip = %conn.remote_address(), %alpn, "accepting");
594
595	// Wait for the QUIC connection to be established.
596	let conn = conn.await.map_err(Error::Establish)?;
597
598	let span = tracing::Span::current();
599	span.record("id", conn.stable_id()); // TODO can we get this earlier?
600	tracing::debug!(%host, ip = %conn.remote_address(), %alpn, "accepted");
601
602	match alpn.as_str() {
603		web_transport_quinn::ALPN => {
604			// Wait for the CONNECT request, then capture its URL and mTLS identity before
605			// the response consumes it.
606			let request = web_transport_quinn::Request::accept(conn)
607				.await
608				.map_err(Error::RecvRequest)?;
609			let url = Some(request.url.clone());
610			let identity = crate::tls::PeerIdentity::from_any(request.conn().peer_identity());
611
612			let mut response = web_transport_quinn::proto::ConnectResponse::OK;
613			// Pick the first sub-protocol that we actually support.
614			// This is the WebTransport equivalent of ALPN negotiation.
615			// If no match is found, we default to no sub-protocol to support older
616			// clients that don't use ALPN. We assume moq-transport-14/moq-lite-02
617			// and perform the SETUP_x exchange instead.
618			if let Some(protocol) = request.protocols.iter().find(|p| alpns.contains(&p.as_str())) {
619				response = response.with_protocol(protocol);
620			}
621			let session = request.respond(response).await.map_err(Error::Server)?;
622			Ok((session, url, identity))
623		}
624		// Recognize any moq ALPN this server actually offered (its configured versions),
625		// not the global default set. rustls only negotiates an ALPN the server offered, so
626		// this covers opt-in / work-in-progress versions (e.g. moq-lite-06-wip) that are
627		// deliberately absent from `moq_net::ALPNS`.
628		alpn if alpns.contains(&alpn) => {
629			// Raw QUIC carries no in-band request URL like WebTransport's CONNECT, so the TLS
630			// SNI is the only authority the client can offer, and it's optional. A client dialing
631			// a bare IP sends no SNI (RFC 6066 forbids IP literals), leaving `host` empty; the
632			// resulting hostless `moqt://` routes to the root path, exactly like a URL-less stream
633			// transport. `url()` returns `None` for the raw variant either way.
634			let host_str = if host.contains(':') {
635				format!("[{}]", host)
636			} else {
637				host.clone()
638			};
639			let url = format!("moqt://{}", host_str).parse::<Url>().map_err(Error::BuildUrl)?;
640			let request = web_transport_quinn::proto::ConnectRequest::new(url);
641			let response = web_transport_quinn::proto::ConnectResponse::OK.with_protocol(alpn);
642			let identity = crate::tls::PeerIdentity::from_any(conn.peer_identity());
643			// Raw QUIC carries no request URL; the path rides the SETUP.
644			let session = web_transport_quinn::Session::raw(conn, request, response);
645			Ok((session, None, identity))
646		}
647		_ => Err(Error::UnsupportedAlpn(alpn)),
648	}
649}
650
651// ── ServerIdGenerator ───────────────────────────────────────────────
652
653struct ServerIdGenerator {
654	server_id: ServerId,
655	nonce_len: usize,
656}
657
658impl ServerIdGenerator {
659	fn new(server_id: ServerId, nonce_len: usize) -> Self {
660		Self { server_id, nonce_len }
661	}
662}
663
664impl quinn::ConnectionIdGenerator for ServerIdGenerator {
665	fn generate_cid(&mut self) -> quinn::ConnectionId {
666		use rand::RngExt;
667		let cid_len = self.cid_len();
668		let mut cid = Vec::with_capacity(cid_len);
669		// First byte has "self-encoded length" of server ID + nonce
670		cid.push((cid_len - 1) as u8);
671		cid.extend(self.server_id.0.iter());
672		cid.extend(rand::rng().random_iter::<u8>().take(self.nonce_len));
673		quinn::ConnectionId::new(cid.as_slice())
674	}
675
676	fn cid_len(&self) -> usize {
677		1 + self.server_id.len() + self.nonce_len
678	}
679
680	fn cid_lifetime(&self) -> Option<Duration> {
681		None
682	}
683}
684
685#[cfg(test)]
686mod tests {
687	use super::*;
688
689	/// Build a controller from each family's factory and downcast it to the
690	/// concrete quinn implementation it must map to.
691	#[test]
692	fn congestion_factory_maps_each_family() {
693		let now = std::time::Instant::now();
694		let mtu = 1200;
695
696		let loss = congestion_factory(CongestionControl::Loss).build(now, mtu);
697		assert!(loss.into_any().downcast::<quinn::congestion::Cubic>().is_ok());
698
699		let delay = congestion_factory(CongestionControl::Delay).build(now, mtu);
700		assert!(delay.into_any().downcast::<quinn::congestion::Bbr>().is_ok());
701	}
702
703	/// An unset knob must land on BBR rather than quinn's own CUBIC default.
704	#[test]
705	fn congestion_control_defaults_to_delay() {
706		let mut quic = crate::quic::Client::default();
707		assert_eq!(congestion_control(&quic.resolve()), CongestionControl::Delay);
708
709		// An explicit request still gets through.
710		quic.congestion_control = Some(CongestionControl::Loss);
711		assert_eq!(congestion_control(&quic.resolve()), CongestionControl::Loss);
712	}
713
714	/// Loopback regression test: a config selecting BBR must produce live
715	/// connections that actually run quinn's BBR controller, on both ends.
716	#[tokio::test]
717	async fn delay_reaches_the_live_connection() {
718		let server_config = ServerConfig {
719			bind: Some("127.0.0.1:0".to_string()),
720			tls: crate::tls::Server {
721				generate: vec!["localhost".into()],
722				..Default::default()
723			},
724			quic: crate::quic::Server {
725				congestion_control: Some(CongestionControl::Delay),
726				..Default::default()
727			},
728			..Default::default()
729		};
730
731		let server = QuinnServer::new(server_config).expect("server init");
732		let addr = server.local_addr().expect("local addr");
733
734		let accepted = tokio::spawn(async move {
735			let incoming = server.accept().await.expect("no incoming connection");
736			let conn = incoming.accept().expect("accept").await.expect("handshake");
737			conn.congestion_state()
738				.into_any()
739				.downcast::<quinn::congestion::Bbr>()
740				.is_ok()
741		});
742
743		// tls::Client has a private field, so it can't be built with a struct literal.
744		let mut tls_config = crate::tls::Client::default();
745		tls_config.disable_verify = Some(true);
746
747		let client_config = ClientConfig {
748			bind: "127.0.0.1:0".parse().unwrap(),
749			tls: tls_config,
750			quic: crate::quic::Client {
751				congestion_control: Some(CongestionControl::Delay),
752				..Default::default()
753			},
754			..Default::default()
755		};
756
757		let tls = client_config.tls.build().expect("tls config");
758		let client = QuinnClient::new(&client_config).expect("client init");
759		// Dial the loopback IP directly so the system resolver is never involved.
760		let url: Url = format!("moqt://127.0.0.1:{}", addr.port()).parse().unwrap();
761
762		// Bound the whole connect + accept + assert flow so a handshake
763		// regression fails fast instead of stalling CI.
764		tokio::time::timeout(Duration::from_secs(5), async move {
765			let session = client
766				.connect(&tls, url, &moq_net::Versions::default())
767				.await
768				.expect("connect failed");
769
770			// web_transport_quinn::Session derefs to the quinn connection.
771			assert!(
772				session
773					.congestion_state()
774					.into_any()
775					.downcast::<quinn::congestion::Bbr>()
776					.is_ok(),
777				"client connection is not running BBR"
778			);
779			assert!(
780				accepted.await.expect("server task panicked"),
781				"server connection is not running BBR"
782			);
783		})
784		.await
785		.expect("test timed out");
786	}
787}