iroh_quinn_proto/
transport_parameters.rs

1//! QUIC connection transport parameters
2//!
3//! The `TransportParameters` type is used to represent the transport parameters
4//! negotiated by peers while establishing a QUIC connection. This process
5//! happens as part of the establishment of the TLS session. As such, the types
6//! contained in this modules should generally only be referred to by custom
7//! implementations of the `crypto::Session` trait.
8
9use std::{
10    convert::TryFrom,
11    net::{Ipv4Addr, Ipv6Addr, SocketAddrV4, SocketAddrV6},
12    num::NonZeroU8,
13};
14
15use bytes::{Buf, BufMut};
16use rand::{Rng as _, RngCore, seq::SliceRandom as _};
17use thiserror::Error;
18
19use crate::{
20    LOC_CID_COUNT, MAX_CID_SIZE, MAX_STREAM_COUNT, RESET_TOKEN_SIZE, ResetToken, Side,
21    TIMER_GRANULARITY, TransportError, VarInt, address_discovery,
22    cid_generator::ConnectionIdGenerator,
23    cid_queue::CidQueue,
24    coding::{BufExt, BufMutExt, UnexpectedEnd},
25    config::{EndpointConfig, ServerConfig, TransportConfig},
26    connection::PathId,
27    shared::ConnectionId,
28};
29
30// Apply a given macro to a list of all the transport parameters having integer types, along with
31// their codes and default values. Using this helps us avoid error-prone duplication of the
32// contained information across decoding, encoding, and the `Default` impl. Whenever we want to do
33// something with transport parameters, we'll handle the bulk of cases by writing a macro that
34// takes a list of arguments in this form, then passing it to this macro.
35macro_rules! apply_params {
36    ($macro:ident) => {
37        $macro! {
38            // #[doc] name (id) = default,
39            /// Milliseconds, disabled if zero
40            max_idle_timeout(MaxIdleTimeout) = 0,
41            /// Limits the size of UDP payloads that the endpoint is willing to receive
42            max_udp_payload_size(MaxUdpPayloadSize) = 65527,
43
44            /// Initial value for the maximum amount of data that can be sent on the connection
45            initial_max_data(InitialMaxData) = 0,
46            /// Initial flow control limit for locally-initiated bidirectional streams
47            initial_max_stream_data_bidi_local(InitialMaxStreamDataBidiLocal) = 0,
48            /// Initial flow control limit for peer-initiated bidirectional streams
49            initial_max_stream_data_bidi_remote(InitialMaxStreamDataBidiRemote) = 0,
50            /// Initial flow control limit for unidirectional streams
51            initial_max_stream_data_uni(InitialMaxStreamDataUni) = 0,
52
53            /// Initial maximum number of bidirectional streams the peer may initiate
54            initial_max_streams_bidi(InitialMaxStreamsBidi) = 0,
55            /// Initial maximum number of unidirectional streams the peer may initiate
56            initial_max_streams_uni(InitialMaxStreamsUni) = 0,
57
58            /// Exponent used to decode the ACK Delay field in the ACK frame
59            ack_delay_exponent(AckDelayExponent) = 3,
60            /// Maximum amount of time in milliseconds by which the endpoint will delay sending
61            /// acknowledgments
62            max_ack_delay(MaxAckDelay) = 25,
63            /// Maximum number of connection IDs from the peer that an endpoint is willing to store
64            active_connection_id_limit(ActiveConnectionIdLimit) = 2,
65        }
66    };
67}
68
69macro_rules! make_struct {
70    {$($(#[$doc:meta])* $name:ident ($id:ident) = $default:expr,)*} => {
71        /// Transport parameters used to negotiate connection-level preferences between peers
72        #[derive(Debug, Copy, Clone, Eq, PartialEq)]
73        pub struct TransportParameters {
74            $($(#[$doc])* pub(crate) $name : VarInt,)*
75
76            /// Does the endpoint support active connection migration
77            pub(crate) disable_active_migration: bool,
78            /// Maximum size for datagram frames
79            pub(crate) max_datagram_frame_size: Option<VarInt>,
80            /// The value that the endpoint included in the Source Connection ID field of the first
81            /// Initial packet it sends for the connection
82            pub(crate) initial_src_cid: Option<ConnectionId>,
83            /// The endpoint is willing to receive QUIC packets containing any value for the fixed
84            /// bit
85            pub(crate) grease_quic_bit: bool,
86
87            /// Minimum amount of time in microseconds by which the endpoint is able to delay
88            /// sending acknowledgments
89            ///
90            /// If a value is provided, it implies that the endpoint supports QUIC Acknowledgement
91            /// Frequency
92            pub(crate) min_ack_delay: Option<VarInt>,
93
94            // Server-only
95            /// The value of the Destination Connection ID field from the first Initial packet sent
96            /// by the client
97            pub(crate) original_dst_cid: Option<ConnectionId>,
98            /// The value that the server included in the Source Connection ID field of a Retry
99            /// packet
100            pub(crate) retry_src_cid: Option<ConnectionId>,
101            /// Token used by the client to verify a stateless reset from the server
102            pub(crate) stateless_reset_token: Option<ResetToken>,
103            /// The server's preferred address for communication after handshake completion
104            pub(crate) preferred_address: Option<PreferredAddress>,
105
106            /// The randomly generated reserved transport parameter to sustain future extensibility
107            /// of transport parameter extensions.
108            /// When present, it is included during serialization but ignored during deserialization.
109            pub(crate) grease_transport_parameter: Option<ReservedTransportParameter>,
110
111            /// Defines the order in which transport parameters are serialized.
112            ///
113            /// This field is initialized only for outgoing `TransportParameters` instances and
114            /// is set to `None` for `TransportParameters` received from a peer.
115            pub(crate) write_order: Option<[u8; TransportParameterId::SUPPORTED.len()]>,
116
117            /// The role of this peer in address discovery, if any.
118            pub(crate) address_discovery_role: address_discovery::Role,
119
120            /// Multipath extension
121            pub(crate) initial_max_path_id: Option<PathId>,
122
123            /// Nat traversal draft
124            pub max_remote_nat_traversal_addresses: Option<NonZeroU8>,
125        }
126
127        // We deliberately don't implement the `Default` trait, since that would be public, and
128        // downstream crates should never construct `TransportParameters` except by decoding those
129        // supplied by a peer.
130        impl TransportParameters {
131            /// Standard defaults, used if the peer does not supply a given parameter.
132            pub(crate) fn default() -> Self {
133                Self {
134                    $($name: VarInt::from_u32($default),)*
135
136                    disable_active_migration: false,
137                    max_datagram_frame_size: None,
138                    initial_src_cid: None,
139                    grease_quic_bit: false,
140                    min_ack_delay: None,
141
142                    original_dst_cid: None,
143                    retry_src_cid: None,
144                    stateless_reset_token: None,
145                    preferred_address: None,
146                    grease_transport_parameter: None,
147                    write_order: None,
148                    address_discovery_role: address_discovery::Role::Disabled,
149                    initial_max_path_id: None,
150                    max_remote_nat_traversal_addresses: None,
151                }
152            }
153        }
154    }
155}
156
157apply_params!(make_struct);
158
159impl TransportParameters {
160    pub(crate) fn new(
161        config: &TransportConfig,
162        endpoint_config: &EndpointConfig,
163        cid_gen: &dyn ConnectionIdGenerator,
164        initial_src_cid: ConnectionId,
165        server_config: Option<&ServerConfig>,
166        rng: &mut impl RngCore,
167    ) -> Self {
168        Self {
169            initial_src_cid: Some(initial_src_cid),
170            initial_max_streams_bidi: config.max_concurrent_bidi_streams,
171            initial_max_streams_uni: config.max_concurrent_uni_streams,
172            initial_max_data: config.receive_window,
173            initial_max_stream_data_bidi_local: config.stream_receive_window,
174            initial_max_stream_data_bidi_remote: config.stream_receive_window,
175            initial_max_stream_data_uni: config.stream_receive_window,
176            max_udp_payload_size: endpoint_config.max_udp_payload_size,
177            max_idle_timeout: config.max_idle_timeout.unwrap_or(VarInt(0)),
178            disable_active_migration: server_config.is_some_and(|c| !c.migration),
179            active_connection_id_limit: if cid_gen.cid_len() == 0 {
180                2 // i.e. default, i.e. unsent
181            } else {
182                CidQueue::LEN as u32
183            }
184            .into(),
185            max_datagram_frame_size: config
186                .datagram_receive_buffer_size
187                .map(|x| (x.min(u16::MAX.into()) as u16).into()),
188            grease_quic_bit: endpoint_config.grease_quic_bit,
189            min_ack_delay: Some(
190                VarInt::from_u64(u64::try_from(TIMER_GRANULARITY.as_micros()).unwrap()).unwrap(),
191            ),
192            grease_transport_parameter: Some(ReservedTransportParameter::random(rng)),
193            write_order: Some({
194                let mut order = std::array::from_fn(|i| i as u8);
195                order.shuffle(rng);
196                order
197            }),
198            address_discovery_role: config.address_discovery_role,
199            initial_max_path_id: config.get_initial_max_path_id(),
200            max_remote_nat_traversal_addresses: config.max_remote_nat_traversal_addresses,
201            ..Self::default()
202        }
203    }
204
205    /// Check that these parameters are legal when resuming from
206    /// certain cached parameters
207    pub(crate) fn validate_resumption_from(&self, cached: &Self) -> Result<(), TransportError> {
208        if cached.active_connection_id_limit > self.active_connection_id_limit
209            || cached.initial_max_data > self.initial_max_data
210            || cached.initial_max_stream_data_bidi_local > self.initial_max_stream_data_bidi_local
211            || cached.initial_max_stream_data_bidi_remote > self.initial_max_stream_data_bidi_remote
212            || cached.initial_max_stream_data_uni > self.initial_max_stream_data_uni
213            || cached.initial_max_streams_bidi > self.initial_max_streams_bidi
214            || cached.initial_max_streams_uni > self.initial_max_streams_uni
215            || cached.max_datagram_frame_size > self.max_datagram_frame_size
216            || cached.grease_quic_bit && !self.grease_quic_bit
217            || cached.address_discovery_role != self.address_discovery_role
218            || cached.max_remote_nat_traversal_addresses != self.max_remote_nat_traversal_addresses
219        {
220            return Err(TransportError::PROTOCOL_VIOLATION(
221                "0-RTT accepted with incompatible transport parameters",
222            ));
223        }
224        Ok(())
225    }
226
227    /// Maximum number of CIDs to issue to this peer
228    ///
229    /// Consider both a) the active_connection_id_limit from the other end; and
230    /// b) LOC_CID_COUNT used locally
231    pub(crate) fn issue_cids_limit(&self) -> u64 {
232        self.active_connection_id_limit.0.min(LOC_CID_COUNT)
233    }
234}
235
236/// A server's preferred address
237///
238/// This is communicated as a transport parameter during TLS session establishment.
239#[derive(Debug, Copy, Clone, Eq, PartialEq)]
240pub(crate) struct PreferredAddress {
241    pub(crate) address_v4: Option<SocketAddrV4>,
242    pub(crate) address_v6: Option<SocketAddrV6>,
243    pub(crate) connection_id: ConnectionId,
244    pub(crate) stateless_reset_token: ResetToken,
245}
246
247impl PreferredAddress {
248    fn wire_size(&self) -> u16 {
249        4 + 2 + 16 + 2 + 1 + self.connection_id.len() as u16 + 16
250    }
251
252    fn write<W: BufMut>(&self, w: &mut W) {
253        w.write(self.address_v4.map_or(Ipv4Addr::UNSPECIFIED, |x| *x.ip()));
254        w.write::<u16>(self.address_v4.map_or(0, |x| x.port()));
255        w.write(self.address_v6.map_or(Ipv6Addr::UNSPECIFIED, |x| *x.ip()));
256        w.write::<u16>(self.address_v6.map_or(0, |x| x.port()));
257        w.write::<u8>(self.connection_id.len() as u8);
258        w.put_slice(&self.connection_id);
259        w.put_slice(&self.stateless_reset_token);
260    }
261
262    fn read<R: Buf>(r: &mut R) -> Result<Self, Error> {
263        let ip_v4 = r.get::<Ipv4Addr>()?;
264        let port_v4 = r.get::<u16>()?;
265        let ip_v6 = r.get::<Ipv6Addr>()?;
266        let port_v6 = r.get::<u16>()?;
267        let cid_len = r.get::<u8>()?;
268        if r.remaining() < cid_len as usize || cid_len > MAX_CID_SIZE as u8 {
269            return Err(Error::Malformed);
270        }
271        let mut stage = [0; MAX_CID_SIZE];
272        r.copy_to_slice(&mut stage[0..cid_len as usize]);
273        let cid = ConnectionId::new(&stage[0..cid_len as usize]);
274        if r.remaining() < 16 {
275            return Err(Error::Malformed);
276        }
277        let mut token = [0; RESET_TOKEN_SIZE];
278        r.copy_to_slice(&mut token);
279        let address_v4 = if ip_v4.is_unspecified() && port_v4 == 0 {
280            None
281        } else {
282            Some(SocketAddrV4::new(ip_v4, port_v4))
283        };
284        let address_v6 = if ip_v6.is_unspecified() && port_v6 == 0 {
285            None
286        } else {
287            Some(SocketAddrV6::new(ip_v6, port_v6, 0, 0))
288        };
289        if address_v4.is_none() && address_v6.is_none() {
290            return Err(Error::IllegalValue);
291        }
292        Ok(Self {
293            address_v4,
294            address_v6,
295            connection_id: cid,
296            stateless_reset_token: token.into(),
297        })
298    }
299}
300
301/// Errors encountered while decoding `TransportParameters`
302#[derive(Debug, Copy, Clone, Eq, PartialEq, Error)]
303pub enum Error {
304    /// Parameters that are semantically invalid
305    #[error("parameter had illegal value")]
306    IllegalValue,
307    /// Catch-all error for problems while decoding transport parameters
308    #[error("parameters were malformed")]
309    Malformed,
310}
311
312impl From<Error> for TransportError {
313    fn from(e: Error) -> Self {
314        match e {
315            Error::IllegalValue => Self::TRANSPORT_PARAMETER_ERROR("illegal value"),
316            Error::Malformed => Self::TRANSPORT_PARAMETER_ERROR("malformed"),
317        }
318    }
319}
320
321impl From<UnexpectedEnd> for Error {
322    fn from(_: UnexpectedEnd) -> Self {
323        Self::Malformed
324    }
325}
326
327impl TransportParameters {
328    /// Encode `TransportParameters` into buffer
329    pub fn write<W: BufMut>(&self, w: &mut W) {
330        for idx in self
331            .write_order
332            .as_ref()
333            .unwrap_or(&std::array::from_fn(|i| i as u8))
334        {
335            let id = TransportParameterId::SUPPORTED[*idx as usize];
336            match id {
337                TransportParameterId::ReservedTransportParameter => {
338                    if let Some(param) = self.grease_transport_parameter {
339                        param.write(w);
340                    }
341                }
342                TransportParameterId::StatelessResetToken => {
343                    if let Some(ref x) = self.stateless_reset_token {
344                        w.write_var(id as u64);
345                        w.write_var(16);
346                        w.put_slice(x);
347                    }
348                }
349                TransportParameterId::DisableActiveMigration => {
350                    if self.disable_active_migration {
351                        w.write_var(id as u64);
352                        w.write_var(0);
353                    }
354                }
355                TransportParameterId::MaxDatagramFrameSize => {
356                    if let Some(x) = self.max_datagram_frame_size {
357                        w.write_var(id as u64);
358                        w.write_var(x.size() as u64);
359                        w.write(x);
360                    }
361                }
362                TransportParameterId::PreferredAddress => {
363                    if let Some(ref x) = self.preferred_address {
364                        w.write_var(id as u64);
365                        w.write_var(x.wire_size() as u64);
366                        x.write(w);
367                    }
368                }
369                TransportParameterId::OriginalDestinationConnectionId => {
370                    if let Some(ref cid) = self.original_dst_cid {
371                        w.write_var(id as u64);
372                        w.write_var(cid.len() as u64);
373                        w.put_slice(cid);
374                    }
375                }
376                TransportParameterId::InitialSourceConnectionId => {
377                    if let Some(ref cid) = self.initial_src_cid {
378                        w.write_var(id as u64);
379                        w.write_var(cid.len() as u64);
380                        w.put_slice(cid);
381                    }
382                }
383                TransportParameterId::RetrySourceConnectionId => {
384                    if let Some(ref cid) = self.retry_src_cid {
385                        w.write_var(id as u64);
386                        w.write_var(cid.len() as u64);
387                        w.put_slice(cid);
388                    }
389                }
390                TransportParameterId::GreaseQuicBit => {
391                    if self.grease_quic_bit {
392                        w.write_var(id as u64);
393                        w.write_var(0);
394                    }
395                }
396                TransportParameterId::MinAckDelayDraft07 => {
397                    if let Some(x) = self.min_ack_delay {
398                        w.write_var(id as u64);
399                        w.write_var(x.size() as u64);
400                        w.write(x);
401                    }
402                }
403                TransportParameterId::ObservedAddr => {
404                    if let Some(varint_role) = self.address_discovery_role.as_transport_parameter()
405                    {
406                        w.write_var(id as u64);
407                        w.write_var(varint_role.size() as u64);
408                        w.write(varint_role);
409                    }
410                }
411                TransportParameterId::InitialMaxPathId => {
412                    if let Some(val) = self.initial_max_path_id {
413                        w.write_var(id as u64);
414                        w.write_var(val.size() as u64);
415                        w.write(val);
416                    }
417                }
418                TransportParameterId::IrohNatTraversal => {
419                    if let Some(val) = self.max_remote_nat_traversal_addresses {
420                        w.write_var(id as u64);
421                        w.write(VarInt(1));
422                        w.write(val.get());
423                    }
424                }
425                id => {
426                    macro_rules! write_params {
427                        {$($(#[$doc:meta])* $name:ident ($id:ident) = $default:expr,)*} => {
428                            match id {
429                                $(TransportParameterId::$id => {
430                                    if self.$name.0 != $default {
431                                        w.write_var(id as u64);
432                                        w.write(VarInt::try_from(self.$name.size()).unwrap());
433                                        w.write(self.$name);
434                                    }
435                                })*,
436                                _ => {
437                                    unimplemented!("Missing implementation of write for transport parameter with code {id:?}");
438                                }
439                            }
440                        }
441                    }
442                    apply_params!(write_params);
443                }
444            }
445        }
446    }
447
448    /// Decode `TransportParameters` from buffer
449    pub fn read<R: Buf>(side: Side, r: &mut R) -> Result<Self, Error> {
450        // Initialize to protocol-specified defaults
451        let mut params = Self::default();
452
453        // State to check for duplicate transport parameters.
454        macro_rules! param_state {
455            {$($(#[$doc:meta])* $name:ident ($id:ident) = $default:expr,)*} => {{
456                struct ParamState {
457                    $($name: bool,)*
458                }
459
460                ParamState {
461                    $($name: false,)*
462                }
463            }}
464        }
465        let mut got = apply_params!(param_state);
466
467        while r.has_remaining() {
468            let id = r.get_var()?;
469            let len = r.get_var()?;
470            if (r.remaining() as u64) < len {
471                return Err(Error::Malformed);
472            }
473            let len = len as usize;
474            let Ok(id) = TransportParameterId::try_from(id) else {
475                // unknown transport parameters are ignored
476                r.advance(len);
477                continue;
478            };
479
480            match id {
481                TransportParameterId::OriginalDestinationConnectionId => {
482                    decode_cid(len, &mut params.original_dst_cid, r)?
483                }
484                TransportParameterId::StatelessResetToken => {
485                    if len != 16 || params.stateless_reset_token.is_some() {
486                        return Err(Error::Malformed);
487                    }
488                    let mut tok = [0; RESET_TOKEN_SIZE];
489                    r.copy_to_slice(&mut tok);
490                    params.stateless_reset_token = Some(tok.into());
491                }
492                TransportParameterId::DisableActiveMigration => {
493                    if len != 0 || params.disable_active_migration {
494                        return Err(Error::Malformed);
495                    }
496                    params.disable_active_migration = true;
497                }
498                TransportParameterId::PreferredAddress => {
499                    if params.preferred_address.is_some() {
500                        return Err(Error::Malformed);
501                    }
502                    params.preferred_address = Some(PreferredAddress::read(&mut r.take(len))?);
503                }
504                TransportParameterId::InitialSourceConnectionId => {
505                    decode_cid(len, &mut params.initial_src_cid, r)?
506                }
507                TransportParameterId::RetrySourceConnectionId => {
508                    decode_cid(len, &mut params.retry_src_cid, r)?
509                }
510                TransportParameterId::MaxDatagramFrameSize => {
511                    if len > 8 || params.max_datagram_frame_size.is_some() {
512                        return Err(Error::Malformed);
513                    }
514                    params.max_datagram_frame_size = Some(r.get().unwrap());
515                }
516                TransportParameterId::GreaseQuicBit => match len {
517                    0 => params.grease_quic_bit = true,
518                    _ => return Err(Error::Malformed),
519                },
520                TransportParameterId::MinAckDelayDraft07 => {
521                    params.min_ack_delay = Some(r.get().unwrap())
522                }
523                TransportParameterId::ObservedAddr => {
524                    if !params.address_discovery_role.is_disabled() {
525                        // duplicate parameter
526                        return Err(Error::Malformed);
527                    }
528                    let value: VarInt = r.get()?;
529                    if len != value.size() {
530                        return Err(Error::Malformed);
531                    }
532                    params.address_discovery_role = value.try_into()?;
533                    tracing::debug!(
534                        role = ?params.address_discovery_role,
535                        "address discovery enabled for peer"
536                    );
537                }
538                TransportParameterId::InitialMaxPathId => {
539                    if params.initial_max_path_id.is_some() {
540                        return Err(Error::Malformed);
541                    }
542
543                    let value: PathId = r.get()?;
544                    if len != value.size() {
545                        return Err(Error::Malformed);
546                    }
547
548                    params.initial_max_path_id = Some(value);
549                }
550                TransportParameterId::IrohNatTraversal => {
551                    if params.max_remote_nat_traversal_addresses.is_some() {
552                        return Err(Error::Malformed);
553                    }
554                    if len != 1 {
555                        return Err(Error::Malformed);
556                    }
557
558                    let value: u8 = r.get()?;
559                    let value = NonZeroU8::new(value).ok_or(Error::IllegalValue)?;
560
561                    params.max_remote_nat_traversal_addresses = Some(value);
562                }
563                _ => {
564                    macro_rules! parse {
565                        {$($(#[$doc:meta])* $name:ident ($id:ident) = $default:expr,)*} => {
566                            match id {
567                                $(TransportParameterId::$id => {
568                                    let value = r.get::<VarInt>()?;
569                                    if len != value.size() || got.$name { return Err(Error::Malformed); }
570                                    params.$name = value.into();
571                                    got.$name = true;
572                                })*
573                                _ => r.advance(len),
574                            }
575                        }
576                    }
577                    apply_params!(parse);
578                }
579            }
580        }
581
582        // Semantic validation
583
584        // https://www.rfc-editor.org/rfc/rfc9000.html#section-18.2-4.26.1
585        if params.ack_delay_exponent.0 > 20
586            // https://www.rfc-editor.org/rfc/rfc9000.html#section-18.2-4.28.1
587            || params.max_ack_delay.0 >= 1 << 14
588            // https://www.rfc-editor.org/rfc/rfc9000.html#section-18.2-6.2.1
589            || params.active_connection_id_limit.0 < 2
590            // https://www.rfc-editor.org/rfc/rfc9000.html#section-18.2-4.10.1
591            || params.max_udp_payload_size.0 < 1200
592            // https://www.rfc-editor.org/rfc/rfc9000.html#section-4.6-2
593            || params.initial_max_streams_bidi.0 > MAX_STREAM_COUNT
594            || params.initial_max_streams_uni.0 > MAX_STREAM_COUNT
595            // https://www.ietf.org/archive/id/draft-ietf-quic-ack-frequency-08.html#section-3-4
596            || params.min_ack_delay.is_some_and(|min_ack_delay| {
597                // min_ack_delay uses microseconds, whereas max_ack_delay uses milliseconds
598                min_ack_delay.0 > params.max_ack_delay.0 * 1_000
599            })
600            // https://www.rfc-editor.org/rfc/rfc9000.html#section-18.2-8
601            || (side.is_server()
602                && (params.original_dst_cid.is_some()
603                    || params.preferred_address.is_some()
604                    || params.retry_src_cid.is_some()
605                    || params.stateless_reset_token.is_some()))
606            // https://www.rfc-editor.org/rfc/rfc9000.html#section-18.2-4.38.1
607            || params
608                .preferred_address.is_some_and(|x| x.connection_id.is_empty())
609        {
610            return Err(Error::IllegalValue);
611        }
612
613        Ok(params)
614    }
615}
616
617/// A reserved transport parameter.
618///
619/// It has an identifier of the form 31 * N + 27 for the integer value of N.
620/// Such identifiers are reserved to exercise the requirement that unknown transport parameters be ignored.
621/// The reserved transport parameter has no semantics and can carry arbitrary values.
622/// It may be included in transport parameters sent to the peer, and should be ignored when received.
623///
624/// See spec: <https://www.rfc-editor.org/rfc/rfc9000.html#section-18.1>
625#[derive(Debug, Copy, Clone, Eq, PartialEq)]
626pub(crate) struct ReservedTransportParameter {
627    /// The reserved identifier of the transport parameter
628    id: VarInt,
629
630    /// Buffer to store the parameter payload
631    payload: [u8; Self::MAX_PAYLOAD_LEN],
632
633    /// The number of bytes to include in the wire format from the `payload` buffer
634    payload_len: usize,
635}
636
637impl ReservedTransportParameter {
638    /// Generates a transport parameter with a random payload and a reserved ID.
639    ///
640    /// The implementation is inspired by quic-go and quiche:
641    /// 1. <https://github.com/quic-go/quic-go/blob/3e0a67b2476e1819752f04d75968de042b197b56/internal/wire/transport_parameters.go#L338-L344>
642    /// 2. <https://github.com/google/quiche/blob/cb1090b20c40e2f0815107857324e99acf6ec567/quiche/quic/core/crypto/transport_parameters.cc#L843-L860>
643    fn random(rng: &mut impl RngCore) -> Self {
644        let id = Self::generate_reserved_id(rng);
645
646        let payload_len = rng.random_range(0..Self::MAX_PAYLOAD_LEN);
647
648        let payload = {
649            let mut slice = [0u8; Self::MAX_PAYLOAD_LEN];
650            rng.fill_bytes(&mut slice[..payload_len]);
651            slice
652        };
653
654        Self {
655            id,
656            payload,
657            payload_len,
658        }
659    }
660
661    fn write(&self, w: &mut impl BufMut) {
662        w.write_var(self.id.0);
663        w.write_var(self.payload_len as u64);
664        w.put_slice(&self.payload[..self.payload_len]);
665    }
666
667    /// Generates a random reserved identifier of the form `31 * N + 27`, as required by RFC 9000.
668    /// Reserved transport parameter identifiers are used to test compliance with the requirement
669    /// that unknown transport parameters must be ignored by peers.
670    /// See: <https://www.rfc-editor.org/rfc/rfc9000.html#section-18.1> and <https://www.rfc-editor.org/rfc/rfc9000.html#section-22.3>
671    fn generate_reserved_id(rng: &mut impl RngCore) -> VarInt {
672        let id = {
673            let rand = rng.random_range(0u64..(1 << 62) - 27);
674            let n = rand / 31;
675            31 * n + 27
676        };
677        debug_assert!(
678            id % 31 == 27,
679            "generated id does not have the form of 31 * N + 27"
680        );
681        VarInt::from_u64(id).expect(
682            "generated id does fit into range of allowed transport parameter IDs: [0; 2^62)",
683        )
684    }
685
686    /// The maximum length of the payload to include as the parameter payload.
687    /// This value is not a specification-imposed limit but is chosen to match
688    /// the limit used by other implementations of QUIC, e.g., quic-go and quiche.
689    const MAX_PAYLOAD_LEN: usize = 16;
690}
691
692#[repr(u64)]
693#[derive(Debug, Clone, Copy, PartialEq, Eq)]
694pub(crate) enum TransportParameterId {
695    // https://www.rfc-editor.org/rfc/rfc9000.html#iana-tp-table
696    OriginalDestinationConnectionId = 0x00,
697    MaxIdleTimeout = 0x01,
698    StatelessResetToken = 0x02,
699    MaxUdpPayloadSize = 0x03,
700    InitialMaxData = 0x04,
701    InitialMaxStreamDataBidiLocal = 0x05,
702    InitialMaxStreamDataBidiRemote = 0x06,
703    InitialMaxStreamDataUni = 0x07,
704    InitialMaxStreamsBidi = 0x08,
705    InitialMaxStreamsUni = 0x09,
706    AckDelayExponent = 0x0A,
707    MaxAckDelay = 0x0B,
708    DisableActiveMigration = 0x0C,
709    PreferredAddress = 0x0D,
710    ActiveConnectionIdLimit = 0x0E,
711    InitialSourceConnectionId = 0x0F,
712    RetrySourceConnectionId = 0x10,
713
714    // Smallest possible ID of reserved transport parameter https://datatracker.ietf.org/doc/html/rfc9000#section-22.3
715    ReservedTransportParameter = 0x1B,
716
717    // https://www.rfc-editor.org/rfc/rfc9221.html#section-3
718    MaxDatagramFrameSize = 0x20,
719
720    // https://www.rfc-editor.org/rfc/rfc9287.html#section-3
721    GreaseQuicBit = 0x2AB2,
722
723    // https://datatracker.ietf.org/doc/html/draft-ietf-quic-ack-frequency#section-10.1
724    MinAckDelayDraft07 = 0xFF04DE1B,
725
726    // <https://datatracker.ietf.org/doc/draft-seemann-quic-address-discovery/>
727    ObservedAddr = 0x9f81a176,
728
729    // https://datatracker.ietf.org/doc/html/draft-ietf-quic-multipath
730    InitialMaxPathId = 0x0f739bbc1b666d0c,
731
732    // inspired by https://www.ietf.org/archive/id/draft-seemann-quic-nat-traversal-02.html,
733    // simplified to iroh's needs
734    IrohNatTraversal = 0x3d7f91120401,
735}
736
737impl TransportParameterId {
738    /// Array with all supported transport parameter IDs
739    const SUPPORTED: [Self; 24] = [
740        Self::MaxIdleTimeout,
741        Self::MaxUdpPayloadSize,
742        Self::InitialMaxData,
743        Self::InitialMaxStreamDataBidiLocal,
744        Self::InitialMaxStreamDataBidiRemote,
745        Self::InitialMaxStreamDataUni,
746        Self::InitialMaxStreamsBidi,
747        Self::InitialMaxStreamsUni,
748        Self::AckDelayExponent,
749        Self::MaxAckDelay,
750        Self::ActiveConnectionIdLimit,
751        Self::ReservedTransportParameter,
752        Self::StatelessResetToken,
753        Self::DisableActiveMigration,
754        Self::MaxDatagramFrameSize,
755        Self::PreferredAddress,
756        Self::OriginalDestinationConnectionId,
757        Self::InitialSourceConnectionId,
758        Self::RetrySourceConnectionId,
759        Self::GreaseQuicBit,
760        Self::MinAckDelayDraft07,
761        Self::ObservedAddr,
762        Self::InitialMaxPathId,
763        Self::IrohNatTraversal,
764    ];
765}
766
767impl std::cmp::PartialEq<u64> for TransportParameterId {
768    fn eq(&self, other: &u64) -> bool {
769        *other == (*self as u64)
770    }
771}
772
773impl TryFrom<u64> for TransportParameterId {
774    type Error = ();
775
776    fn try_from(value: u64) -> Result<Self, Self::Error> {
777        let param = match value {
778            id if Self::MaxIdleTimeout == id => Self::MaxIdleTimeout,
779            id if Self::MaxUdpPayloadSize == id => Self::MaxUdpPayloadSize,
780            id if Self::InitialMaxData == id => Self::InitialMaxData,
781            id if Self::InitialMaxStreamDataBidiLocal == id => Self::InitialMaxStreamDataBidiLocal,
782            id if Self::InitialMaxStreamDataBidiRemote == id => {
783                Self::InitialMaxStreamDataBidiRemote
784            }
785            id if Self::InitialMaxStreamDataUni == id => Self::InitialMaxStreamDataUni,
786            id if Self::InitialMaxStreamsBidi == id => Self::InitialMaxStreamsBidi,
787            id if Self::InitialMaxStreamsUni == id => Self::InitialMaxStreamsUni,
788            id if Self::AckDelayExponent == id => Self::AckDelayExponent,
789            id if Self::MaxAckDelay == id => Self::MaxAckDelay,
790            id if Self::ActiveConnectionIdLimit == id => Self::ActiveConnectionIdLimit,
791            id if Self::ReservedTransportParameter == id => Self::ReservedTransportParameter,
792            id if Self::StatelessResetToken == id => Self::StatelessResetToken,
793            id if Self::DisableActiveMigration == id => Self::DisableActiveMigration,
794            id if Self::MaxDatagramFrameSize == id => Self::MaxDatagramFrameSize,
795            id if Self::PreferredAddress == id => Self::PreferredAddress,
796            id if Self::OriginalDestinationConnectionId == id => {
797                Self::OriginalDestinationConnectionId
798            }
799            id if Self::InitialSourceConnectionId == id => Self::InitialSourceConnectionId,
800            id if Self::RetrySourceConnectionId == id => Self::RetrySourceConnectionId,
801            id if Self::GreaseQuicBit == id => Self::GreaseQuicBit,
802            id if Self::MinAckDelayDraft07 == id => Self::MinAckDelayDraft07,
803            id if Self::ObservedAddr == id => Self::ObservedAddr,
804            id if Self::InitialMaxPathId == id => Self::InitialMaxPathId,
805            id if Self::IrohNatTraversal == id => Self::IrohNatTraversal,
806            _ => return Err(()),
807        };
808        Ok(param)
809    }
810}
811
812fn decode_cid(len: usize, value: &mut Option<ConnectionId>, r: &mut impl Buf) -> Result<(), Error> {
813    if len > MAX_CID_SIZE || value.is_some() || r.remaining() < len {
814        return Err(Error::Malformed);
815    }
816
817    *value = Some(ConnectionId::from_buf(r, len));
818    Ok(())
819}
820
821#[cfg(test)]
822mod test {
823
824    use super::*;
825
826    #[test]
827    fn coding() {
828        let mut buf = Vec::new();
829        let params = TransportParameters {
830            initial_src_cid: Some(ConnectionId::new(&[])),
831            original_dst_cid: Some(ConnectionId::new(&[])),
832            initial_max_streams_bidi: 16u32.into(),
833            initial_max_streams_uni: 16u32.into(),
834            ack_delay_exponent: 2u32.into(),
835            max_udp_payload_size: 1200u32.into(),
836            preferred_address: Some(PreferredAddress {
837                address_v4: Some(SocketAddrV4::new(Ipv4Addr::LOCALHOST, 42)),
838                address_v6: Some(SocketAddrV6::new(Ipv6Addr::LOCALHOST, 24, 0, 0)),
839                connection_id: ConnectionId::new(&[0x42]),
840                stateless_reset_token: [0xab; RESET_TOKEN_SIZE].into(),
841            }),
842            grease_quic_bit: true,
843            min_ack_delay: Some(2_000u32.into()),
844            address_discovery_role: address_discovery::Role::SendOnly,
845            initial_max_path_id: Some(PathId::MAX),
846            max_remote_nat_traversal_addresses: Some(5u8.try_into().unwrap()),
847            ..TransportParameters::default()
848        };
849        params.write(&mut buf);
850        assert_eq!(
851            TransportParameters::read(Side::Client, &mut buf.as_slice()).unwrap(),
852            params
853        );
854    }
855
856    #[test]
857    fn reserved_transport_parameter_generate_reserved_id() {
858        let mut rngs = [
859            StepRng(0),
860            StepRng(1),
861            StepRng(27),
862            StepRng(31),
863            StepRng(u32::MAX as u64),
864            StepRng(u32::MAX as u64 - 1),
865            StepRng(u32::MAX as u64 + 1),
866            StepRng(u32::MAX as u64 - 27),
867            StepRng(u32::MAX as u64 + 27),
868            StepRng(u32::MAX as u64 - 31),
869            StepRng(u32::MAX as u64 + 31),
870            StepRng(u64::MAX),
871            StepRng(u64::MAX - 1),
872            StepRng(u64::MAX - 27),
873            StepRng(u64::MAX - 31),
874            StepRng(1 << 62),
875            StepRng((1 << 62) - 1),
876            StepRng((1 << 62) + 1),
877            StepRng((1 << 62) - 27),
878            StepRng((1 << 62) + 27),
879            StepRng((1 << 62) - 31),
880            StepRng((1 << 62) + 31),
881        ];
882        for rng in &mut rngs {
883            let id = ReservedTransportParameter::generate_reserved_id(rng);
884            assert!(id.0 % 31 == 27)
885        }
886    }
887
888    struct StepRng(u64);
889
890    impl RngCore for StepRng {
891        #[inline]
892        fn next_u32(&mut self) -> u32 {
893            self.next_u64() as u32
894        }
895
896        #[inline]
897        fn next_u64(&mut self) -> u64 {
898            let res = self.0;
899            self.0 = self.0.wrapping_add(1);
900            res
901        }
902
903        #[inline]
904        fn fill_bytes(&mut self, dst: &mut [u8]) {
905            let mut left = dst;
906            while left.len() >= 8 {
907                let (l, r) = left.split_at_mut(8);
908                left = r;
909                l.copy_from_slice(&self.next_u64().to_le_bytes());
910            }
911            let n = left.len();
912            if n > 0 {
913                left.copy_from_slice(&self.next_u32().to_le_bytes()[..n]);
914            }
915        }
916    }
917
918    #[test]
919    fn reserved_transport_parameter_ignored_when_read() {
920        let mut buf = Vec::new();
921        let reserved_parameter = ReservedTransportParameter::random(&mut rand::rng());
922        assert!(reserved_parameter.payload_len < ReservedTransportParameter::MAX_PAYLOAD_LEN);
923        assert!(reserved_parameter.id.0 % 31 == 27);
924
925        reserved_parameter.write(&mut buf);
926        assert!(!buf.is_empty());
927        let read_params = TransportParameters::read(Side::Server, &mut buf.as_slice()).unwrap();
928        assert_eq!(read_params, TransportParameters::default());
929    }
930
931    #[test]
932    fn read_semantic_validation() {
933        #[allow(clippy::type_complexity)]
934        let illegal_params_builders: Vec<Box<dyn FnMut(&mut TransportParameters)>> = vec![
935            Box::new(|t| {
936                // This min_ack_delay is bigger than max_ack_delay!
937                let min_ack_delay = t.max_ack_delay.0 * 1_000 + 1;
938                t.min_ack_delay = Some(VarInt::from_u64(min_ack_delay).unwrap())
939            }),
940            Box::new(|t| {
941                // Preferred address can only be sent by senders (and we are reading the transport
942                // params as a client)
943                t.preferred_address = Some(PreferredAddress {
944                    address_v4: Some(SocketAddrV4::new(Ipv4Addr::LOCALHOST, 42)),
945                    address_v6: None,
946                    connection_id: ConnectionId::new(&[]),
947                    stateless_reset_token: [0xab; RESET_TOKEN_SIZE].into(),
948                })
949            }),
950        ];
951
952        for mut builder in illegal_params_builders {
953            let mut buf = Vec::new();
954            let mut params = TransportParameters::default();
955            builder(&mut params);
956            params.write(&mut buf);
957
958            assert_eq!(
959                TransportParameters::read(Side::Server, &mut buf.as_slice()),
960                Err(Error::IllegalValue)
961            );
962        }
963    }
964
965    #[test]
966    fn resumption_params_validation() {
967        let high_limit = TransportParameters {
968            initial_max_streams_uni: 32u32.into(),
969            ..TransportParameters::default()
970        };
971        let low_limit = TransportParameters {
972            initial_max_streams_uni: 16u32.into(),
973            ..TransportParameters::default()
974        };
975        high_limit.validate_resumption_from(&low_limit).unwrap();
976        low_limit.validate_resumption_from(&high_limit).unwrap_err();
977    }
978}