Skip to main content

tokio_quiche/
lib.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//! Bridging the gap between [quiche] and [tokio].
28//!
29//! tokio-quiche connects [quiche::Connection]s and [quiche::h3::Connection]s to
30//! tokio's event loop. Users have the choice between implementing their own,
31//! custom [`ApplicationOverQuic`] or using the ready-made
32//! [H3Driver](crate::http3::driver::H3Driver) for HTTP/3 clients and servers.
33//!
34//! # Starting an HTTP/3 Server
35//!
36//! A server [`listen`]s on a UDP socket for QUIC connections and spawns a new
37//! tokio task to handle each individual connection.
38//!
39//! ```
40//! use futures::stream::StreamExt;
41//! use tokio_quiche::http3::settings::Http3Settings;
42//! use tokio_quiche::listen;
43//! use tokio_quiche::metrics::DefaultMetrics;
44//! use tokio_quiche::quic::SimpleConnectionIdGenerator;
45//! use tokio_quiche::ConnectionParams;
46//! use tokio_quiche::ServerH3Driver;
47//!
48//! # async fn example() -> tokio_quiche::QuicResult<()> {
49//! let socket = tokio::net::UdpSocket::bind("0.0.0.0:443").await?;
50//! let mut listeners =
51//!     listen([socket], ConnectionParams::default(), DefaultMetrics)?;
52//! let mut accept_stream = &mut listeners[0];
53//!
54//! while let Some(conn) = accept_stream.next().await {
55//!     let (driver, mut controller) =
56//!         ServerH3Driver::new(Http3Settings::default());
57//!     conn?.start(driver);
58//!
59//!     tokio::spawn(async move {
60//!         // `controller` is the handle to our established HTTP/3 connection.
61//!         // For example, inbound requests are available as H3Events via:
62//!         let event = controller.event_receiver_mut().recv().await;
63//!     });
64//! }
65//! # Ok(())
66//! # }
67//! ```
68//!
69//! For client-side use cases, check out our [`connect`](crate::quic::connect)
70//! API.
71//!
72//! # Feature Flags
73//!
74//! tokio-quiche supports a number of feature flags to enable experimental
75//! features, performance enhancements, and additional telemetry. By default, no
76//! feature flags are enabled.
77//!
78//! - `rpk`: Support for raw public keys (RPK) in QUIC handshakes (via
79//!   [boring]).
80//! - `gcongestion`: Replace quiche's original congestion control implementation
81//!   with one adapted from google/quiche.
82//! - `zero-copy`: Use zero-copy sends with quiche (implies `gcongestion`).
83//! - `perf-quic-listener-metrics`: Extra telemetry for QUIC handshake
84//!   durations, including protocol overhead and network delays.
85//! - `tokio-task-metrics`: Scheduling & poll duration histograms for tokio
86//!   tasks.
87//!
88//! Other parts of the crate are enabled by separate build flags instead, to be
89//! controlled by the final binary:
90//!
91//! - `--cfg capture_keylogs`: Optional `SSLKEYLOGFILE` capturing for QUIC
92//!   connections.
93
94pub extern crate quiche;
95
96pub mod buf_factory;
97pub mod http3;
98pub mod metrics;
99pub mod quic;
100mod result;
101pub mod settings;
102pub mod socket;
103
104pub use buffer_pool;
105pub use datagram_socket;
106
107use foundations::telemetry::settings::LogVerbosity;
108use std::io;
109use std::sync::Arc;
110use std::sync::Once;
111use tokio::net::UdpSocket;
112use tokio_stream::wrappers::ReceiverStream;
113
114use crate::metrics::Metrics;
115use crate::socket::QuicListener;
116
117pub use crate::http3::driver::ClientH3Controller;
118pub use crate::http3::driver::ClientH3Driver;
119pub use crate::http3::driver::ServerH3Controller;
120pub use crate::http3::driver::ServerH3Driver;
121pub use crate::http3::ClientH3Connection;
122pub use crate::http3::ServerH3Connection;
123pub use crate::quic::connection::ApplicationOverQuic;
124pub use crate::quic::connection::ConnectionIdGenerator;
125pub use crate::quic::connection::InitialQuicConnection;
126pub use crate::quic::connection::QuicConnection;
127pub use crate::result::BoxError;
128pub use crate::result::QuicResult;
129pub use crate::settings::ConnectionParams;
130
131#[doc(hidden)]
132pub use crate::result::QuicResultExt;
133
134/// A stream of accepted [`InitialQuicConnection`]s from a [`listen`] call.
135///
136/// Errors from processing the client's QUIC initials can also be emitted on
137/// this stream. These do not indicate that the listener itself has failed.
138pub type QuicConnectionStream<M> =
139    ReceiverStream<io::Result<InitialQuicConnection<UdpSocket, M>>>;
140
141/// Starts listening for inbound QUIC connections on the given
142/// [`QuicListener`]s.
143///
144/// Each socket starts a separate tokio task to process and route inbound
145/// packets. This task emits connections on the respective
146/// [`QuicConnectionStream`] after receiving the client's QUIC initial and
147/// (optionally) validating its IP address.
148///
149/// The task shuts down when the returned stream is closed (or dropped) and all
150/// previously-yielded connections are closed.
151pub fn listen_with_capabilities<M>(
152    sockets: impl IntoIterator<Item = QuicListener>, params: ConnectionParams,
153    metrics: M,
154) -> io::Result<Vec<QuicConnectionStream<M>>>
155where
156    M: Metrics,
157{
158    if params.settings.capture_quiche_logs {
159        capture_quiche_logs();
160    }
161
162    sockets
163        .into_iter()
164        .map(|s| crate::quic::start_listener(s, &params, metrics.clone()))
165        .collect()
166}
167
168/// Starts listening for inbound QUIC connections on the given `sockets`.
169///
170/// Each socket is converted into a [`QuicListener`] with defaulted socket
171/// parameters. The listeners are then passed to [`listen_with_capabilities`].
172pub fn listen<S, M>(
173    sockets: impl IntoIterator<Item = S>, params: ConnectionParams, metrics: M,
174) -> io::Result<Vec<QuicConnectionStream<M>>>
175where
176    S: TryInto<QuicListener, Error = io::Error>,
177    M: Metrics,
178{
179    let quic_sockets: Vec<QuicListener> = sockets
180        .into_iter()
181        .map(|s| {
182            #[cfg_attr(not(target_os = "linux"), expect(unused_mut))]
183            let mut socket = s.try_into()?;
184            #[cfg(target_os = "linux")]
185            socket.apply_max_capabilities();
186            Ok(socket)
187        })
188        .collect::<io::Result<_>>()?;
189
190    listen_with_capabilities(quic_sockets, params, metrics)
191}
192
193static GLOBAL_LOGGER_ONCE: Once = Once::new();
194
195/// Forward Quiche logs into the slog::Drain currently used by Foundations
196///
197/// # Warning
198///
199/// This should **only be used for local debugging**. Quiche can potentially
200/// emit lots (and lots, and lots) of logs (the TRACE level emits a log record
201/// on every packet and frame) and you can very easily overwhelm your logging
202/// pipeline.
203///
204/// # Note
205///
206/// Quiche uses the `env_logger` crate, which uses `log` under the hood. `log`
207/// requires that you only set the global logger once. That means that we have
208/// to register the logger at `listen()` time for servers - for clients, we
209/// should register loggers when the `quiche::Connection` is established.
210pub(crate) fn capture_quiche_logs() {
211    GLOBAL_LOGGER_ONCE.call_once(|| {
212        use foundations::telemetry::log as foundations_log;
213        use log::Level as std_level;
214
215        let curr_logger =
216            Arc::clone(&foundations_log::slog_logger()).read().clone();
217        let scope_guard = slog_scope::set_global_logger(curr_logger);
218
219        // Convert slog::Level from Foundations settings to log::Level
220        let normalized_level = match foundations_log::verbosity() {
221            LogVerbosity::Critical | LogVerbosity::Error => std_level::Error,
222            LogVerbosity::Warning => std_level::Warn,
223            LogVerbosity::Info => std_level::Info,
224            LogVerbosity::Debug => std_level::Debug,
225            LogVerbosity::Trace => std_level::Trace,
226        };
227
228        slog_stdlog::init_with_level(normalized_level).unwrap();
229
230        // The slog Drain becomes `slog::Discard` when the scope_guard is dropped,
231        // and you can't set the global logger again because of a mandate
232        // in the `log` crate. We have to manually `forget` the scope
233        // guard so that the logger remains registered for the duration of the
234        // process.
235        std::mem::forget(scope_guard)
236    });
237}