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 returned no address usable from the local socket, usually an address family mismatch.
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
226type Result<T> = std::result::Result<T, Error>;
227
228// ── Client ──────────────────────────────────────────────────────────
229
230#[derive(Clone)]
231pub(crate) struct QuinnClient {
232	pub quic: quinn::Endpoint,
233	pub transport: Arc<quinn::TransportConfig>,
234	/// Whether an `http://` URL may bootstrap a pin (see [crate::tls::Client::allows_http_bootstrap]).
235	pub http_bootstrap: bool,
236	/// Optional TLS SNI / verification hostname override (from config).
237	pub host_name: Option<String>,
238	/// Whether the bound socket really came back dual-stack, which decides
239	/// whether an IPv4 destination is reachable at all. Captured here because the
240	/// endpoint owns the socket from here on and `local_addr` can't tell us.
241	dual_stack: bool,
242}
243
244impl QuinnClient {
245	pub fn new(config: &ClientConfig) -> Result<Self> {
246		let socket = crate::bind::udp(config.bind).map_err(Error::BindSocket)?;
247		let dual_stack = crate::bind::udp_is_dual_stack(&socket);
248
249		let quic = config.quic.resolve();
250		let mut transport = quinn::TransportConfig::default();
251		apply_transport(&mut transport, &quic);
252		apply_qlog(&mut transport, &quic, "client")?;
253		let transport = Arc::new(transport);
254
255		// There's a bit more boilerplate to make a generic endpoint.
256		let runtime = quinn::default_runtime().ok_or(Error::NoRuntime)?;
257		let endpoint_config = quinn::EndpointConfig::default();
258
259		// Create the generic QUIC endpoint.
260		let quic = quinn::Endpoint::new(endpoint_config, None, socket, runtime).map_err(Error::CreateEndpoint)?;
261
262		Ok(Self {
263			quic,
264			transport,
265			http_bootstrap: config.tls.allows_http_bootstrap(),
266			host_name: config.tls.host_name.clone(),
267			dual_stack,
268		})
269	}
270
271	pub async fn connect(
272		&self,
273		tls: &rustls::ClientConfig,
274		url: Url,
275		versions: &moq_net::Versions,
276	) -> Result<web_transport_quinn::Session> {
277		let mut url = url;
278		let mut config = tls.clone();
279
280		let host = url.host().ok_or(Error::InvalidDnsName)?.to_string();
281		let port = url.port().unwrap_or(443);
282
283		// Look up the DNS entry. Quinn doesn't support happy eyeballs, so we commit to
284		// a single address; `pick_addr` documents how that one is chosen.
285		let local = self.quic.local_addr().map_err(Error::LocalAddr)?;
286		let addrs = tokio::net::lookup_host((host.clone(), port))
287			.await
288			.map_err(Error::DnsLookup)?;
289		let ip = crate::util::pick_addr(addrs, local, self.dual_stack).ok_or(Error::NoDnsEntries)?;
290
291		if url.scheme() == "http" {
292			// Insecure per-connection bootstrap: only honored when no stronger
293			// verification is configured, so an attacker controlling the plaintext
294			// fetch can't weaken an explicit pin or re-enable disabled verification.
295			if self.http_bootstrap {
296				// Perform a HTTP request to fetch the certificate fingerprint.
297				let mut fingerprint = url.clone();
298				fingerprint.set_path("/certificate.sha256");
299				fingerprint.set_query(None);
300				fingerprint.set_fragment(None);
301
302				tracing::warn!(url = %fingerprint, "performing insecure HTTP request for certificate");
303
304				let resp = reqwest::get(fingerprint.as_str())
305					.await
306					.map_err(Error::FetchFingerprint)?
307					.error_for_status()
308					.map_err(Error::FingerprintStatus)?;
309
310				let fingerprint = resp.text().await.map_err(Error::ReadFingerprint)?;
311				let fingerprint = hex::decode(fingerprint.trim())?;
312
313				let verifier = FingerprintVerifier::new(config.crypto_provider().clone(), vec![fingerprint]);
314				config.dangerous().set_certificate_verifier(Arc::new(verifier));
315			} else {
316				tracing::warn!(
317					"ignoring insecure http:// fingerprint bootstrap; using the configured TLS verification"
318				);
319			}
320
321			url.set_scheme("https").expect("failed to set scheme");
322		}
323
324		let alpns: Vec<Vec<u8>> = match url.scheme() {
325			"https" => vec![web_transport_quinn::ALPN.as_bytes().to_vec()],
326			"moqt" | "moql" => versions.alpns().iter().map(|alpn| alpn.as_bytes().to_vec()).collect(),
327			_ => return Err(Error::InvalidScheme),
328		};
329
330		config.alpn_protocols = alpns;
331		config.key_log = Arc::new(rustls::KeyLogFile::new());
332
333		let config: quinn::crypto::rustls::QuicClientConfig = config.try_into()?;
334		let mut config = quinn::ClientConfig::new(Arc::new(config));
335		config.transport_config(self.transport.clone());
336
337		tracing::debug!(%url, %ip, "connecting");
338
339		// Use the configured host_name override for SNI + cert verification, else the URL host.
340		let host_name = self.host_name.clone().unwrap_or(host);
341
342		let connection = self.quic.connect_with(config, ip, &host_name)?.await?;
343		tracing::Span::current().record("id", connection.stable_id());
344
345		let mut request = web_transport_quinn::proto::ConnectRequest::new(url.clone());
346		for alpn in versions.alpns() {
347			request = request.with_protocol(alpn.to_string());
348		}
349
350		let session = match url.scheme() {
351			"https" => web_transport_quinn::Session::connect(connection, request)
352				.await
353				.map_err(map_client_error)?,
354			"moqt" | "moql" => {
355				let handshake = connection
356					.handshake_data()
357					.ok_or(Error::MissingHandshake)?
358					.downcast::<quinn::crypto::rustls::HandshakeData>()
359					.unwrap();
360
361				let alpn = handshake.protocol.ok_or(Error::MissingAlpn)?;
362				let alpn = String::from_utf8(alpn)?;
363
364				let response = web_transport_quinn::proto::ConnectResponse::OK.with_protocol(alpn);
365				web_transport_quinn::Session::raw(connection, request, response)
366			}
367			_ => return Err(Error::UnsupportedScheme(url.scheme().to_string())),
368		};
369
370		Ok(session)
371	}
372}
373
374impl Error {
375	pub(crate) fn connect_error(&self) -> Option<crate::ConnectError> {
376		match self {
377			Self::ConnectRejected(err) => Some(*err),
378			Self::Client(err) => classify_client_error(err),
379			_ => None,
380		}
381	}
382}
383
384fn map_client_error(err: web_transport_quinn::ClientError) -> Error {
385	if let Some(err) = classify_client_error(&err) {
386		return err.into();
387	}
388
389	err.into()
390}
391
392fn classify_client_error(err: &web_transport_quinn::ClientError) -> Option<crate::ConnectError> {
393	match err {
394		web_transport_quinn::ClientError::HttpError(err) => classify_connect_error(err),
395		_ => None,
396	}
397}
398
399fn classify_connect_error(err: &web_transport_quinn::ConnectError) -> Option<crate::ConnectError> {
400	match err {
401		web_transport_quinn::ConnectError::ErrorStatus(status) => crate::ConnectError::from_status_u16(status.as_u16()),
402		web_transport_quinn::ConnectError::ProtoError(err) => classify_proto_error(err),
403		_ => None,
404	}
405}
406
407fn classify_proto_error(err: &web_transport_quinn::proto::ConnectError) -> Option<crate::ConnectError> {
408	match err {
409		web_transport_quinn::proto::ConnectError::ErrorStatus(status)
410		| web_transport_quinn::proto::ConnectError::WrongStatus(Some(status)) => {
411			crate::ConnectError::from_status_u16(status.as_u16())
412		}
413		_ => None,
414	}
415}
416
417// ── Server ──────────────────────────────────────────────────────────
418
419pub(crate) struct QuinnServer {
420	pub quic: quinn::Endpoint,
421	pub certs: Arc<ServeCerts>,
422}
423
424impl QuinnServer {
425	pub fn new(config: ServerConfig) -> Result<Self> {
426		let quic = config.quic.resolve();
427		let mut transport = quinn::TransportConfig::default();
428		apply_transport(&mut transport, &quic);
429		apply_qlog(&mut transport, &quic, "server")?;
430		let transport = Arc::new(transport);
431
432		let provider = crate::crypto::provider();
433
434		let certs = ServeCerts::new(provider.clone());
435		certs.load_certs(&config.tls)?;
436		let certs = Arc::new(certs);
437
438		let tls_builder = rustls::ServerConfig::builder_with_provider(provider.clone())
439			.with_protocol_versions(&[&rustls::version::TLS13])
440			.map_err(crate::tls::Error::from)?;
441
442		let mut tls = if config.tls.root.is_empty() {
443			tls_builder.with_no_client_auth().with_cert_resolver(certs.clone())
444		} else {
445			let roots = config.tls.load_roots()?;
446			let verifier = rustls::server::WebPkiClientVerifier::builder_with_provider(Arc::new(roots), provider)
447				.allow_unauthenticated()
448				.build()
449				.map_err(Error::ClientVerifier)?;
450			tls_builder
451				.with_client_cert_verifier(verifier)
452				.with_cert_resolver(certs.clone())
453		};
454
455		// H3 is last because it requires WebTransport framing which not all H3 endpoints support.
456		let mut alpns: Vec<Vec<u8>> = config
457			.versions()
458			.alpns()
459			.iter()
460			.map(|alpn| alpn.as_bytes().to_vec())
461			.collect();
462		alpns.push(web_transport_quinn::ALPN.as_bytes().to_vec());
463
464		tls.alpn_protocols = alpns;
465		tls.key_log = Arc::new(rustls::KeyLogFile::new());
466
467		let tls: quinn::crypto::rustls::QuicServerConfig = tls.try_into()?;
468		let mut tls = quinn::ServerConfig::with_crypto(Arc::new(tls));
469		tls.transport_config(transport);
470
471		// Advertise the preferred_address transport parameter (RFC 9000 §9.6).
472		// Quinn allocates a fresh CID + reset token for the address during the handshake.
473		if let Some(addr) = config.quic.preferred_v4 {
474			tls.preferred_address_v4(Some(addr));
475		}
476		if let Some(addr) = config.quic.preferred_v6 {
477			tls.preferred_address_v6(Some(addr));
478		}
479
480		// There's a bit more boilerplate to make a generic endpoint.
481		let runtime = quinn::default_runtime().ok_or(Error::NoRuntime)?;
482
483		let listen =
484			crate::util::resolve(config.bind.as_deref(), crate::server::DEFAULT_BIND).map_err(Error::ResolveBind)?;
485
486		// Configure connection ID generator with server ID if provided
487		let mut endpoint_config = quinn::EndpointConfig::default();
488		if let Some(server_id) = config.quic.quic_lb_id {
489			let nonce_len = config.quic.quic_lb_nonce.unwrap_or(8);
490			if nonce_len < 4 {
491				return Err(Error::QuicLbNonceTooSmall);
492			}
493
494			let cid_len = 1 + server_id.len() + nonce_len;
495			if cid_len > 20 {
496				return Err(Error::QuicLbCidTooLong(cid_len));
497			}
498
499			tracing::info!(
500				?server_id,
501				nonce_len,
502				"using QUIC-LB compatible connection ID generation"
503			);
504			endpoint_config.cid_generator(move || Box::new(ServerIdGenerator::new(server_id.clone(), nonce_len)));
505		}
506
507		let socket = crate::bind::udp(listen).map_err(Error::BindSocket)?;
508
509		// Create the generic QUIC endpoint.
510		let quic = quinn::Endpoint::new(endpoint_config, Some(tls), socket, runtime).map_err(Error::CreateEndpoint)?;
511
512		// Spawn the cert reload watcher only after endpoint creation succeeds,
513		// so we don't leave a dangling watcher on failure.
514		tokio::spawn(crate::tls::reload_certs(certs.clone(), config.tls.clone()));
515
516		Ok(Self { quic, certs })
517	}
518
519	pub fn accept(&self) -> impl std::future::Future<Output = Option<quinn::Incoming>> + '_ {
520		self.quic.accept()
521	}
522
523	pub fn certificates(&self) -> crate::tls::Certificates {
524		crate::tls::Certificates::new(self.certs.info.clone())
525	}
526
527	pub fn local_addr(&self) -> Result<net::SocketAddr> {
528		self.quic.local_addr().map_err(Error::LocalAddr)
529	}
530
531	pub fn close(&self) {
532		self.quic.close(quinn::VarInt::from_u32(0), b"server shutdown");
533	}
534}
535
536// ── QuinnRequest ────────────────────────────────────────────────────
537
538/// Accept a QUIC connection, negotiate WebTransport or raw moq, and complete the
539/// handshake (a `200 OK` for WebTransport). Returns the established session plus the
540/// request URL and validated mTLS identity, both captured before the response consumes
541/// the request. Raw QUIC carries no request URL (the path rides the SETUP instead).
542pub(crate) async fn accept(
543	conn: quinn::Incoming,
544	alpns: Vec<&'static str>,
545) -> Result<(
546	web_transport_quinn::Session,
547	Option<Url>,
548	Option<crate::tls::PeerIdentity>,
549)> {
550	let mut conn = conn.accept()?;
551
552	let handshake = conn
553		.handshake_data()
554		.await?
555		.downcast::<quinn::crypto::rustls::HandshakeData>()
556		.unwrap();
557
558	let alpn = handshake.protocol.ok_or(Error::MissingAlpn)?;
559	let alpn = String::from_utf8(alpn)?;
560	let host = handshake.server_name.unwrap_or_default();
561
562	tracing::debug!(%host, ip = %conn.remote_address(), %alpn, "accepting");
563
564	// Wait for the QUIC connection to be established.
565	let conn = conn.await.map_err(Error::Establish)?;
566
567	let span = tracing::Span::current();
568	span.record("id", conn.stable_id()); // TODO can we get this earlier?
569	tracing::debug!(%host, ip = %conn.remote_address(), %alpn, "accepted");
570
571	match alpn.as_str() {
572		web_transport_quinn::ALPN => {
573			// Wait for the CONNECT request, then capture its URL and mTLS identity before
574			// the response consumes it.
575			let request = web_transport_quinn::Request::accept(conn)
576				.await
577				.map_err(Error::RecvRequest)?;
578			let url = Some(request.url.clone());
579			let identity = crate::tls::PeerIdentity::from_any(request.conn().peer_identity());
580
581			let mut response = web_transport_quinn::proto::ConnectResponse::OK;
582			// Pick the first sub-protocol that we actually support.
583			// This is the WebTransport equivalent of ALPN negotiation.
584			// If no match is found, we default to no sub-protocol to support older
585			// clients that don't use ALPN. We assume moq-transport-14/moq-lite-02
586			// and perform the SETUP_x exchange instead.
587			if let Some(protocol) = request.protocols.iter().find(|p| alpns.contains(&p.as_str())) {
588				response = response.with_protocol(protocol);
589			}
590			let session = request.respond(response).await.map_err(Error::Server)?;
591			Ok((session, url, identity))
592		}
593		// Recognize any moq ALPN this server actually offered (its configured versions),
594		// not the global default set. rustls only negotiates an ALPN the server offered, so
595		// this covers opt-in / work-in-progress versions (e.g. moq-lite-06-wip) that are
596		// deliberately absent from `moq_net::ALPNS`.
597		alpn if alpns.contains(&alpn) => {
598			// Raw QUIC carries no in-band request URL like WebTransport's CONNECT, so the TLS
599			// SNI is the only authority the client can offer, and it's optional. A client dialing
600			// a bare IP sends no SNI (RFC 6066 forbids IP literals), leaving `host` empty; the
601			// resulting hostless `moqt://` routes to the root path, exactly like a URL-less stream
602			// transport. `url()` returns `None` for the raw variant either way.
603			let host_str = if host.contains(':') {
604				format!("[{}]", host)
605			} else {
606				host.clone()
607			};
608			let url = format!("moqt://{}", host_str).parse::<Url>().map_err(Error::BuildUrl)?;
609			let request = web_transport_quinn::proto::ConnectRequest::new(url);
610			let response = web_transport_quinn::proto::ConnectResponse::OK.with_protocol(alpn);
611			let identity = crate::tls::PeerIdentity::from_any(conn.peer_identity());
612			// Raw QUIC carries no request URL; the path rides the SETUP.
613			let session = web_transport_quinn::Session::raw(conn, request, response);
614			Ok((session, None, identity))
615		}
616		_ => Err(Error::UnsupportedAlpn(alpn)),
617	}
618}
619
620// ── ServerIdGenerator ───────────────────────────────────────────────
621
622struct ServerIdGenerator {
623	server_id: ServerId,
624	nonce_len: usize,
625}
626
627impl ServerIdGenerator {
628	fn new(server_id: ServerId, nonce_len: usize) -> Self {
629		Self { server_id, nonce_len }
630	}
631}
632
633impl quinn::ConnectionIdGenerator for ServerIdGenerator {
634	fn generate_cid(&mut self) -> quinn::ConnectionId {
635		use rand::RngExt;
636		let cid_len = self.cid_len();
637		let mut cid = Vec::with_capacity(cid_len);
638		// First byte has "self-encoded length" of server ID + nonce
639		cid.push((cid_len - 1) as u8);
640		cid.extend(self.server_id.0.iter());
641		cid.extend(rand::rng().random_iter::<u8>().take(self.nonce_len));
642		quinn::ConnectionId::new(cid.as_slice())
643	}
644
645	fn cid_len(&self) -> usize {
646		1 + self.server_id.len() + self.nonce_len
647	}
648
649	fn cid_lifetime(&self) -> Option<Duration> {
650		None
651	}
652}
653
654#[cfg(test)]
655mod tests {
656	use super::*;
657
658	/// Build a controller from each family's factory and downcast it to the
659	/// concrete quinn implementation it must map to.
660	#[test]
661	fn congestion_factory_maps_each_family() {
662		let now = std::time::Instant::now();
663		let mtu = 1200;
664
665		let loss = congestion_factory(CongestionControl::Loss).build(now, mtu);
666		assert!(loss.into_any().downcast::<quinn::congestion::Cubic>().is_ok());
667
668		let delay = congestion_factory(CongestionControl::Delay).build(now, mtu);
669		assert!(delay.into_any().downcast::<quinn::congestion::Bbr>().is_ok());
670	}
671
672	/// An unset knob must land on BBR rather than quinn's own CUBIC default.
673	#[test]
674	fn congestion_control_defaults_to_delay() {
675		let mut quic = crate::quic::Client::default();
676		assert_eq!(congestion_control(&quic.resolve()), CongestionControl::Delay);
677
678		// An explicit request still gets through.
679		quic.congestion_control = Some(CongestionControl::Loss);
680		assert_eq!(congestion_control(&quic.resolve()), CongestionControl::Loss);
681	}
682
683	/// Loopback regression test: a config selecting BBR must produce live
684	/// connections that actually run quinn's BBR controller, on both ends.
685	#[tokio::test]
686	async fn delay_reaches_the_live_connection() {
687		let server_config = ServerConfig {
688			bind: Some("127.0.0.1:0".to_string()),
689			tls: crate::tls::Server {
690				generate: vec!["localhost".into()],
691				..Default::default()
692			},
693			quic: crate::quic::Server {
694				congestion_control: Some(CongestionControl::Delay),
695				..Default::default()
696			},
697			..Default::default()
698		};
699
700		let server = QuinnServer::new(server_config).expect("server init");
701		let addr = server.local_addr().expect("local addr");
702
703		let accepted = tokio::spawn(async move {
704			let incoming = server.accept().await.expect("no incoming connection");
705			let conn = incoming.accept().expect("accept").await.expect("handshake");
706			conn.congestion_state()
707				.into_any()
708				.downcast::<quinn::congestion::Bbr>()
709				.is_ok()
710		});
711
712		// tls::Client has a private field, so it can't be built with a struct literal.
713		let mut tls_config = crate::tls::Client::default();
714		tls_config.disable_verify = Some(true);
715
716		let client_config = ClientConfig {
717			bind: "127.0.0.1:0".parse().unwrap(),
718			tls: tls_config,
719			quic: crate::quic::Client {
720				congestion_control: Some(CongestionControl::Delay),
721				..Default::default()
722			},
723			..Default::default()
724		};
725
726		let tls = client_config.tls.build().expect("tls config");
727		let client = QuinnClient::new(&client_config).expect("client init");
728		// Dial the loopback IP directly so the system resolver is never involved.
729		let url: Url = format!("moqt://127.0.0.1:{}", addr.port()).parse().unwrap();
730
731		// Bound the whole connect + accept + assert flow so a handshake
732		// regression fails fast instead of stalling CI.
733		tokio::time::timeout(Duration::from_secs(5), async move {
734			let session = client
735				.connect(&tls, url, &moq_net::Versions::default())
736				.await
737				.expect("connect failed");
738
739			// web_transport_quinn::Session derefs to the quinn connection.
740			assert!(
741				session
742					.congestion_state()
743					.into_any()
744					.downcast::<quinn::congestion::Bbr>()
745					.is_ok(),
746				"client connection is not running BBR"
747			);
748			assert!(
749				accepted.await.expect("server task panicked"),
750				"server connection is not running BBR"
751			);
752		})
753		.await
754		.expect("test timed out");
755	}
756}