tokio_quiche/http3/settings.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
27use std::future::poll_fn;
28use std::task::Context;
29use std::task::Poll;
30use std::time::Duration;
31
32use crate::http3::driver::H3ConnectionError;
33use crate::quic::QuicheConnection;
34
35use foundations::telemetry::log;
36use tokio_util::time::delay_queue::DelayQueue;
37use tokio_util::time::delay_queue::{
38 self,
39};
40
41/// Unified configuration parameters for
42/// [H3Driver](crate::http3::driver::H3Driver)s.
43#[derive(Default, Clone, Debug)]
44pub struct Http3Settings {
45 /// Maximum number of requests a
46 /// [ServerH3Driver](crate::http3::driver::ServerH3Driver) allows per
47 /// connection.
48 pub max_requests_per_connection: Option<u64>,
49 /// Maximum size of a single HEADERS frame, in bytes.
50 pub max_header_list_size: Option<u64>,
51 /// Maximum value the QPACK encoder is permitted to set for the dynamic
52 /// table capcity. See <https://www.rfc-editor.org/rfc/rfc9204.html#name-maximum-dynamic-table-capac>
53 pub qpack_max_table_capacity: Option<u64>,
54 /// Upper bound on the number of streams that can be blocked on the QPACK
55 /// decoder. See <https://www.rfc-editor.org/rfc/rfc9204.html#name-blocked-streams>
56 pub qpack_blocked_streams: Option<u64>,
57 /// Timeout between starting the QUIC handshake and receiving the first
58 /// request on a connection. Only applicable to
59 /// [ServerH3Driver](crate::http3::driver::ServerH3Driver).
60 pub post_accept_timeout: Option<Duration>,
61 /// Set the `SETTINGS_ENABLE_CONNECT_PROTOCOL` HTTP/3 setting.
62 /// See <https://www.rfc-editor.org/rfc/rfc9220#section-3-2>
63 pub enable_extended_connect: bool,
64 /// Maximum size, in bytes, of the buffer the driver uses to read HTTP/3
65 /// body data out of quiche before forwarding it upstream.
66 ///
67 /// The buffer is sized dynamically to the amount of data currently
68 /// readable on a stream (which is itself bounded by the QUIC flow-control
69 /// window and the size of the buffered QUIC STREAM frames), but a single
70 /// read will never allocate more than this cap. This bounds the memory a
71 /// single (potentially adversarial) stream can force the driver to
72 /// allocate.
73 ///
74 /// When unset or `Some(0)`, the driver defaults to 16 KiB.
75 pub max_recv_body_buf_size: Option<usize>,
76}
77
78impl From<&Http3Settings> for quiche::h3::Config {
79 fn from(value: &Http3Settings) -> Self {
80 let mut config = Self::new().unwrap();
81
82 if let Some(v) = value.max_header_list_size {
83 config.set_max_field_section_size(v);
84 }
85
86 if let Some(v) = value.qpack_max_table_capacity {
87 config.set_qpack_max_table_capacity(v);
88 }
89
90 if let Some(v) = value.qpack_blocked_streams {
91 config.set_qpack_blocked_streams(v);
92 }
93
94 if value.enable_extended_connect {
95 config.enable_extended_connect(value.enable_extended_connect)
96 }
97
98 config
99 }
100}
101
102/// Opaque handle to an entry in [`Http3Timeouts`].
103pub(crate) struct TimeoutKey(delay_queue::Key);
104
105pub(crate) struct Http3SettingsEnforcer {
106 limits: Http3Limits,
107 timeouts: Http3Timeouts,
108}
109
110impl From<&Http3Settings> for Http3SettingsEnforcer {
111 fn from(value: &Http3Settings) -> Self {
112 Self {
113 limits: Http3Limits {
114 max_requests_per_connection: value.max_requests_per_connection,
115 },
116 timeouts: Http3Timeouts {
117 post_accept_timeout: value.post_accept_timeout,
118 delay_queue: DelayQueue::new(),
119 },
120 }
121 }
122}
123
124impl Http3SettingsEnforcer {
125 /// Returns a boolean indicating whether or not the connection should be
126 /// closed due to a violation of the request count limit.
127 pub fn enforce_requests_limit(&self, request_count: u64) -> bool {
128 if let Some(limit) = self.limits.max_requests_per_connection {
129 return request_count >= limit;
130 }
131
132 false
133 }
134
135 /// Returns the configured post-accept timeout.
136 pub fn post_accept_timeout(&self) -> Option<Duration> {
137 self.timeouts.post_accept_timeout
138 }
139
140 /// Registers a timeout of `typ` in this [Http3SettingsEnforcer].
141 pub fn add_timeout(
142 &mut self, typ: Http3TimeoutType, duration: Duration,
143 ) -> TimeoutKey {
144 let key = self.timeouts.delay_queue.insert(typ, duration);
145 TimeoutKey(key)
146 }
147
148 /// Checks whether the [Http3SettingsEnforcer] has any pending timeouts.
149 /// This should be used to selectively poll `enforce_timeouts`.
150 pub fn has_pending_timeouts(&self) -> bool {
151 !self.timeouts.delay_queue.is_empty()
152 }
153
154 /// Checks which timeouts have expired.
155 fn poll_timeouts(&mut self, cx: &mut Context) -> Poll<TimeoutCheckResult> {
156 let mut changed = false;
157 let mut result = TimeoutCheckResult::default();
158
159 while let Poll::Ready(Some(exp)) =
160 self.timeouts.delay_queue.poll_expired(cx)
161 {
162 changed |= result.set_expired(exp.into_inner());
163 }
164
165 if changed {
166 return Poll::Ready(result);
167 }
168 Poll::Pending
169 }
170
171 /// Waits for at least one registered timeout to expire.
172 ///
173 /// This function will automatically call `close()` on the underlying
174 /// [quiche::Connection].
175 pub async fn enforce_timeouts(
176 &mut self, qconn: &mut QuicheConnection,
177 ) -> Result<(), H3ConnectionError> {
178 let result = poll_fn(|cx| self.poll_timeouts(cx)).await;
179
180 if result.connection_timed_out {
181 log::debug!("connection timed out due to post-accept-timeout"; "scid" => ?qconn.source_id());
182 qconn.close(true, quiche::h3::WireErrorCode::NoError as u64, &[])?;
183 }
184
185 Ok(())
186 }
187
188 /// Cancels a timeout that was previously registered with `add_timeout`.
189 pub fn cancel_timeout(&mut self, key: TimeoutKey) {
190 self.timeouts.delay_queue.remove(&key.0);
191 }
192}
193
194// TODO(rmehra): explore if these should really be Options, or if we
195// should enforce sane defaults
196struct Http3Limits {
197 max_requests_per_connection: Option<u64>,
198}
199
200struct Http3Timeouts {
201 post_accept_timeout: Option<Duration>,
202 delay_queue: DelayQueue<Http3TimeoutType>,
203}
204
205#[derive(Clone, Copy, Debug)]
206pub(crate) enum Http3TimeoutType {
207 PostAccept,
208}
209
210#[derive(Default, Eq, PartialEq)]
211struct TimeoutCheckResult {
212 connection_timed_out: bool,
213}
214
215impl TimeoutCheckResult {
216 fn set_expired(&mut self, typ: Http3TimeoutType) -> bool {
217 use Http3TimeoutType::*;
218 let field = match typ {
219 PostAccept => &mut self.connection_timed_out,
220 };
221
222 *field = true;
223 true
224 }
225}