moq_native/
server.rs

1use std::path::PathBuf;
2use std::{net, sync::Arc, time::Duration};
3
4use crate::crypto;
5use anyhow::Context;
6use rustls::pki_types::{CertificateDer, PrivatePkcs8KeyDer};
7use rustls::server::{ClientHello, ResolvesServerCert};
8use rustls::sign::CertifiedKey;
9use std::fs;
10use std::io::{self, Cursor, Read};
11use url::Url;
12use web_transport_quinn::http;
13
14use futures::future::BoxFuture;
15use futures::stream::{FuturesUnordered, StreamExt};
16use futures::FutureExt;
17
18#[derive(clap::Args, Clone, Debug, serde::Serialize, serde::Deserialize)]
19#[serde(deny_unknown_fields)]
20pub struct ServerTlsCert {
21	pub chain: PathBuf,
22	pub key: PathBuf,
23}
24
25impl ServerTlsCert {
26	// A crude colon separated string parser just for clap support.
27	pub fn parse(s: &str) -> anyhow::Result<Self> {
28		let (chain, key) = s.split_once(':').context("invalid certificate")?;
29		Ok(Self {
30			chain: PathBuf::from(chain),
31			key: PathBuf::from(key),
32		})
33	}
34}
35
36#[derive(clap::Args, Clone, Default, Debug, serde::Serialize, serde::Deserialize)]
37#[serde(deny_unknown_fields)]
38pub struct ServerTlsConfig {
39	/// Load the given certificate from disk.
40	#[arg(long = "tls-cert", id = "tls-cert", env = "MOQ_SERVER_TLS_CERT")]
41	#[serde(default, skip_serializing_if = "Vec::is_empty")]
42	pub cert: Vec<PathBuf>,
43
44	/// Load the given key from disk.
45	#[arg(long = "tls-key", id = "tls-key", env = "MOQ_SERVER_TLS_KEY")]
46	#[serde(default, skip_serializing_if = "Vec::is_empty")]
47	pub key: Vec<PathBuf>,
48
49	/// Or generate a new certificate and key with the given hostnames.
50	/// This won't be valid unless the client uses the fingerprint or disables verification.
51	#[arg(
52		long = "tls-generate",
53		id = "tls-generate",
54		value_delimiter = ',',
55		env = "MOQ_SERVER_TLS_GENERATE"
56	)]
57	#[serde(default, skip_serializing_if = "Vec::is_empty")]
58	pub generate: Vec<String>,
59}
60
61#[derive(clap::Args, Clone, Debug, Default, serde::Serialize, serde::Deserialize)]
62#[serde(deny_unknown_fields, default)]
63pub struct ServerConfig {
64	/// Listen for UDP packets on the given address.
65	/// Defaults to `[::]:443` if not provided.
66	#[arg(long, env = "MOQ_SERVER_LISTEN")]
67	pub listen: Option<net::SocketAddr>,
68
69	#[command(flatten)]
70	#[serde(default)]
71	pub tls: ServerTlsConfig,
72}
73
74impl ServerConfig {
75	pub fn init(self) -> anyhow::Result<Server> {
76		Server::new(self)
77	}
78}
79
80pub struct Server {
81	quic: quinn::Endpoint,
82	accept: FuturesUnordered<BoxFuture<'static, anyhow::Result<Request>>>,
83	fingerprints: Vec<String>,
84}
85
86impl Server {
87	pub fn new(config: ServerConfig) -> anyhow::Result<Self> {
88		// Enable BBR congestion control
89		// TODO Validate the BBR implementation before enabling it
90		let mut transport = quinn::TransportConfig::default();
91		transport.max_idle_timeout(Some(Duration::from_secs(10).try_into().unwrap()));
92		transport.keep_alive_interval(Some(Duration::from_secs(4)));
93		//transport.congestion_controller_factory(Arc::new(quinn::congestion::BbrConfig::default()));
94		transport.mtu_discovery_config(None); // Disable MTU discovery
95		let transport = Arc::new(transport);
96
97		let provider = crypto::provider();
98
99		let mut serve = ServeCerts::new(provider.clone());
100
101		// Load the certificate and key files based on their index.
102		anyhow::ensure!(
103			config.tls.cert.len() == config.tls.key.len(),
104			"must provide both cert and key"
105		);
106
107		for (cert, key) in config.tls.cert.iter().zip(config.tls.key.iter()) {
108			serve.load(cert, key)?;
109		}
110
111		if !config.tls.generate.is_empty() {
112			serve.generate(&config.tls.generate)?;
113		}
114
115		let fingerprints = serve.fingerprints();
116
117		let mut tls = rustls::ServerConfig::builder_with_provider(provider)
118			.with_protocol_versions(&[&rustls::version::TLS13])?
119			.with_no_client_auth()
120			.with_cert_resolver(Arc::new(serve));
121
122		tls.alpn_protocols = vec![
123			web_transport_quinn::ALPN.as_bytes().to_vec(),
124			moq_lite::ALPN.as_bytes().to_vec(),
125		];
126		tls.key_log = Arc::new(rustls::KeyLogFile::new());
127
128		let tls: quinn::crypto::rustls::QuicServerConfig = tls.try_into()?;
129		let mut tls = quinn::ServerConfig::with_crypto(Arc::new(tls));
130		tls.transport_config(transport.clone());
131
132		// There's a bit more boilerplate to make a generic endpoint.
133		let runtime = quinn::default_runtime().context("no async runtime")?;
134		let endpoint_config = quinn::EndpointConfig::default();
135
136		let listen = config.listen.unwrap_or("[::]:443".parse().unwrap());
137		let socket = std::net::UdpSocket::bind(listen).context("failed to bind UDP socket")?;
138
139		// Create the generic QUIC endpoint.
140		let quic = quinn::Endpoint::new(endpoint_config, Some(tls), socket, runtime)
141			.context("failed to create QUIC endpoint")?;
142
143		Ok(Self {
144			quic: quic.clone(),
145			accept: Default::default(),
146			fingerprints,
147		})
148	}
149
150	pub fn fingerprints(&self) -> &[String] {
151		&self.fingerprints
152	}
153
154	/// Returns the next partially established QUIC or WebTransport session.
155	///
156	/// This returns a [Request] instead of a [web_transport_quinn::Session]
157	/// so the connection can be rejected early on an invalid path or missing auth.
158	///
159	/// The [Request] is either a WebTransport or a raw QUIC request.
160	/// Call [Request::ok] or [Request::close] to complete the handshake in case this is
161	/// a WebTransport request.
162	pub async fn accept(&mut self) -> Option<Request> {
163		loop {
164			tokio::select! {
165				res = self.quic.accept() => {
166					let conn = res?;
167					self.accept.push(Self::accept_session(conn).boxed());
168				}
169				Some(res) = self.accept.next() => {
170					match res {
171						Ok(session) => return Some(session),
172						Err(err) => tracing::debug!(%err, "failed to accept session"),
173					}
174				}
175				_ = tokio::signal::ctrl_c() => {
176					self.close();
177					// Give it a chance to close.
178					tokio::time::sleep(Duration::from_millis(100)).await;
179
180					return None;
181				}
182			}
183		}
184	}
185
186	async fn accept_session(conn: quinn::Incoming) -> anyhow::Result<Request> {
187		let mut conn = conn.accept()?;
188
189		let handshake = conn
190			.handshake_data()
191			.await?
192			.downcast::<quinn::crypto::rustls::HandshakeData>()
193			.unwrap();
194
195		let alpn = handshake.protocol.context("missing ALPN")?;
196		let alpn = String::from_utf8(alpn).context("failed to decode ALPN")?;
197		let host = handshake.server_name.unwrap_or_default();
198
199		tracing::debug!(%host, ip = %conn.remote_address(), %alpn, "accepting");
200
201		// Wait for the QUIC connection to be established.
202		let conn = conn.await.context("failed to establish QUIC connection")?;
203
204		let span = tracing::Span::current();
205		span.record("id", conn.stable_id()); // TODO can we get this earlier?
206		tracing::debug!(%host, ip = %conn.remote_address(), %alpn, "accepted");
207
208		match alpn.as_str() {
209			web_transport_quinn::ALPN => {
210				// Wait for the CONNECT request.
211				let request = web_transport_quinn::Request::accept(conn)
212					.await
213					.context("failed to receive WebTransport request")?;
214				Ok(Request::WebTransport(request))
215			}
216			moq_lite::ALPN => Ok(Request::Quic(QuicRequest::accept(conn))),
217			_ => anyhow::bail!("unsupported ALPN: {alpn}"),
218		}
219	}
220
221	pub fn local_addr(&self) -> anyhow::Result<net::SocketAddr> {
222		self.quic.local_addr().context("failed to get local address")
223	}
224
225	pub fn close(&mut self) {
226		self.quic.close(quinn::VarInt::from_u32(0), b"server shutdown");
227	}
228}
229
230pub enum Request {
231	WebTransport(web_transport_quinn::Request),
232	Quic(QuicRequest),
233}
234
235impl Request {
236	/// Reject the session, returning your favorite HTTP status code.
237	pub async fn close(self, status: http::StatusCode) -> Result<(), quinn::WriteError> {
238		match self {
239			Self::WebTransport(request) => request.close(status).await,
240			Self::Quic(request) => {
241				request.close(status);
242				Ok(())
243			}
244		}
245	}
246
247	/// Accept the session.
248	///
249	/// For WebTransport, this completes the HTTP handshake (200 OK).
250	/// For raw QUIC, this constructs a raw session.
251	pub async fn ok(self) -> Result<web_transport_quinn::Session, quinn::WriteError> {
252		match self {
253			Request::WebTransport(request) => request.ok().await,
254			Request::Quic(request) => Ok(request.ok()),
255		}
256	}
257
258	/// Returns the URL provided by the client.
259	pub fn url(&self) -> &Url {
260		match self {
261			Request::WebTransport(request) => request.url(),
262			Request::Quic(request) => request.url(),
263		}
264	}
265}
266
267pub struct QuicRequest {
268	connection: quinn::Connection,
269	url: Url,
270}
271
272impl QuicRequest {
273	/// Accept a new QUIC session from a client.
274	pub fn accept(connection: quinn::Connection) -> Self {
275		let url: Url = format!("moql://{}", connection.remote_address())
276			.parse()
277			.expect("URL is valid");
278		Self { connection, url }
279	}
280
281	/// Accept the session, returning a 200 OK if using WebTransport.
282	pub fn ok(self) -> web_transport_quinn::Session {
283		web_transport_quinn::Session::raw(self.connection, self.url)
284	}
285
286	/// Returns the URL provided by the client.
287	pub fn url(&self) -> &Url {
288		&self.url
289	}
290
291	/// Reject the session with a status code.
292	///
293	/// The status code number will be used as the error code.
294	pub fn close(self, status: http::StatusCode) {
295		self.connection
296			.close(status.as_u16().into(), status.as_str().as_bytes());
297	}
298}
299
300#[derive(Debug)]
301struct ServeCerts {
302	certs: Vec<Arc<CertifiedKey>>,
303	provider: crypto::Provider,
304}
305
306impl ServeCerts {
307	pub fn new(provider: crypto::Provider) -> Self {
308		Self {
309			certs: Vec::new(),
310			provider,
311		}
312	}
313
314	// Load a certificate and corresponding key from a file
315	pub fn load(&mut self, chain: &PathBuf, key: &PathBuf) -> anyhow::Result<()> {
316		let chain = fs::File::open(chain).context("failed to open cert file")?;
317		let mut chain = io::BufReader::new(chain);
318
319		let chain: Vec<CertificateDer> = rustls_pemfile::certs(&mut chain)
320			.collect::<Result<_, _>>()
321			.context("failed to read certs")?;
322
323		anyhow::ensure!(!chain.is_empty(), "could not find certificate");
324
325		// Read the PEM private key
326		let mut keys = fs::File::open(key).context("failed to open key file")?;
327
328		// Read the keys into a Vec so we can parse it twice.
329		let mut buf = Vec::new();
330		keys.read_to_end(&mut buf)?;
331
332		let key = rustls_pemfile::private_key(&mut Cursor::new(&buf))?.context("missing private key")?;
333		let key = self.provider.key_provider.load_private_key(key)?;
334
335		self.certs.push(Arc::new(CertifiedKey::new(chain, key)));
336
337		Ok(())
338	}
339
340	pub fn generate(&mut self, hostnames: &[String]) -> anyhow::Result<()> {
341		let key_pair = rcgen::KeyPair::generate()?;
342
343		let mut params = rcgen::CertificateParams::new(hostnames)?;
344
345		// Make the certificate valid for two weeks, starting yesterday (in case of clock drift).
346		// WebTransport certificates MUST be valid for two weeks at most.
347		params.not_before = time::OffsetDateTime::now_utc() - time::Duration::days(1);
348		params.not_after = params.not_before + time::Duration::days(14);
349
350		// Generate the certificate
351		let cert = params.self_signed(&key_pair)?;
352
353		// Convert the rcgen type to the rustls type.
354		let key_der = key_pair.serialized_der().to_vec();
355		let key_der = PrivatePkcs8KeyDer::from(key_der);
356		let key = self.provider.key_provider.load_private_key(key_der.into())?;
357
358		// Create a rustls::sign::CertifiedKey
359		self.certs.push(Arc::new(CertifiedKey::new(vec![cert.into()], key)));
360
361		Ok(())
362	}
363
364	// Return the SHA256 fingerprints of all our certificates.
365	pub fn fingerprints(&self) -> Vec<String> {
366		self.certs
367			.iter()
368			.map(|ck| {
369				let fingerprint = crate::crypto::sha256(&self.provider, ck.cert[0].as_ref());
370				hex::encode(fingerprint)
371			})
372			.collect()
373	}
374
375	// Return the best certificate for the given ClientHello.
376	fn best_certificate(&self, client_hello: &ClientHello<'_>) -> Option<Arc<CertifiedKey>> {
377		let server_name = client_hello.server_name()?;
378		let dns_name = rustls::pki_types::ServerName::try_from(server_name).ok()?;
379
380		for ck in &self.certs {
381			let leaf: webpki::EndEntityCert = ck
382				.end_entity_cert()
383				.expect("missing certificate")
384				.try_into()
385				.expect("failed to parse certificate");
386
387			if leaf.verify_is_valid_for_subject_name(&dns_name).is_ok() {
388				return Some(ck.clone());
389			}
390		}
391
392		None
393	}
394}
395
396impl ResolvesServerCert for ServeCerts {
397	fn resolve(&self, client_hello: ClientHello<'_>) -> Option<Arc<CertifiedKey>> {
398		if let Some(cert) = self.best_certificate(&client_hello) {
399			return Some(cert);
400		}
401
402		// If this happens, it means the client was trying to connect to an unknown hostname.
403		// We do our best and return the first certificate.
404		tracing::warn!(server_name = ?client_hello.server_name(), "no SNI certificate found");
405
406		self.certs.first().cloned()
407	}
408}