Debian Codegraph @

third_party/rust/neqo-transport/src/connection/params.rs

raw
1 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
2 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
3 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
4 // option. This file may not be copied, modified, or distributed
5 // except according to those terms.
6
7 use std::{cmp::max, time::Duration};
8
9 use neqo_common::MAX_VARINT;
10
11 pub use crate::recovery::FAST_PTO_SCALE;
12 use crate::{
13 connection::{ConnectionIdManager, Role, LOCAL_ACTIVE_CID_LIMIT},
14 recv_stream::INITIAL_RECV_WINDOW_SIZE,
15 rtt::GRANULARITY,
16 stream_id::StreamType,
17 tparams::{
18 PreferredAddress, TransportParameter,
19 TransportParameterId::{
20 self, ActiveConnectionIdLimit, DisableMigration, GreaseQuicBit, InitialMaxData,
21 InitialMaxStreamDataBidiLocal, InitialMaxStreamDataBidiRemote, InitialMaxStreamDataUni,
22 InitialMaxStreamsBidi, InitialMaxStreamsUni, MaxAckDelay, MaxDatagramFrameSize,
23 MinAckDelay,
24 },
25 TransportParametersHandler,
26 },
27 tracking::DEFAULT_LOCAL_ACK_DELAY,
28 version::{Version, VersionConfig},
29 CongestionControlAlgorithm, Res,
30 };
31
32 const LOCAL_MAX_DATA: u64 = MAX_VARINT;
33 const LOCAL_STREAM_LIMIT_BIDI: u64 = 16;
34 const LOCAL_STREAM_LIMIT_UNI: u64 = 16;
35 /// See `ConnectionParameters.ack_ratio` for a discussion of this value.
36 pub const ACK_RATIO_SCALE: u8 = 10;
37 /// By default, aim to have the peer acknowledge 4 times per round trip time.
38 /// See `ConnectionParameters.ack_ratio` for more.
39 pub const DEFAULT_ACK_RATIO: u8 = 4 * ACK_RATIO_SCALE;
40 /// The local value for the idle timeout period.
41 const DEFAULT_IDLE_TIMEOUT: Duration = Duration::from_secs(30);
42 const MAX_QUEUED_DATAGRAMS_DEFAULT: usize = 10;
43
44 /// What to do with preferred addresses.
45 #[derive(Debug, Clone)]
46 pub enum PreferredAddressConfig {
47 /// Disabled, whether for client or server.
48 Disabled,
49 /// Enabled at a client, disabled at a server.
50 Default,
51 /// Enabled at both client and server.
52 Address(PreferredAddress),
53 }
54
55 /// `ConnectionParameters` use for setting initial value for QUIC parameters.
56 /// This collects configuration like initial limits, protocol version, and
57 /// congestion control algorithm.
58 #[expect(clippy::struct_excessive_bools, reason = "We need that many, sorry.")]
59 #[derive(Debug, Clone)]
60 pub struct ConnectionParameters {
61 versions: VersionConfig,
62 cc_algorithm: CongestionControlAlgorithm,
63 /// Initial connection-level flow control limit.
64 max_data: u64,
65 /// Initial flow control limit for receiving data on bidirectional streams that the peer
66 /// creates.
67 max_stream_data_bidi_remote: u64,
68 /// Initial flow control limit for receiving data on bidirectional streams that this endpoint
69 /// creates.
70 max_stream_data_bidi_local: u64,
71 /// Initial flow control limit for receiving data on unidirectional streams that the peer
72 /// creates.
73 max_stream_data_uni: u64,
74 /// Initial limit on bidirectional streams that the peer creates.
75 max_streams_bidi: u64,
76 /// Initial limit on unidirectional streams that this endpoint creates.
77 max_streams_uni: u64,
78 /// The ACK ratio determines how many acknowledgements we will request as a
79 /// fraction of both the current congestion window (expressed in packets) and
80 /// as a fraction of the current round trip time. This value is scaled by
81 /// `ACK_RATIO_SCALE`; that is, if the goal is to have at least five
82 /// acknowledgments every round trip, set the value to `5 * ACK_RATIO_SCALE`.
83 /// Values less than `ACK_RATIO_SCALE` are clamped to `ACK_RATIO_SCALE`.
84 ack_ratio: u8,
85 /// The duration of the idle timeout for the connection.
86 idle_timeout: Duration,
87 preferred_address: PreferredAddressConfig,
88 datagram_size: u64,
89 outgoing_datagram_queue: usize,
90 incoming_datagram_queue: usize,
91 fast_pto: u8,
92 grease: bool,
93 disable_migration: bool,
94 pacing: bool,
95 /// Whether the connection performs PLPMTUD.
96 pmtud: bool,
97 /// Whether PMTUD should take the local interface MTU into account.
98 pmtud_iface_mtu: bool,
99 /// Whether the connection should use SNI slicing.
100 sni_slicing: bool,
101 /// Whether to enable mlkem768nistp256-sha256.
102 mlkem: bool,
103 }
104
105 impl Default for ConnectionParameters {
106 fn default() -> Self {
107 Self {
108 versions: VersionConfig::default(),
109 cc_algorithm: CongestionControlAlgorithm::Cubic,
110 max_data: LOCAL_MAX_DATA,
111 max_stream_data_bidi_remote: u64::try_from(INITIAL_RECV_WINDOW_SIZE)
112 .expect("usize fits in u64"),
113 max_stream_data_bidi_local: u64::try_from(INITIAL_RECV_WINDOW_SIZE)
114 .expect("usize fits in u64"),
115 max_stream_data_uni: u64::try_from(INITIAL_RECV_WINDOW_SIZE)
116 .expect("usize fits in u64"),
117 max_streams_bidi: LOCAL_STREAM_LIMIT_BIDI,
118 max_streams_uni: LOCAL_STREAM_LIMIT_UNI,
119 ack_ratio: DEFAULT_ACK_RATIO,
120 idle_timeout: DEFAULT_IDLE_TIMEOUT,
121 preferred_address: PreferredAddressConfig::Default,
122 datagram_size: 0,
123 outgoing_datagram_queue: MAX_QUEUED_DATAGRAMS_DEFAULT,
124 incoming_datagram_queue: MAX_QUEUED_DATAGRAMS_DEFAULT,
125 fast_pto: FAST_PTO_SCALE,
126 grease: true,
127 disable_migration: false,
128 pacing: true,
129 pmtud: false,
130 pmtud_iface_mtu: true,
131 sni_slicing: true,
132 mlkem: true,
133 }
134 }
135 }
136
137 impl ConnectionParameters {
138 #[must_use]
139 pub const fn get_versions(&self) -> &VersionConfig {
140 &self.versions
141 }
142
143 pub(crate) fn get_versions_mut(&mut self) -> &mut VersionConfig {
144 &mut self.versions
145 }
146
147 /// Describe the initial version that should be attempted and all the
148 /// versions that should be enabled. This list should contain the initial
149 /// version and be in order of preference, with more preferred versions
150 /// before less preferred.
151 #[must_use]
152 pub fn versions(mut self, initial: Version, all: Vec<Version>) -> Self {
153 self.versions = VersionConfig::new(initial, all);
154 self
155 }
156
157 #[must_use]
158 pub const fn get_cc_algorithm(&self) -> CongestionControlAlgorithm {
159 self.cc_algorithm
160 }
161
162 #[must_use]
163 pub const fn cc_algorithm(mut self, v: CongestionControlAlgorithm) -> Self {
164 self.cc_algorithm = v;
165 self
166 }
167
168 #[must_use]
169 pub const fn get_max_data(&self) -> u64 {
170 self.max_data
171 }
172
173 #[must_use]
174 pub const fn max_data(mut self, v: u64) -> Self {
175 self.max_data = v;
176 self
177 }
178
179 #[must_use]
180 pub const fn get_max_streams(&self, stream_type: StreamType) -> u64 {
181 match stream_type {
182 StreamType::BiDi => self.max_streams_bidi,
183 StreamType::UniDi => self.max_streams_uni,
184 }
185 }
186
187 /// # Panics
188 ///
189 /// If v > 2^60 (the maximum allowed by the protocol).
190 #[must_use]
191 pub fn max_streams(mut self, stream_type: StreamType, v: u64) -> Self {
192 assert!(v <= (1 << 60), "max_streams is too large");
193 match stream_type {
194 StreamType::BiDi => {
195 self.max_streams_bidi = v;
196 }
197 StreamType::UniDi => {
198 self.max_streams_uni = v;
199 }
200 }
201 self
202 }
203
204 /// Get the maximum stream data that we will accept on different types of streams.
205 ///
206 /// # Panics
207 ///
208 /// If `StreamType::UniDi` and `false` are passed as that is not a valid combination.
209 #[must_use]
210 pub fn get_max_stream_data(&self, stream_type: StreamType, remote: bool) -> u64 {
211 match (stream_type, remote) {
212 (StreamType::BiDi, false) => self.max_stream_data_bidi_local,
213 (StreamType::BiDi, true) => self.max_stream_data_bidi_remote,
214 (StreamType::UniDi, false) => {
215 panic!("Can't get receive limit on a stream that can only be sent")
216 }
217 (StreamType::UniDi, true) => self.max_stream_data_uni,
218 }
219 }
220
221 /// Set the maximum stream data that we will accept on different types of streams.
222 ///
223 /// # Panics
224 ///
225 /// If `StreamType::UniDi` and `false` are passed as that is not a valid combination
226 /// or if v >= 62 (the maximum allowed by the protocol).
227 #[must_use]
228 pub fn max_stream_data(mut self, stream_type: StreamType, remote: bool, v: u64) -> Self {
229 assert!(v < (1 << 62), "max stream data is too large");
230 match (stream_type, remote) {
231 (StreamType::BiDi, false) => {
232 self.max_stream_data_bidi_local = v;
233 }
234 (StreamType::BiDi, true) => {
235 self.max_stream_data_bidi_remote = v;
236 }
237 (StreamType::UniDi, false) => {
238 panic!("Can't set receive limit on a stream that can only be sent")
239 }
240 (StreamType::UniDi, true) => {
241 self.max_stream_data_uni = v;
242 }
243 }
244 self
245 }
246
247 /// Set a preferred address (which only has an effect for a server).
248 #[must_use]
249 pub const fn preferred_address(mut self, preferred: PreferredAddress) -> Self {
250 self.preferred_address = PreferredAddressConfig::Address(preferred);
251 self
252 }
253
254 /// Disable the use of preferred addresses.
255 #[must_use]
256 pub const fn disable_preferred_address(mut self) -> Self {
257 self.preferred_address = PreferredAddressConfig::Disabled;
258 self
259 }
260
261 #[must_use]
262 pub const fn get_preferred_address(&self) -> &PreferredAddressConfig {
263 &self.preferred_address
264 }
265
266 #[must_use]
267 pub const fn ack_ratio(mut self, ack_ratio: u8) -> Self {
268 self.ack_ratio = ack_ratio;
269 self
270 }
271
272 #[must_use]
273 pub const fn get_ack_ratio(&self) -> u8 {
274 self.ack_ratio
275 }
276
277 /// # Panics
278 ///
279 /// If `timeout` is 2^62 milliseconds or more.
280 #[must_use]
281 pub fn idle_timeout(mut self, timeout: Duration) -> Self {
282 assert!(timeout.as_millis() < (1 << 62), "idle timeout is too long");
283 self.idle_timeout = timeout;
284 self
285 }
286
287 #[must_use]
288 pub const fn get_idle_timeout(&self) -> Duration {
289 self.idle_timeout
290 }
291
292 #[must_use]
293 pub const fn get_datagram_size(&self) -> u64 {
294 self.datagram_size
295 }
296
297 #[must_use]
298 pub const fn datagram_size(mut self, v: u64) -> Self {
299 self.datagram_size = v;
300 self
301 }
302
303 #[must_use]
304 pub const fn get_outgoing_datagram_queue(&self) -> usize {
305 self.outgoing_datagram_queue
306 }
307
308 #[must_use]
309 pub fn outgoing_datagram_queue(mut self, v: usize) -> Self {
310 // The max queue length must be at least 1.
311 self.outgoing_datagram_queue = max(v, 1);
312 self
313 }
314
315 #[must_use]
316 pub const fn get_incoming_datagram_queue(&self) -> usize {
317 self.incoming_datagram_queue
318 }
319
320 #[must_use]
321 pub fn incoming_datagram_queue(mut self, v: usize) -> Self {
322 // The max queue length must be at least 1.
323 self.incoming_datagram_queue = max(v, 1);
324 self
325 }
326
327 #[must_use]
328 pub const fn get_fast_pto(&self) -> u8 {
329 self.fast_pto
330 }
331
332 /// Scale the PTO timer. A value of `FAST_PTO_SCALE` follows the spec, a smaller
333 /// value does not, but produces more probes with the intent of ensuring lower
334 /// latency in the event of tail loss. A value of `FAST_PTO_SCALE/4` is quite
335 /// aggressive. Smaller values (other than zero) are not rejected, but could be
336 /// very wasteful. Values greater than `FAST_PTO_SCALE` delay probes and could
337 /// reduce performance. It should not be possible to increase the PTO timer by
338 /// too much based on the range of valid values, but a maximum value of 255 will
339 /// result in very poor performance.
340 /// Scaling PTO this way does not affect when persistent congestion is declared,
341 /// but may change how many retransmissions are sent before declaring persistent
342 /// congestion.
343 ///
344 /// # Panics
345 ///
346 /// A value of 0 is invalid and will cause a panic.
347 #[must_use]
348 pub fn fast_pto(mut self, scale: u8) -> Self {
349 assert_ne!(scale, 0);
350 self.fast_pto = scale;
351 self
352 }
353
354 #[must_use]
355 pub const fn is_greasing(&self) -> bool {
356 self.grease
357 }
358
359 #[must_use]
360 pub const fn grease(mut self, grease: bool) -> Self {
361 self.grease = grease;
362 self
363 }
364
365 #[must_use]
366 pub const fn disable_migration(mut self, disable_migration: bool) -> Self {
367 self.disable_migration = disable_migration;
368 self
369 }
370
371 #[must_use]
372 pub const fn pacing_enabled(&self) -> bool {
373 self.pacing
374 }
375
376 #[must_use]
377 pub const fn pacing(mut self, pacing: bool) -> Self {
378 self.pacing = pacing;
379 self
380 }
381
382 #[must_use]
383 pub const fn pmtud_enabled(&self) -> bool {
384 self.pmtud
385 }
386
387 #[must_use]
388 pub const fn pmtud(mut self, pmtud: bool) -> Self {
389 self.pmtud = pmtud;
390 self
391 }
392
393 #[must_use]
394 pub const fn pmtud_iface_mtu_enabled(&self) -> bool {
395 self.pmtud_iface_mtu
396 }
397
398 #[must_use]
399 pub const fn pmtud_iface_mtu(mut self, pmtud_iface_mtu: bool) -> Self {
400 self.pmtud_iface_mtu = pmtud_iface_mtu;
401 self
402 }
403
404 #[must_use]
405 pub const fn sni_slicing_enabled(&self) -> bool {
406 self.sni_slicing
407 }
408
409 #[must_use]
410 pub const fn sni_slicing(mut self, sni_slicing: bool) -> Self {
411 self.sni_slicing = sni_slicing;
412 self
413 }
414
415 #[must_use]
416 pub const fn mlkem_enabled(&self) -> bool {
417 self.mlkem
418 }
419
420 #[must_use]
421 pub const fn mlkem(mut self, mlkem: bool) -> Self {
422 self.mlkem = mlkem;
423 self
424 }
425
426 /// # Errors
427 /// When a connection ID cannot be obtained.
428 /// # Panics
429 /// Only when this code includes a transport parameter that is invalid.
430 pub fn create_transport_parameter(
431 &self,
432 role: Role,
433 cid_manager: &mut ConnectionIdManager,
434 ) -> Res<TransportParametersHandler> {
435 let mut tps = TransportParametersHandler::new(role, self.versions.clone());
436 // default parameters
437 tps.local_mut().set_integer(
438 ActiveConnectionIdLimit,
439 u64::try_from(LOCAL_ACTIVE_CID_LIMIT)?,
440 );
441 if self.disable_migration {
442 tps.local_mut().set_empty(DisableMigration);
443 }
444 if self.grease {
445 tps.local_mut().set_empty(GreaseQuicBit);
446 }
447 tps.local_mut().set_integer(
448 MaxAckDelay,
449 u64::try_from(DEFAULT_LOCAL_ACK_DELAY.as_millis())?,
450 );
451 tps.local_mut()
452 .set_integer(MinAckDelay, u64::try_from(GRANULARITY.as_micros())?);
453
454 // set configurable parameters
455 tps.local_mut().set_integer(InitialMaxData, self.max_data);
456 tps.local_mut().set_integer(
457 InitialMaxStreamDataBidiLocal,
458 self.max_stream_data_bidi_local,
459 );
460 tps.local_mut().set_integer(
461 InitialMaxStreamDataBidiRemote,
462 self.max_stream_data_bidi_remote,
463 );
464 tps.local_mut()
465 .set_integer(InitialMaxStreamDataUni, self.max_stream_data_uni);
466 tps.local_mut()
467 .set_integer(InitialMaxStreamsBidi, self.max_streams_bidi);
468 tps.local_mut()
469 .set_integer(InitialMaxStreamsUni, self.max_streams_uni);
470 tps.local_mut().set_integer(
471 TransportParameterId::IdleTimeout,
472 u64::try_from(self.idle_timeout.as_millis()).unwrap_or(0),
473 );
474 if let PreferredAddressConfig::Address(preferred) = &self.preferred_address {
475 if role == Role::Server {
476 let (cid, srt) = cid_manager.preferred_address_cid()?;
477 tps.local_mut().set(
478 TransportParameterId::PreferredAddress,
479 TransportParameter::PreferredAddress {
480 v4: preferred.ipv4(),
481 v6: preferred.ipv6(),
482 cid,
483 srt,
484 },
485 );
486 }
487 }
488 tps.local_mut()
489 .set_integer(MaxDatagramFrameSize, self.datagram_size);
490 Ok(tps)
491 }
492 }