1use 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 LOCAL_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
30macro_rules! apply_params {
36 ($macro:ident) => {
37 $macro! {
38 max_idle_timeout(MaxIdleTimeout) = 0,
41 max_udp_payload_size(MaxUdpPayloadSize) = 65527,
43
44 initial_max_data(InitialMaxData) = 0,
46 initial_max_stream_data_bidi_local(InitialMaxStreamDataBidiLocal) = 0,
48 initial_max_stream_data_bidi_remote(InitialMaxStreamDataBidiRemote) = 0,
50 initial_max_stream_data_uni(InitialMaxStreamDataUni) = 0,
52
53 initial_max_streams_bidi(InitialMaxStreamsBidi) = 0,
55 initial_max_streams_uni(InitialMaxStreamsUni) = 0,
57
58 ack_delay_exponent(AckDelayExponent) = 3,
60 max_ack_delay(MaxAckDelay) = 25,
63 active_connection_id_limit(ActiveConnectionIdLimit) = 2,
65 }
66 };
67}
68
69macro_rules! make_struct {
70 {$($(#[$doc:meta])* $name:ident ($id:ident) = $default:expr,)*} => {
71 #[derive(Debug, Copy, Clone, Eq, PartialEq)]
73 pub struct TransportParameters {
74 $($(#[$doc])* pub(crate) $name : VarInt,)*
75
76 pub(crate) disable_active_migration: bool,
78 pub(crate) max_datagram_frame_size: Option<VarInt>,
80 pub(crate) initial_src_cid: Option<ConnectionId>,
83 pub(crate) grease_quic_bit: bool,
86
87 pub(crate) min_ack_delay: Option<VarInt>,
93
94 pub(crate) original_dst_cid: Option<ConnectionId>,
98 pub(crate) retry_src_cid: Option<ConnectionId>,
101 pub(crate) stateless_reset_token: Option<ResetToken>,
103 pub(crate) preferred_address: Option<PreferredAddress>,
105
106 pub(crate) grease_transport_parameter: Option<ReservedTransportParameter>,
110
111 pub(crate) write_order: Option<[u8; TransportParameterId::SUPPORTED.len()]>,
116
117 pub(crate) address_discovery_role: address_discovery::Role,
119
120 pub(crate) initial_max_path_id: Option<PathId>,
122
123 pub max_remote_nat_traversal_addresses: Option<NonZeroU8>,
125 }
126
127 impl TransportParameters {
131 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 } 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 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 pub(crate) fn issue_cids_limit(&self) -> u64 {
232 self.active_connection_id_limit.0.min(LOCAL_CID_COUNT)
233 }
234}
235
236#[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#[derive(Debug, Copy, Clone, Eq, PartialEq, Error)]
303pub enum Error {
304 #[error("parameter had illegal value")]
306 IllegalValue,
307 #[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 pub fn write<W: BufMut>(&self, w: &mut W) {
330 let ids = match &self.write_order {
331 Some(order) => order,
332 None => &std::array::from_fn(|i| i as u8),
333 };
334
335 for idx in ids {
336 let id = TransportParameterId::SUPPORTED[*idx as usize];
337 match id {
338 TransportParameterId::ReservedTransportParameter => {
339 if let Some(param) = self.grease_transport_parameter {
340 param.write(w);
341 }
342 }
343 TransportParameterId::StatelessResetToken => {
344 if let Some(ref x) = self.stateless_reset_token {
345 w.write_var(id as u64);
346 w.write_var(16);
347 w.put_slice(x);
348 }
349 }
350 TransportParameterId::DisableActiveMigration => {
351 if self.disable_active_migration {
352 w.write_var(id as u64);
353 w.write_var(0);
354 }
355 }
356 TransportParameterId::MaxDatagramFrameSize => {
357 if let Some(x) = self.max_datagram_frame_size {
358 w.write_var(id as u64);
359 w.write_var(x.size() as u64);
360 w.write(x);
361 }
362 }
363 TransportParameterId::PreferredAddress => {
364 if let Some(ref x) = self.preferred_address {
365 w.write_var(id as u64);
366 w.write_var(x.wire_size() as u64);
367 x.write(w);
368 }
369 }
370 TransportParameterId::OriginalDestinationConnectionId => {
371 if let Some(ref cid) = self.original_dst_cid {
372 w.write_var(id as u64);
373 w.write_var(cid.len() as u64);
374 w.put_slice(cid);
375 }
376 }
377 TransportParameterId::InitialSourceConnectionId => {
378 if let Some(ref cid) = self.initial_src_cid {
379 w.write_var(id as u64);
380 w.write_var(cid.len() as u64);
381 w.put_slice(cid);
382 }
383 }
384 TransportParameterId::RetrySourceConnectionId => {
385 if let Some(ref cid) = self.retry_src_cid {
386 w.write_var(id as u64);
387 w.write_var(cid.len() as u64);
388 w.put_slice(cid);
389 }
390 }
391 TransportParameterId::GreaseQuicBit => {
392 if self.grease_quic_bit {
393 w.write_var(id as u64);
394 w.write_var(0);
395 }
396 }
397 TransportParameterId::MinAckDelayDraft07 => {
398 if let Some(x) = self.min_ack_delay {
399 w.write_var(id as u64);
400 w.write_var(x.size() as u64);
401 w.write(x);
402 }
403 }
404 TransportParameterId::ObservedAddr => {
405 if let Some(varint_role) = self.address_discovery_role.as_transport_parameter()
406 {
407 w.write_var(id as u64);
408 w.write_var(varint_role.size() as u64);
409 w.write(varint_role);
410 }
411 }
412 TransportParameterId::InitialMaxPathId => {
413 if let Some(val) = self.initial_max_path_id {
414 w.write_var(id as u64);
415 w.write_var(val.size() as u64);
416 w.write(val);
417 }
418 }
419 TransportParameterId::N0NatTraversal => {
420 if let Some(val) = self.max_remote_nat_traversal_addresses {
421 w.write_var(id as u64);
422 w.write(VarInt(1));
423 w.write(val.get());
424 }
425 }
426 id => {
427 macro_rules! write_params {
428 {$($(#[$doc:meta])* $name:ident ($id:ident) = $default:expr,)*} => {
429 match id {
430 $(TransportParameterId::$id => {
431 if self.$name.0 != $default {
432 w.write_var(id as u64);
433 w.write(VarInt::try_from(self.$name.size()).unwrap());
434 w.write(self.$name);
435 }
436 })*,
437 _ => {
438 unimplemented!("Missing implementation of write for transport parameter with code {id:?}");
439 }
440 }
441 }
442 }
443 apply_params!(write_params);
444 }
445 }
446 }
447 }
448
449 pub fn read<R: Buf>(side: Side, r: &mut R) -> Result<Self, Error> {
451 let mut params = Self::default();
453
454 macro_rules! param_state {
456 {$($(#[$doc:meta])* $name:ident ($id:ident) = $default:expr,)*} => {{
457 struct ParamState {
458 $($name: bool,)*
459 }
460
461 ParamState {
462 $($name: false,)*
463 }
464 }}
465 }
466 let mut got = apply_params!(param_state);
467
468 while r.has_remaining() {
469 let id = r.get_var()?;
470 let len = r.get_var()?;
471 if (r.remaining() as u64) < len {
472 return Err(Error::Malformed);
473 }
474 let len = len as usize;
475 let Ok(id) = TransportParameterId::try_from(id) else {
476 r.advance(len);
478 continue;
479 };
480
481 match id {
482 TransportParameterId::OriginalDestinationConnectionId => {
483 decode_cid(len, &mut params.original_dst_cid, r)?
484 }
485 TransportParameterId::StatelessResetToken => {
486 if len != 16 || params.stateless_reset_token.is_some() {
487 return Err(Error::Malformed);
488 }
489 let mut tok = [0; RESET_TOKEN_SIZE];
490 r.copy_to_slice(&mut tok);
491 params.stateless_reset_token = Some(tok.into());
492 }
493 TransportParameterId::DisableActiveMigration => {
494 if len != 0 || params.disable_active_migration {
495 return Err(Error::Malformed);
496 }
497 params.disable_active_migration = true;
498 }
499 TransportParameterId::PreferredAddress => {
500 if params.preferred_address.is_some() {
501 return Err(Error::Malformed);
502 }
503 params.preferred_address = Some(PreferredAddress::read(&mut r.take(len))?);
504 }
505 TransportParameterId::InitialSourceConnectionId => {
506 decode_cid(len, &mut params.initial_src_cid, r)?
507 }
508 TransportParameterId::RetrySourceConnectionId => {
509 decode_cid(len, &mut params.retry_src_cid, r)?
510 }
511 TransportParameterId::MaxDatagramFrameSize => {
512 if len > 8 || params.max_datagram_frame_size.is_some() {
513 return Err(Error::Malformed);
514 }
515 params.max_datagram_frame_size = Some(r.get()?);
516 }
517 TransportParameterId::GreaseQuicBit => match len {
518 0 => params.grease_quic_bit = true,
519 _ => return Err(Error::Malformed),
520 },
521 TransportParameterId::MinAckDelayDraft07 => params.min_ack_delay = Some(r.get()?),
522 TransportParameterId::ObservedAddr => {
523 if !params.address_discovery_role.is_disabled() {
524 return Err(Error::Malformed);
526 }
527 let value: VarInt = r.get()?;
528 if len != value.size() {
529 return Err(Error::Malformed);
530 }
531 params.address_discovery_role = value.try_into()?;
532 tracing::debug!(
533 role = ?params.address_discovery_role,
534 "address discovery enabled for peer"
535 );
536 }
537 TransportParameterId::InitialMaxPathId => {
538 if params.initial_max_path_id.is_some() {
539 return Err(Error::Malformed);
540 }
541
542 let value: PathId = r.get()?;
543 if len != value.size() {
544 return Err(Error::Malformed);
545 }
546
547 params.initial_max_path_id = Some(value);
548 }
549 TransportParameterId::N0NatTraversal => {
550 if params.max_remote_nat_traversal_addresses.is_some() {
551 return Err(Error::Malformed);
552 }
553 if len != 1 {
554 return Err(Error::Malformed);
555 }
556
557 let value: u8 = r.get()?;
558 let value = NonZeroU8::new(value).ok_or(Error::IllegalValue)?;
559
560 params.max_remote_nat_traversal_addresses = Some(value);
561 }
562 _ => {
563 macro_rules! parse {
564 {$($(#[$doc:meta])* $name:ident ($id:ident) = $default:expr,)*} => {
565 match id {
566 $(TransportParameterId::$id => {
567 let value = r.get::<VarInt>()?;
568 if len != value.size() || got.$name { return Err(Error::Malformed); }
569 params.$name = value.into();
570 got.$name = true;
571 })*
572 _ => r.advance(len),
573 }
574 }
575 }
576 apply_params!(parse);
577 }
578 }
579 }
580
581 if params.ack_delay_exponent.0 > 20
585 || params.max_ack_delay.0 >= 1 << 14
587 || params.active_connection_id_limit.0 < 2
589 || params.max_udp_payload_size.0 < 1200
591 || params.initial_max_streams_bidi.0 > MAX_STREAM_COUNT
593 || params.initial_max_streams_uni.0 > MAX_STREAM_COUNT
594 || params.min_ack_delay.is_some_and(|min_ack_delay| {
596 min_ack_delay.0 > params.max_ack_delay.0 * 1_000
598 })
599 || (side.is_server()
601 && (params.original_dst_cid.is_some()
602 || params.preferred_address.is_some()
603 || params.retry_src_cid.is_some()
604 || params.stateless_reset_token.is_some()))
605 || params
607 .preferred_address.is_some_and(|x| x.connection_id.is_empty())
608 {
609 return Err(Error::IllegalValue);
610 }
611
612 Ok(params)
613 }
614}
615
616#[derive(Debug, Copy, Clone, Eq, PartialEq)]
625pub(crate) struct ReservedTransportParameter {
626 id: VarInt,
628
629 payload: [u8; Self::MAX_PAYLOAD_LEN],
631
632 payload_len: usize,
634}
635
636impl ReservedTransportParameter {
637 fn random(rng: &mut impl RngCore) -> Self {
643 let id = Self::generate_reserved_id(rng);
644
645 let payload_len = rng.random_range(0..Self::MAX_PAYLOAD_LEN);
646
647 let payload = {
648 let mut slice = [0u8; Self::MAX_PAYLOAD_LEN];
649 rng.fill_bytes(&mut slice[..payload_len]);
650 slice
651 };
652
653 Self {
654 id,
655 payload,
656 payload_len,
657 }
658 }
659
660 fn write(&self, w: &mut impl BufMut) {
661 w.write_var(self.id.0);
662 w.write_var(self.payload_len as u64);
663 w.put_slice(&self.payload[..self.payload_len]);
664 }
665
666 fn generate_reserved_id(rng: &mut impl RngCore) -> VarInt {
671 let id = {
672 let rand = rng.random_range(0u64..(1 << 62) - 27);
673 let n = rand / 31;
674 31 * n + 27
675 };
676 debug_assert!(
677 id % 31 == 27,
678 "generated id does not have the form of 31 * N + 27"
679 );
680 VarInt::from_u64(id).expect(
681 "generated id does fit into range of allowed transport parameter IDs: [0; 2^62)",
682 )
683 }
684
685 const MAX_PAYLOAD_LEN: usize = 16;
689}
690
691#[repr(u64)]
692#[derive(Debug, Clone, Copy, PartialEq, Eq)]
693pub(crate) enum TransportParameterId {
694 OriginalDestinationConnectionId = 0x00,
696 MaxIdleTimeout = 0x01,
697 StatelessResetToken = 0x02,
698 MaxUdpPayloadSize = 0x03,
699 InitialMaxData = 0x04,
700 InitialMaxStreamDataBidiLocal = 0x05,
701 InitialMaxStreamDataBidiRemote = 0x06,
702 InitialMaxStreamDataUni = 0x07,
703 InitialMaxStreamsBidi = 0x08,
704 InitialMaxStreamsUni = 0x09,
705 AckDelayExponent = 0x0A,
706 MaxAckDelay = 0x0B,
707 DisableActiveMigration = 0x0C,
708 PreferredAddress = 0x0D,
709 ActiveConnectionIdLimit = 0x0E,
710 InitialSourceConnectionId = 0x0F,
711 RetrySourceConnectionId = 0x10,
712
713 ReservedTransportParameter = 0x1B,
715
716 MaxDatagramFrameSize = 0x20,
718
719 GreaseQuicBit = 0x2AB2,
721
722 MinAckDelayDraft07 = 0xFF04DE1B,
724
725 ObservedAddr = 0x9f81a176,
727
728 InitialMaxPathId = 0x3e,
730
731 N0NatTraversal = 0x3d7f91120401,
734}
735
736impl TransportParameterId {
737 const SUPPORTED: [Self; 24] = [
739 Self::MaxIdleTimeout,
740 Self::MaxUdpPayloadSize,
741 Self::InitialMaxData,
742 Self::InitialMaxStreamDataBidiLocal,
743 Self::InitialMaxStreamDataBidiRemote,
744 Self::InitialMaxStreamDataUni,
745 Self::InitialMaxStreamsBidi,
746 Self::InitialMaxStreamsUni,
747 Self::AckDelayExponent,
748 Self::MaxAckDelay,
749 Self::ActiveConnectionIdLimit,
750 Self::ReservedTransportParameter,
751 Self::StatelessResetToken,
752 Self::DisableActiveMigration,
753 Self::MaxDatagramFrameSize,
754 Self::PreferredAddress,
755 Self::OriginalDestinationConnectionId,
756 Self::InitialSourceConnectionId,
757 Self::RetrySourceConnectionId,
758 Self::GreaseQuicBit,
759 Self::MinAckDelayDraft07,
760 Self::ObservedAddr,
761 Self::InitialMaxPathId,
762 Self::N0NatTraversal,
763 ];
764}
765
766impl std::cmp::PartialEq<u64> for TransportParameterId {
767 fn eq(&self, other: &u64) -> bool {
768 *other == (*self as u64)
769 }
770}
771
772impl TryFrom<u64> for TransportParameterId {
773 type Error = ();
774
775 fn try_from(value: u64) -> Result<Self, Self::Error> {
776 let param = match value {
777 id if Self::MaxIdleTimeout == id => Self::MaxIdleTimeout,
778 id if Self::MaxUdpPayloadSize == id => Self::MaxUdpPayloadSize,
779 id if Self::InitialMaxData == id => Self::InitialMaxData,
780 id if Self::InitialMaxStreamDataBidiLocal == id => Self::InitialMaxStreamDataBidiLocal,
781 id if Self::InitialMaxStreamDataBidiRemote == id => {
782 Self::InitialMaxStreamDataBidiRemote
783 }
784 id if Self::InitialMaxStreamDataUni == id => Self::InitialMaxStreamDataUni,
785 id if Self::InitialMaxStreamsBidi == id => Self::InitialMaxStreamsBidi,
786 id if Self::InitialMaxStreamsUni == id => Self::InitialMaxStreamsUni,
787 id if Self::AckDelayExponent == id => Self::AckDelayExponent,
788 id if Self::MaxAckDelay == id => Self::MaxAckDelay,
789 id if Self::ActiveConnectionIdLimit == id => Self::ActiveConnectionIdLimit,
790 id if Self::ReservedTransportParameter == id => Self::ReservedTransportParameter,
791 id if Self::StatelessResetToken == id => Self::StatelessResetToken,
792 id if Self::DisableActiveMigration == id => Self::DisableActiveMigration,
793 id if Self::MaxDatagramFrameSize == id => Self::MaxDatagramFrameSize,
794 id if Self::PreferredAddress == id => Self::PreferredAddress,
795 id if Self::OriginalDestinationConnectionId == id => {
796 Self::OriginalDestinationConnectionId
797 }
798 id if Self::InitialSourceConnectionId == id => Self::InitialSourceConnectionId,
799 id if Self::RetrySourceConnectionId == id => Self::RetrySourceConnectionId,
800 id if Self::GreaseQuicBit == id => Self::GreaseQuicBit,
801 id if Self::MinAckDelayDraft07 == id => Self::MinAckDelayDraft07,
802 id if Self::ObservedAddr == id => Self::ObservedAddr,
803 id if Self::InitialMaxPathId == id => Self::InitialMaxPathId,
804 id if Self::N0NatTraversal == id => Self::N0NatTraversal,
805 _ => return Err(()),
806 };
807 Ok(param)
808 }
809}
810
811fn decode_cid(len: usize, value: &mut Option<ConnectionId>, r: &mut impl Buf) -> Result<(), Error> {
812 if len > MAX_CID_SIZE || value.is_some() || r.remaining() < len {
813 return Err(Error::Malformed);
814 }
815
816 *value = Some(ConnectionId::from_buf(r, len));
817 Ok(())
818}
819
820#[cfg(test)]
821mod test {
822
823 use super::*;
824
825 #[test]
826 fn coding() {
827 let mut buf = Vec::new();
828 let params = TransportParameters {
829 initial_src_cid: Some(ConnectionId::new(&[])),
830 original_dst_cid: Some(ConnectionId::new(&[])),
831 initial_max_streams_bidi: 16u32.into(),
832 initial_max_streams_uni: 16u32.into(),
833 ack_delay_exponent: 2u32.into(),
834 max_udp_payload_size: 1200u32.into(),
835 preferred_address: Some(PreferredAddress {
836 address_v4: Some(SocketAddrV4::new(Ipv4Addr::LOCALHOST, 42)),
837 address_v6: Some(SocketAddrV6::new(Ipv6Addr::LOCALHOST, 24, 0, 0)),
838 connection_id: ConnectionId::new(&[0x42]),
839 stateless_reset_token: [0xab; RESET_TOKEN_SIZE].into(),
840 }),
841 grease_quic_bit: true,
842 min_ack_delay: Some(2_000u32.into()),
843 address_discovery_role: address_discovery::Role::SendOnly,
844 initial_max_path_id: Some(PathId::MAX),
845 max_remote_nat_traversal_addresses: Some(5u8.try_into().unwrap()),
846 ..TransportParameters::default()
847 };
848 params.write(&mut buf);
849 assert_eq!(
850 TransportParameters::read(Side::Client, &mut buf.as_slice()).unwrap(),
851 params
852 );
853 }
854
855 #[test]
856 fn reserved_transport_parameter_generate_reserved_id() {
857 let mut rngs = [
858 StepRng(0),
859 StepRng(1),
860 StepRng(27),
861 StepRng(31),
862 StepRng(u32::MAX as u64),
863 StepRng(u32::MAX as u64 - 1),
864 StepRng(u32::MAX as u64 + 1),
865 StepRng(u32::MAX as u64 - 27),
866 StepRng(u32::MAX as u64 + 27),
867 StepRng(u32::MAX as u64 - 31),
868 StepRng(u32::MAX as u64 + 31),
869 StepRng(u64::MAX),
870 StepRng(u64::MAX - 1),
871 StepRng(u64::MAX - 27),
872 StepRng(u64::MAX - 31),
873 StepRng(1 << 62),
874 StepRng((1 << 62) - 1),
875 StepRng((1 << 62) + 1),
876 StepRng((1 << 62) - 27),
877 StepRng((1 << 62) + 27),
878 StepRng((1 << 62) - 31),
879 StepRng((1 << 62) + 31),
880 ];
881 for rng in &mut rngs {
882 let id = ReservedTransportParameter::generate_reserved_id(rng);
883 assert!(id.0 % 31 == 27)
884 }
885 }
886
887 struct StepRng(u64);
888
889 impl RngCore for StepRng {
890 #[inline]
891 fn next_u32(&mut self) -> u32 {
892 self.next_u64() as u32
893 }
894
895 #[inline]
896 fn next_u64(&mut self) -> u64 {
897 let res = self.0;
898 self.0 = self.0.wrapping_add(1);
899 res
900 }
901
902 #[inline]
903 fn fill_bytes(&mut self, dst: &mut [u8]) {
904 let mut left = dst;
905 while left.len() >= 8 {
906 let (l, r) = left.split_at_mut(8);
907 left = r;
908 l.copy_from_slice(&self.next_u64().to_le_bytes());
909 }
910 let n = left.len();
911 if n > 0 {
912 left.copy_from_slice(&self.next_u32().to_le_bytes()[..n]);
913 }
914 }
915 }
916
917 #[test]
918 fn reserved_transport_parameter_ignored_when_read() {
919 let mut buf = Vec::new();
920 let reserved_parameter = ReservedTransportParameter::random(&mut rand::rng());
921 assert!(reserved_parameter.payload_len < ReservedTransportParameter::MAX_PAYLOAD_LEN);
922 assert!(reserved_parameter.id.0 % 31 == 27);
923
924 reserved_parameter.write(&mut buf);
925 assert!(!buf.is_empty());
926 let read_params = TransportParameters::read(Side::Server, &mut buf.as_slice()).unwrap();
927 assert_eq!(read_params, TransportParameters::default());
928 }
929
930 #[test]
931 fn read_semantic_validation() {
932 #[allow(clippy::type_complexity)]
933 let illegal_params_builders: Vec<Box<dyn FnMut(&mut TransportParameters)>> = vec![
934 Box::new(|t| {
935 let min_ack_delay = t.max_ack_delay.0 * 1_000 + 1;
937 t.min_ack_delay = Some(VarInt::from_u64(min_ack_delay).unwrap())
938 }),
939 Box::new(|t| {
940 t.preferred_address = Some(PreferredAddress {
943 address_v4: Some(SocketAddrV4::new(Ipv4Addr::LOCALHOST, 42)),
944 address_v6: None,
945 connection_id: ConnectionId::new(&[]),
946 stateless_reset_token: [0xab; RESET_TOKEN_SIZE].into(),
947 })
948 }),
949 ];
950
951 for mut builder in illegal_params_builders {
952 let mut buf = Vec::new();
953 let mut params = TransportParameters::default();
954 builder(&mut params);
955 params.write(&mut buf);
956
957 assert_eq!(
958 TransportParameters::read(Side::Server, &mut buf.as_slice()),
959 Err(Error::IllegalValue)
960 );
961 }
962 }
963
964 #[test]
965 fn resumption_params_validation() {
966 let high_limit = TransportParameters {
967 initial_max_streams_uni: 32u32.into(),
968 ..TransportParameters::default()
969 };
970 let low_limit = TransportParameters {
971 initial_max_streams_uni: 16u32.into(),
972 ..TransportParameters::default()
973 };
974 high_limit.validate_resumption_from(&low_limit).unwrap();
975 low_limit.validate_resumption_from(&high_limit).unwrap_err();
976 }
977}