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`: Deprecated. Zero-copy sends are now always enabled. This
83//!   feature is kept for backwards compatibility and only enables
84//!   `gcongestion`.
85//! - `perf-quic-listener-metrics`: Extra telemetry for QUIC handshake
86//!   durations, including protocol overhead and network delays.
87//! - `tokio-task-metrics`: Scheduling & poll duration histograms for tokio
88//!   tasks.
89//!
90//! Other parts of the crate are enabled by separate build flags instead, to be
91//! controlled by the final binary:
92//!
93//! - `--cfg capture_keylogs`: Optional `SSLKEYLOGFILE` capturing for QUIC
94//!   connections.
95
96pub extern crate quiche;
97
98pub mod buf_factory;
99pub mod http3;
100pub mod metrics;
101pub mod quic;
102mod result;
103pub mod settings;
104pub mod socket;
105
106pub use datagram_socket;
107
108use foundations::telemetry::settings::LogVerbosity;
109use std::io;
110use std::sync::Arc;
111use std::sync::Once;
112use tokio::net::UdpSocket;
113use tokio_stream::wrappers::ReceiverStream;
114
115use crate::metrics::Metrics;
116use crate::socket::QuicListener;
117
118pub use crate::http3::driver::ClientH3Controller;
119pub use crate::http3::driver::ClientH3Driver;
120pub use crate::http3::driver::ServerH3Controller;
121pub use crate::http3::driver::ServerH3Driver;
122pub use crate::http3::ClientH3Connection;
123pub use crate::http3::ServerH3Connection;
124pub use crate::quic::connection::ApplicationOverQuic;
125pub use crate::quic::connection::ConnectionIdGenerator;
126pub use crate::quic::connection::InitialQuicConnection;
127pub use crate::quic::connection::QuicConnection;
128pub use crate::result::BoxError;
129pub use crate::result::QuicResult;
130pub use crate::settings::ConnectionParams;
131
132#[doc(hidden)]
133pub use crate::result::QuicResultExt;
134
135/// A stream of accepted [`InitialQuicConnection`]s from a [`listen`] call.
136///
137/// Errors from processing the client's QUIC initials can also be emitted on
138/// this stream. These do not indicate that the listener itself has failed.
139pub type QuicConnectionStream<M> =
140    ReceiverStream<io::Result<InitialQuicConnection<UdpSocket, M>>>;
141
142/// Starts listening for inbound QUIC connections on the given
143/// [`QuicListener`]s.
144///
145/// Each socket starts a separate tokio task to process and route inbound
146/// packets. This task emits connections on the respective
147/// [`QuicConnectionStream`] after receiving the client's QUIC initial and
148/// (optionally) validating its IP address.
149///
150/// The task shuts down when the returned stream is closed (or dropped) and all
151/// previously-yielded connections are closed.
152pub fn listen_with_capabilities<M>(
153    sockets: impl IntoIterator<Item = QuicListener>, params: ConnectionParams,
154    metrics: M,
155) -> io::Result<Vec<QuicConnectionStream<M>>>
156where
157    M: Metrics,
158{
159    if params.settings.capture_quiche_logs {
160        capture_quiche_logs();
161    }
162
163    sockets
164        .into_iter()
165        .map(|s| crate::quic::start_listener(s, &params, metrics.clone()))
166        .collect()
167}
168
169/// Starts listening for inbound QUIC connections on the given `sockets`.
170///
171/// Each socket is converted into a [`QuicListener`] with defaulted socket
172/// parameters. The listeners are then passed to [`listen_with_capabilities`].
173pub fn listen<S, M>(
174    sockets: impl IntoIterator<Item = S>, params: ConnectionParams, metrics: M,
175) -> io::Result<Vec<QuicConnectionStream<M>>>
176where
177    S: TryInto<QuicListener, Error = io::Error>,
178    M: Metrics,
179{
180    let quic_sockets: Vec<QuicListener> = sockets
181        .into_iter()
182        .map(|s| {
183            #[cfg_attr(not(target_os = "linux"), expect(unused_mut))]
184            let mut socket = s.try_into()?;
185            #[cfg(target_os = "linux")]
186            socket.apply_max_capabilities();
187            Ok(socket)
188        })
189        .collect::<io::Result<_>>()?;
190
191    listen_with_capabilities(quic_sockets, params, metrics)
192}
193
194static GLOBAL_LOGGER_ONCE: Once = Once::new();
195
196/// Forward Quiche logs into the slog::Drain currently used by Foundations
197///
198/// # Warning
199///
200/// This should **only be used for local debugging**. Quiche can potentially
201/// emit lots (and lots, and lots) of logs (the TRACE level emits a log record
202/// on every packet and frame) and you can very easily overwhelm your logging
203/// pipeline.
204///
205/// # Note
206///
207/// Quiche uses the `env_logger` crate, which uses `log` under the hood. `log`
208/// requires that you only set the global logger once. That means that we have
209/// to register the logger at `listen()` time for servers - for clients, we
210/// should register loggers when the `quiche::Connection` is established.
211pub(crate) fn capture_quiche_logs() {
212    GLOBAL_LOGGER_ONCE.call_once(|| {
213        use foundations::telemetry::log as foundations_log;
214        use log::Level as std_level;
215
216        let curr_logger =
217            Arc::clone(&foundations_log::slog_logger()).read().clone();
218        let scope_guard = slog_scope::set_global_logger(curr_logger);
219
220        // Convert slog::Level from Foundations settings to log::Level
221        let normalized_level = match foundations_log::verbosity() {
222            LogVerbosity::Critical | LogVerbosity::Error => std_level::Error,
223            LogVerbosity::Warning => std_level::Warn,
224            LogVerbosity::Info => std_level::Info,
225            LogVerbosity::Debug => std_level::Debug,
226            LogVerbosity::Trace => std_level::Trace,
227        };
228
229        slog_stdlog::init_with_level(normalized_level).unwrap();
230
231        // The slog Drain becomes `slog::Discard` when the scope_guard is dropped,
232        // and you can't set the global logger again because of a mandate
233        // in the `log` crate. We have to manually `forget` the scope
234        // guard so that the logger remains registered for the duration of the
235        // process.
236        std::mem::forget(scope_guard)
237    });
238}