tokio_quiche/quic/mod.rs
1// Copyright (C) 2025, Cloudflare, Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8// * Redistributions of source code must retain the above copyright notice,
9// this list of conditions and the following disclaimer.
10//
11// * Redistributions in binary form must reproduce the above copyright
12// notice, this list of conditions and the following disclaimer in the
13// documentation and/or other materials provided with the distribution.
14//
15// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
16// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
17// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
18// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
19// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
20// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
22// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
23// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
24// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26
27//! `async`-ified QUIC connections powered by [quiche].
28//!
29//! Hooking up a [quiche::Connection] to [tokio]'s executor and IO primitives
30//! requires an [`ApplicationOverQuic`] to control the connection. The
31//! application exposes a small number of callbacks which are executed whenever
32//! there is work to do with the connection.
33//!
34//! The primary entrypoints to set up a connection are [`listen`][listen] for
35//! servers and [`connect`] for clients.
36//! [`listen_with_capabilities`](crate::listen_with_capabilities)
37//! and [`connect_with_config`] exist for scenarios that require more in-depth
38//! configuration. Lastly, the [`raw`] submodule allows users to take full
39//! control over connection creation and its ingress path.
40//!
41//! # QUIC Connection Internals
42//!
43//! 
44//!
45//! *Note: Internal details are subject to change between minor versions.*
46//!
47//! tokio-quiche conceptually separates a network socket into a `recv` half and
48//! a `send` half. The `recv` half can only sensibly be used by one async task
49//! at a time, while many tasks can `send` packets on the socket concurrently.
50//! Thus, we spawn a dedicated `InboundPacketRouter` task for each socket which
51//! becomes the sole owner of the socket's `recv` half. It decodes the QUIC
52//! header in each packet, looks up the destination connection ID (DCID), and
53//! forwards the packet to the connection's `IoWorker` task.
54//!
55//! If the packet initiates a new connection, it is passed to an
56//! `InitialPacketHandler` with logic for either the client- or server-side
57//! connection setup. The purple `ConnectionAcceptor` depicted above is the
58//! server-side implementation. It optionally validates the client's IP
59//! address with a `RETRY` packet before packaging the nascent connection into
60//! an [`InitialQuicConnection`][iqc] and sending it to the
61//! [`QuicConnectionStream`] returned by [`listen`][listen].
62//!
63//! At this point the caller of [`listen`][listen] has control of the
64//! [`InitialQuicConnection`][iqc] (`IQC`). Now an `IoWorker` task needs to be
65//! spawned to continue driving the connection. This is possible with
66//! `IQC::handshake` or `IQC::start` (see the [`InitialQuicConnection`][iqc]
67//! docs). Client-side connections use the same infrastructure (except for the
68//! `InitialPacketHandler`), but [`connect`] immediately consumes the
69//! [`QuicConnectionStream`] and calls `IQC::start`.
70//!
71//! `IoWorker` is responsible for feeding inbound packets into the underlying
72//! [`quiche::Connection`], executing the [`ApplicationOverQuic`] callbacks, and
73//! flushing outbound packets to the network via the socket's shared `send`
74//! half. It loops through these operations in the order shown above, yielding
75//! only when sending packets and on `wait_for_data` calls. New inbound packets
76//! or a timeout can also restart the loop while `wait_for_data` is pending.
77//! This continues until the connection is closed or the [`ApplicationOverQuic`]
78//! returns an error.
79//!
80//! [listen]: crate::listen
81//! [iqc]: crate::InitialQuicConnection
82
83use std::sync::Arc;
84use std::time::Duration;
85
86use datagram_socket::DatagramSocketRecv;
87use datagram_socket::DatagramSocketSend;
88use foundations::telemetry::log;
89
90use crate::http3::settings::Http3Settings;
91use crate::metrics::DefaultMetrics;
92use crate::metrics::Metrics;
93use crate::settings::Config;
94use crate::socket::QuicListener;
95use crate::socket::Socket;
96use crate::ClientH3Controller;
97use crate::ClientH3Driver;
98use crate::ConnectionParams;
99use crate::QuicConnectionStream;
100use crate::QuicResult;
101use crate::QuicResultExt;
102
103mod addr_validation_token;
104pub(crate) mod connection;
105mod hooks;
106mod io;
107pub mod raw;
108mod router;
109
110use self::connection::ApplicationOverQuic;
111use self::connection::ConnectionIdGenerator as _;
112use self::connection::QuicConnection;
113use self::router::acceptor::ConnectionAcceptor;
114use self::router::acceptor::ConnectionAcceptorConfig;
115use self::router::connector::ClientConnector;
116use self::router::InboundPacketRouter;
117
118pub use self::connection::ConnectionShutdownBehaviour;
119pub use self::connection::HandshakeError;
120pub use self::connection::HandshakeInfo;
121pub use self::connection::Incoming;
122pub use self::connection::QuicCommand;
123pub use self::connection::QuicConnectionStats;
124pub use self::connection::SimpleConnectionIdGenerator;
125pub use self::hooks::ConnectionHook;
126
127/// Alias of [quiche::Connection] used internally by the crate.
128pub type QuicheConnection = quiche::Connection<crate::buf_factory::BufFactory>;
129
130fn make_qlog_writer(
131 dir: &str, id: &str,
132) -> std::io::Result<std::io::BufWriter<std::fs::File>> {
133 let mut path = std::path::PathBuf::from(dir);
134 let filename = format!("{id}.sqlog");
135 path.push(filename);
136
137 let f = std::fs::File::create(&path)?;
138 Ok(std::io::BufWriter::new(f))
139}
140
141/// Connects to an HTTP/3 server using `socket` and the default client
142/// configuration.
143///
144/// This function always uses the [`ApplicationOverQuic`] provided in
145/// [`http3::driver`](crate::http3::driver) and returns a corresponding
146/// [ClientH3Controller]. To specify a different implementation or customize the
147/// configuration, use [`connect_with_config`].
148///
149/// # Note
150/// tokio-quiche currently only supports one client connection per socket.
151/// Sharing a socket among multiple connections will lead to lost packets as
152/// both connections try to read from the shared socket.
153pub async fn connect<Tx, Rx, S>(
154 socket: S, host: Option<&str>,
155) -> QuicResult<(QuicConnection, ClientH3Controller)>
156where
157 Tx: DatagramSocketSend + Send + 'static,
158 Rx: DatagramSocketRecv + Unpin + 'static,
159 S: TryInto<Socket<Tx, Rx>>,
160 S::Error: std::error::Error + Send + Sync + 'static,
161{
162 // Don't apply_max_capabilities(): some NICs don't support GSO
163 let socket: Socket<Tx, Rx> = socket.try_into()?;
164
165 let (h3_driver, h3_controller) =
166 ClientH3Driver::new(Http3Settings::default());
167 let mut params = ConnectionParams::default();
168 params.settings.max_idle_timeout = Some(Duration::from_secs(30));
169
170 Ok((
171 connect_with_config(socket, host, ¶ms, h3_driver).await?,
172 h3_controller,
173 ))
174}
175
176/// Connects to a QUIC server using `socket` and the provided
177/// [`ApplicationOverQuic`].
178///
179/// When the future resolves, the connection has completed its handshake and
180/// `app` is running in the worker task. In case the handshake failed, we close
181/// the connection automatically and the future will resolve with an error.
182///
183/// # Note
184/// tokio-quiche currently only supports one client connection per socket.
185/// Sharing a socket among multiple connections will lead to lost packets as
186/// both connections try to read from the shared socket.
187pub async fn connect_with_config<Tx, Rx, App>(
188 socket: Socket<Tx, Rx>, host: Option<&str>, params: &ConnectionParams<'_>,
189 app: App,
190) -> QuicResult<QuicConnection>
191where
192 Tx: DatagramSocketSend + Send + 'static,
193 Rx: DatagramSocketRecv + Unpin + 'static,
194 App: ApplicationOverQuic,
195{
196 let mut client_config = Config::new(params, socket.capabilities)?;
197 let scid = SimpleConnectionIdGenerator.new_connection_id();
198
199 let mut quiche_conn = quiche::connect_with_buffer_factory(
200 host,
201 &scid,
202 socket.local_addr,
203 socket.peer_addr,
204 client_config.as_mut(),
205 )?;
206
207 log::info!("created unestablished quiche::Connection"; "scid" => ?scid);
208
209 if let Some(session) = ¶ms.session {
210 quiche_conn.set_session(session).map_err(|error| {
211 log::error!("application provided an invalid session"; "error"=>?error);
212 quiche::Error::CryptoFail
213 })?;
214 }
215
216 // Set the qlog writer here instead of in the `ClientConnector` to avoid
217 // missing logs from early in the connection
218 if let Some(qlog_dir) = &client_config.qlog_dir {
219 log::info!("setting up qlogs"; "qlog_dir"=>qlog_dir);
220 let id = format!("{:?}", &scid);
221 if let Ok(writer) = make_qlog_writer(qlog_dir, &id) {
222 quiche_conn.set_qlog(
223 std::boxed::Box::new(writer),
224 "tokio-quiche qlog".to_string(),
225 format!("tokio-quiche qlog id={id}"),
226 );
227 }
228 }
229
230 // Set the keylog file here for the same reason
231 if let Some(keylog_file) = &client_config.keylog_file {
232 log::info!("setting up keylog file");
233 if let Ok(keylog_clone) = keylog_file.try_clone() {
234 quiche_conn.set_keylog(Box::new(keylog_clone));
235 }
236 }
237
238 let socket_tx = Arc::new(socket.send);
239 let socket_rx = socket.recv;
240
241 let (router, mut quic_connection_stream) = InboundPacketRouter::new(
242 client_config,
243 Arc::clone(&socket_tx),
244 socket_rx,
245 socket.local_addr,
246 ClientConnector::new(socket_tx, quiche_conn),
247 DefaultMetrics,
248 );
249
250 // drive the packet router:
251 tokio::spawn(async move {
252 match router.await {
253 Ok(()) => log::debug!("incoming packet router finished"),
254 Err(error) => {
255 log::error!("incoming packet router failed"; "error"=>error)
256 },
257 }
258 });
259
260 Ok(quic_connection_stream
261 .recv()
262 .await
263 .ok_or("unable to establish connection")??
264 .start(app))
265}
266
267pub(crate) fn start_listener<M>(
268 socket: QuicListener, params: &ConnectionParams, metrics: M,
269) -> std::io::Result<QuicConnectionStream<M>>
270where
271 M: Metrics,
272{
273 #[cfg(unix)]
274 assert!(
275 datagram_socket::is_nonblocking(&socket).unwrap_or_default(),
276 "O_NONBLOCK should be set for the listening socket"
277 );
278
279 let config = Config::new(params, socket.capabilities).into_io()?;
280
281 let local_addr = socket.socket.local_addr()?;
282 let socket_tx = Arc::new(socket.socket);
283 let socket_rx = Arc::clone(&socket_tx);
284
285 let acceptor = ConnectionAcceptor::new(
286 ConnectionAcceptorConfig {
287 disable_client_ip_validation: config.disable_client_ip_validation,
288 qlog_dir: config.qlog_dir.clone(),
289 keylog_file: config
290 .keylog_file
291 .as_ref()
292 .and_then(|f| f.try_clone().ok()),
293 #[cfg(target_os = "linux")]
294 with_pktinfo: if local_addr.is_ipv4() {
295 config.has_ippktinfo
296 } else {
297 config.has_ipv6pktinfo
298 },
299 },
300 Arc::clone(&socket_tx),
301 Default::default(),
302 socket.cid_generator,
303 metrics.clone(),
304 );
305
306 let (socket_driver, accept_stream) = InboundPacketRouter::new(
307 config,
308 socket_tx,
309 socket_rx,
310 local_addr,
311 acceptor,
312 metrics.clone(),
313 );
314
315 crate::metrics::tokio_task::spawn("quic_udp_listener", metrics, async move {
316 match socket_driver.await {
317 Ok(()) => log::trace!("incoming packet router finished"),
318 Err(error) => {
319 log::error!("incoming packet router failed"; "error"=>error)
320 },
321 }
322 });
323 Ok(QuicConnectionStream::new(accept_stream))
324}