Skip to main content

rocket/listener/
quic.rs

1//! Experimental support for Quic and HTTP/3.
2//!
3//! To enable Rocket's experimental support for HTTP/3 and Quic, enable the
4//! `http3-preview` feature and provide a valid TLS configuration:
5//!
6//! ```toml
7//! // Add the following to your Cargo.toml:
8//! [dependencies]
9//! rocket = { version = "=0.6.0-rc.1", features = ["http3-preview"] }
10//!
11//! // In your Rocket.toml or other equivalent config source:
12//! [default.tls]
13//! certs = "private/rsa_sha256_cert.pem"
14//! key = "private/rsa_sha256_key.pem"
15//! ```
16//!
17//! The launch message confirms that Rocket is serving traffic over Quic in
18//! addition to TCP:
19//!
20//! ```sh
21//! > ๐Ÿš€ Rocket has launched on https://127.0.0.1:8000 (QUIC + mTLS)
22//! ```
23
24use std::io;
25use std::net::SocketAddr;
26use std::pin::{pin, Pin};
27use std::sync::Arc;
28use std::task::{ready, Context, Poll};
29
30use bytes::{Buf, Bytes};
31use futures::{Stream, StreamExt};
32use h3::server::RequestStream;
33use quinn::crypto::rustls::QuicServerConfig;
34
35use crate::tls::{TlsConfig, Error};
36use crate::listener::{AsyncCancel, Certificates};
37use crate::shutdown::Shutdown;
38
39pub(crate) type Connection = h3::server::Connection<h3_quinn::Connection, Bytes>;
40
41/// The receiving half of an HTTP/3 request stream: the request body.
42pub struct QuicRx(pub(crate) RequestStream<h3_quinn::RecvStream, Bytes>);
43
44/// The sending half of an HTTP/3 request stream: the response.
45///
46/// Dropping a `QuicTx` before the response is complete resets the stream so
47/// that the client cannot mistake a truncated response for a complete one.
48pub(crate) struct QuicTx {
49    stream: RequestStream<h3_quinn::SendStream<Bytes>, Bytes>,
50    grace: Shutdown,
51    done: bool,
52}
53
54/// Binds a QUIC endpoint to `addr` using Rocket's TLS configuration `tls`.
55pub(crate) async fn bind(addr: SocketAddr, tls: &TlsConfig) -> Result<quinn::Endpoint, Error> {
56    let mut tls_config = tls.server_config().await?;
57    tls_config.alpn_protocols = vec![b"h3".to_vec()];
58
59    let quic_config = QuicServerConfig::try_from(tls_config)
60        .map_err(|e| Error::Bind(Box::new(e)))?;
61
62    let server_config = quinn::ServerConfig::with_crypto(Arc::new(quic_config));
63    Ok(quinn::Endpoint::server(server_config, addr)?)
64}
65
66/// Returns the TLS certificate chain presented by the peer of `conn`, if any.
67pub(crate) fn certificates(conn: &quinn::Connection) -> Option<Certificates<'static>> {
68    #[cfg(feature = "mtls")] {
69        let certs = conn.peer_identity()?;
70        let certs = certs.downcast::<Vec<rustls::pki_types::CertificateDer<'static>>>().ok()?;
71        Some(Certificates::from(*certs))
72    }
73
74    #[cfg(not(feature = "mtls"))] {
75        let _ = conn;
76        None
77    }
78}
79
80/// Returns the server name (SNI) requested by the peer of `conn`, if any.
81pub(crate) fn server_name(conn: &quinn::Connection) -> Option<String> {
82    let data = conn.handshake_data()?;
83    data.downcast::<quinn::crypto::rustls::HandshakeData>().ok()?.server_name
84}
85
86/// Sends `response`, streaming the body as it becomes available.
87pub(crate) async fn send_response<S>(tx: &mut QuicTx, response: http::Response<S>) -> io::Result<()>
88    where S: Stream<Item = io::Result<Bytes>>
89{
90    let (mut parts, body) = response.into_parts();
91    strip_connection_headers(&mut parts.headers);
92    let stream = &mut tx.stream;
93    stream.send_response(http::Response::from_parts(parts, ())).await.map_err(io::Error::other)?;
94
95    let mut body = pin!(body);
96    while let Some(chunk) = body.next().await {
97        stream.send_data(chunk?).await.map_err(io::Error::other)?;
98    }
99
100    stream.finish().await.map_err(io::Error::other)?;
101    tx.done = true;
102    Ok(())
103}
104
105/// Removes the connection-specific headers that HTTP/3 forbids (RFC 9114
106/// ยง4.2): the same headers hyper removes from HTTP/2 responses.
107fn strip_connection_headers(headers: &mut http::HeaderMap) {
108    use http::header::{HeaderName, CONNECTION, TE, TRANSFER_ENCODING, UPGRADE};
109
110    let keep_alive = HeaderName::from_static("keep-alive");
111    let proxy_connection = HeaderName::from_static("proxy-connection");
112    for name in [keep_alive, proxy_connection, TRANSFER_ENCODING, UPGRADE, TE] {
113        headers.remove(name);
114    }
115
116    // `Connection` may name other headers that are specific to the connection.
117    let names: Vec<_> = headers.get_all(CONNECTION).iter()
118        .filter_map(|names| names.to_str().ok())
119        .flat_map(|names| names.split(','))
120        .map(|name| name.trim().to_string())
121        .collect();
122
123    headers.remove(CONNECTION);
124    for name in names {
125        headers.remove(name);
126    }
127}
128
129impl QuicTx {
130    /// Wraps the sending half of a request stream. A response that is cut
131    /// short once `grace` has elapsed is reset as cancelled.
132    pub(crate) fn new(
133        stream: RequestStream<h3_quinn::SendStream<Bytes>, Bytes>,
134        grace: Shutdown,
135    ) -> Self {
136        QuicTx { stream, grace, done: false }
137    }
138}
139
140impl Drop for QuicTx {
141    fn drop(&mut self) {
142        if !self.done {
143            let code = match self.grace.notified() {
144                true => h3::error::Code::H3_REQUEST_CANCELLED,
145                false => h3::error::Code::H3_INTERNAL_ERROR,
146            };
147
148            self.stream.stop_stream(code);
149        }
150    }
151}
152
153/// Logs an error from serving an HTTP/3 connection or request. A client
154/// closing its connection, cancelling a request, or going idle is routine and
155/// logged at `debug`. Other errors from h3 or quinn are logged at `warn`, as
156/// hyper's are. Any other error is a server error.
157pub(crate) fn log_error(error: &io::Error) {
158    use h3::error::{Code, ConnectionError, LocalError, StreamError};
159    use h3::quic::ConnectionErrorIncoming;
160
161    fn quinn_routine(error: &quinn::ConnectionError) -> bool {
162        use quinn::ConnectionError::*;
163
164        match error {
165            ApplicationClosed(close) => close.error_code.into_inner() == Code::H3_NO_ERROR.value(),
166            Reset | TimedOut | LocallyClosed => true,
167            _ => false,
168        }
169    }
170
171    // h3's error variants are non-exhaustive, so fields are matched by name.
172    fn h3_routine(error: &ConnectionError) -> bool {
173        match error {
174            ConnectionError::Timeout { .. } => true,
175            ConnectionError::Local { error: LocalError::Closing { .. }, .. } => true,
176            ConnectionError::Remote { 0: ConnectionErrorIncoming::Timeout, .. } => true,
177            ConnectionError::Remote { 0: ConnectionErrorIncoming::Undefined(e), .. } => {
178                e.downcast_ref().is_some_and(quinn_routine)
179            }
180            error => error.is_h3_no_error(),
181        }
182    }
183
184    let Some(inner) = error.get_ref() else {
185        return crate::error::log_server_error(error);
186    };
187
188    let routine = if let Some(e) = inner.downcast_ref::<ConnectionError>() {
189        h3_routine(e)
190    } else if let Some(e) = inner.downcast_ref::<StreamError>() {
191        match e {
192            StreamError::RemoteTerminate { .. } | StreamError::RemoteClosing { .. } => true,
193            StreamError::ConnectionError { 0: e, .. } => h3_routine(e),
194            _ => false,
195        }
196    } else if let Some(e) = inner.downcast_ref::<quinn::ConnectionError>() {
197        quinn_routine(e)
198    } else if inner.is::<tokio::time::error::Elapsed>() {
199        false
200    } else {
201        return crate::error::log_server_error(error);
202    };
203
204    match routine {
205        true => debug!(error = %error, "http/3 connection or request closed"),
206        false => warn!(error = %error, "http/3 connection or request failed"),
207    }
208}
209
210impl Stream for QuicRx {
211    type Item = io::Result<Bytes>;
212
213    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
214        match ready!(self.0.poll_recv_data(cx)) {
215            Ok(Some(mut buf)) => Poll::Ready(Some(Ok(buf.copy_to_bytes(buf.remaining())))),
216            Ok(None) => Poll::Ready(None),
217            Err(e) => Poll::Ready(Some(Err(io::Error::other(e)))),
218        }
219    }
220}
221
222impl AsyncCancel for QuicRx {
223    fn poll_cancel(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<io::Result<()>> {
224        // The stream is dropped once cancelled, which stops the client from
225        // sending. `stop_sending()` would panic here if a read were pending.
226        Poll::Ready(Ok(()))
227    }
228}