1use std::{
2 cmp,
3 collections::{BTreeMap, VecDeque, btree_map},
4 convert::TryFrom,
5 fmt, io, mem,
6 net::SocketAddr,
7 num::{NonZeroU32, NonZeroUsize},
8 sync::Arc,
9};
10
11use bytes::{Bytes, BytesMut};
12use frame::StreamMetaVec;
13
14use rand::{RngExt, SeedableRng, rngs::StdRng};
15use rustc_hash::{FxHashMap, FxHashSet};
16use thiserror::Error;
17use tracing::{debug, error, trace, trace_span, warn};
18
19use crate::{
20 Dir, Duration, EndpointConfig, FourTuple, Frame, INITIAL_MTU, Instant, MAX_CID_SIZE,
21 MAX_STREAM_COUNT, MIN_INITIAL_SIZE, Side, StreamId, TIMER_GRANULARITY, TokenStore, Transmit,
22 TransportError, TransportErrorCode, VarInt,
23 cid_generator::ConnectionIdGenerator,
24 cid_queue::CidQueue,
25 config::{ServerConfig, TransportConfig},
26 congestion::Controller,
27 connection::{
28 qlog::{QlogRecvPacket, QlogSink},
29 spaces::LostPacket,
30 stats::PathStatsMap,
31 timer::{ConnTimer, PathTimer},
32 },
33 crypto::{self, Keys},
34 frame::{
35 self, Close, DataBlocked, Datagram, FrameStruct, NewToken, ObservedAddr, StreamDataBlocked,
36 StreamsBlocked,
37 },
38 n0_nat_traversal,
39 packet::{
40 FixedLengthConnectionIdParser, Header, InitialHeader, InitialPacket, LongType, Packet,
41 PacketNumber, PartialDecode, SpaceId,
42 },
43 range_set::ArrayRangeSet,
44 shared::{
45 ConnectionEvent, ConnectionEventInner, ConnectionId, DatagramConnectionEvent, EcnCodepoint,
46 EndpointEvent, EndpointEventInner,
47 },
48 token::{ResetToken, Token, TokenPayload},
49 transport_parameters::TransportParameters,
50};
51
52mod ack_frequency;
53use ack_frequency::AckFrequencyState;
54
55mod assembler;
56pub use assembler::Chunk;
57
58mod cid_state;
59use cid_state::CidState;
60
61mod datagrams;
62use datagrams::DatagramState;
63pub use datagrams::{Datagrams, SendDatagramError};
64
65mod mtud;
66mod pacing;
67
68mod packet_builder;
69use packet_builder::{PacketBuilder, PadDatagram};
70
71mod packet_crypto;
72use packet_crypto::CryptoState;
73pub(crate) use packet_crypto::EncryptionLevel;
74
75mod paths;
76pub use paths::{
77 ClosedPath, PathAbandonReason, PathEvent, PathId, PathStatus, RttEstimator, SetPathStatusError,
78};
79use paths::{PathData, PathState};
80
81pub(crate) mod qlog;
82pub(crate) mod send_buffer;
83
84pub(crate) mod spaces;
85#[cfg(fuzzing)]
86pub use spaces::Retransmits;
87#[cfg(not(fuzzing))]
88use spaces::Retransmits;
89pub(crate) use spaces::SpaceKind;
90use spaces::{PacketSpace, SendableFrames, SentPacket, ThinRetransmits};
91
92mod stats;
93pub use stats::{ConnectionStats, FrameStats, PathStats, UdpStats};
94
95mod streams;
96#[cfg(fuzzing)]
97pub use streams::StreamsState;
98#[cfg(not(fuzzing))]
99use streams::StreamsState;
100pub use streams::{
101 Chunks, ClosedStream, FinishError, ReadError, ReadableError, RecvStream, SendStream,
102 ShouldTransmit, StreamEvent, Streams, WriteError,
103};
104
105mod timer;
106use timer::{Timer, TimerTable};
107
108mod transmit_buf;
109use transmit_buf::TransmitBuf;
110
111mod state;
112
113#[cfg(not(fuzzing))]
114use state::State;
115#[cfg(fuzzing)]
116pub use state::State;
117use state::StateType;
118
119pub struct Connection {
159 endpoint_config: Arc<EndpointConfig>,
160 config: Arc<TransportConfig>,
161 rng: StdRng,
162 crypto_state: CryptoState,
164 handshake_cid: ConnectionId,
166 remote_handshake_cid: ConnectionId,
168 paths: BTreeMap<PathId, PathState>,
174 path_generation_counter: u64,
185 allow_mtud: bool,
187 state: State,
188 side: ConnectionSide,
189 peer_params: TransportParameters,
191 original_remote_cid: ConnectionId,
193 initial_dst_cid: ConnectionId,
195 retry_src_cid: Option<ConnectionId>,
198 events: VecDeque<Event>,
200 endpoint_events: VecDeque<EndpointEventInner>,
201 spin_enabled: bool,
203 spin: bool,
205 spaces: [PacketSpace; 3],
207 highest_space: SpaceKind,
209 idle_timeout: Option<Duration>,
211 timers: TimerTable,
212 authentication_failures: u64,
214
215 connection_close_pending: bool,
220
221 ack_frequency: AckFrequencyState,
225
226 receiving_ecn: bool,
231 total_authed_packets: u64,
233
234 next_observed_addr_seq_no: VarInt,
239
240 streams: StreamsState,
241 remote_cids: FxHashMap<PathId, CidQueue>,
247 local_cid_state: FxHashMap<PathId, CidState>,
254 datagrams: DatagramState,
256 path_stats: PathStatsMap,
258 partial_stats: ConnectionStats,
264 version: u32,
266
267 max_concurrent_paths: NonZeroU32,
276 local_max_path_id: PathId,
291 remote_max_path_id: PathId,
297 max_path_id_with_cids: PathId,
303 abandoned_paths: FxHashSet<PathId>,
311
312 n0_nat_traversal: n0_nat_traversal::State,
314 qlog: QlogSink,
315}
316
317impl Connection {
318 pub(crate) fn new(
319 endpoint_config: Arc<EndpointConfig>,
320 config: Arc<TransportConfig>,
321 init_cid: ConnectionId,
322 local_cid: ConnectionId,
323 remote_cid: ConnectionId,
324 network_path: FourTuple,
325 crypto: Box<dyn crypto::Session>,
326 cid_gen: &dyn ConnectionIdGenerator,
327 now: Instant,
328 version: u32,
329 allow_mtud: bool,
330 rng_seed: [u8; 32],
331 side_args: SideArgs,
332 qlog: QlogSink,
333 ) -> Self {
334 let pref_addr_cid = side_args.pref_addr_cid();
335 let path_validated = side_args.path_validated();
336 let connection_side = ConnectionSide::from(side_args);
337 let side = connection_side.side();
338 let mut rng = StdRng::from_seed(rng_seed);
339 let initial_space = PacketSpace::new(now, SpaceId::Initial, &mut rng);
340 let handshake_space = PacketSpace::new(now, SpaceId::Handshake, &mut rng);
341 #[cfg(test)]
342 let data_space = match config.deterministic_packet_numbers {
343 true => PacketSpace::new_deterministic(now, SpaceId::Data),
344 false => PacketSpace::new(now, SpaceId::Data, &mut rng),
345 };
346 #[cfg(not(test))]
347 let data_space = PacketSpace::new(now, SpaceId::Data, &mut rng);
348 let state = State::handshake(state::Handshake {
349 remote_cid_set: side.is_server(),
350 expected_token: Bytes::new(),
351 client_hello: None,
352 allow_server_migration: side.is_client(),
353 });
354 let local_cid_state = FxHashMap::from_iter([(
355 PathId::ZERO,
356 CidState::new(
357 cid_gen.cid_len(),
358 cid_gen.cid_lifetime(),
359 now,
360 if pref_addr_cid.is_some() { 2 } else { 1 },
361 ),
362 )]);
363
364 let mut path = PathData::new(network_path, allow_mtud, None, 0, now, &config);
365 path.open_status = paths::OpenStatus::Informed;
366 let mut this = Self {
367 endpoint_config,
368 crypto_state: CryptoState::new(crypto, init_cid, side, &mut rng),
369 handshake_cid: local_cid,
370 remote_handshake_cid: remote_cid,
371 local_cid_state,
372 paths: BTreeMap::from_iter([(
373 PathId::ZERO,
374 PathState {
375 data: path,
376 prev: None,
377 },
378 )]),
379 path_generation_counter: 0,
380 allow_mtud,
381 state,
382 side: connection_side,
383 peer_params: TransportParameters::default(),
384 original_remote_cid: remote_cid,
385 initial_dst_cid: init_cid,
386 retry_src_cid: None,
387 events: VecDeque::new(),
388 endpoint_events: VecDeque::new(),
389 spin_enabled: config.allow_spin && rng.random_ratio(7, 8),
390 spin: false,
391 spaces: [initial_space, handshake_space, data_space],
392 highest_space: SpaceKind::Initial,
393 idle_timeout: match config.max_idle_timeout {
394 None | Some(VarInt(0)) => None,
395 Some(dur) => Some(Duration::from_millis(dur.0)),
396 },
397 timers: TimerTable::default(),
398 authentication_failures: 0,
399 connection_close_pending: false,
400
401 ack_frequency: AckFrequencyState::new(get_max_ack_delay(
402 &TransportParameters::default(),
403 )),
404
405 receiving_ecn: false,
406 total_authed_packets: 0,
407
408 next_observed_addr_seq_no: 0u32.into(),
409
410 streams: StreamsState::new(
411 side,
412 config.max_concurrent_uni_streams,
413 config.max_concurrent_bidi_streams,
414 config.send_window,
415 config.receive_window,
416 config.stream_receive_window,
417 ),
418 datagrams: DatagramState::default(),
419 config,
420 remote_cids: FxHashMap::from_iter([(PathId::ZERO, CidQueue::new(remote_cid))]),
421 rng,
422 path_stats: Default::default(),
423 partial_stats: ConnectionStats::default(),
424 version,
425
426 max_concurrent_paths: NonZeroU32::MIN,
428 local_max_path_id: PathId::ZERO,
429 remote_max_path_id: PathId::ZERO,
430 max_path_id_with_cids: PathId::ZERO,
431 abandoned_paths: Default::default(),
432
433 n0_nat_traversal: Default::default(),
434 qlog,
435 };
436 if path_validated {
437 this.on_path_validated(PathId::ZERO);
438 }
439 if side.is_client() {
440 this.write_crypto();
442 this.init_0rtt(now);
443 }
444 this.qlog
445 .emit_tuple_assigned(PathId::ZERO, network_path, now);
446 this
447 }
448
449 #[must_use]
457 pub fn poll_timeout(&mut self) -> Option<Instant> {
458 self.timers.peek()
459 }
460
461 #[must_use]
467 pub fn poll(&mut self) -> Option<Event> {
468 if let Some(x) = self.events.pop_front() {
469 return Some(x);
470 }
471
472 if let Some(event) = self.streams.poll() {
473 return Some(Event::Stream(event));
474 }
475
476 if let Some(reason) = self.state.take_error() {
477 return Some(Event::ConnectionLost { reason });
478 }
479
480 None
481 }
482
483 #[must_use]
485 pub fn poll_endpoint_events(&mut self) -> Option<EndpointEvent> {
486 self.endpoint_events.pop_front().map(EndpointEvent)
487 }
488
489 #[must_use]
491 pub fn streams(&mut self) -> Streams<'_> {
492 Streams {
493 state: &mut self.streams,
494 conn_state: &self.state,
495 }
496 }
497
498 #[must_use]
500 pub fn recv_stream(&mut self, id: StreamId) -> RecvStream<'_> {
501 assert!(id.dir() == Dir::Bi || id.initiator() != self.side.side());
502 RecvStream {
503 id,
504 state: &mut self.streams,
505 pending: &mut self.spaces[SpaceId::Data].pending,
506 }
507 }
508
509 #[must_use]
511 pub fn send_stream(&mut self, id: StreamId) -> SendStream<'_> {
512 assert!(id.dir() == Dir::Bi || id.initiator() == self.side.side());
513 SendStream {
514 id,
515 state: &mut self.streams,
516 pending: &mut self.spaces[SpaceId::Data].pending,
517 conn_state: &self.state,
518 }
519 }
520
521 pub fn open_path_ensure(
538 &mut self,
539 network_path: FourTuple,
540 initial_status: PathStatus,
541 now: Instant,
542 ) -> Result<(PathId, bool), PathError> {
543 let existing_open_path = self.paths.iter().find(|(id, path)| {
544 network_path.is_probably_same_path(&path.data.network_path)
545 && !self.abandoned_paths.contains(*id)
546 });
547 match existing_open_path {
548 Some((path_id, _state)) => Ok((*path_id, true)),
549 None => Ok((self.open_path(network_path, initial_status, now)?, false)),
550 }
551 }
552
553 pub fn open_path(
559 &mut self,
560 network_path: FourTuple,
561 initial_status: PathStatus,
562 now: Instant,
563 ) -> Result<PathId, PathError> {
564 if !self.is_multipath_negotiated() {
565 return Err(PathError::MultipathNotNegotiated);
566 }
567 if self.side().is_server() {
568 return Err(PathError::ServerSideNotAllowed);
569 }
570
571 let max_abandoned = self.abandoned_paths.iter().max().copied();
572 let max_used = self.paths.keys().last().copied();
573 let path_id = max_abandoned
574 .max(max_used)
575 .unwrap_or(PathId::ZERO)
576 .saturating_add(1u8);
577
578 if Some(path_id) > self.max_path_id() {
579 return Err(PathError::MaxPathIdReached);
580 }
581 if path_id > self.remote_max_path_id {
582 self.spaces[SpaceId::Data].pending.paths_blocked = true;
583 return Err(PathError::MaxPathIdReached);
584 }
585 if self
586 .remote_cids
587 .get(&path_id)
588 .map(CidQueue::active)
589 .is_none()
590 {
591 self.spaces[SpaceId::Data]
592 .pending
593 .path_cids_blocked
594 .insert(path_id);
595 return Err(PathError::RemoteCidsExhausted);
596 }
597
598 let path = self.ensure_path(path_id, network_path, now, None);
599 path.status.local_update(initial_status);
600
601 Ok(path_id)
602 }
603
604 pub fn close_path(
610 &mut self,
611 now: Instant,
612 path_id: PathId,
613 error_code: VarInt,
614 ) -> Result<(), ClosePathError> {
615 self.close_path_inner(
616 now,
617 path_id,
618 PathAbandonReason::ApplicationClosed { error_code },
619 )
620 }
621
622 pub(crate) fn close_path_inner(
627 &mut self,
628 now: Instant,
629 path_id: PathId,
630 reason: PathAbandonReason,
631 ) -> Result<(), ClosePathError> {
632 if self.state.is_drained() {
633 return Ok(());
634 }
635
636 if !self.is_multipath_negotiated() {
637 return Err(ClosePathError::MultipathNotNegotiated);
638 }
639 if self.abandoned_paths.contains(&path_id)
640 || Some(path_id) > self.max_path_id()
641 || !self.paths.contains_key(&path_id)
642 {
643 return Err(ClosePathError::ClosedPath);
644 }
645
646 let is_last_path = !self
647 .paths
648 .keys()
649 .any(|id| *id != path_id && !self.abandoned_paths.contains(id));
650
651 if is_last_path && !reason.is_remote() {
652 return Err(ClosePathError::LastOpenPath);
653 }
654
655 self.abandon_path(now, path_id, reason);
656
657 if is_last_path {
661 let rtt = RttEstimator::new(self.config.initial_rtt);
665 let pto = rtt.pto_base() + self.ack_frequency.max_ack_delay_for_pto();
666 let grace = pto * 3;
667 self.timers.set(
668 Timer::Conn(ConnTimer::NoAvailablePath),
669 now + grace,
670 self.qlog.with_time(now),
671 );
672 }
673
674 Ok(())
675 }
676
677 fn abandon_path(&mut self, now: Instant, path_id: PathId, reason: PathAbandonReason) {
682 trace!(%path_id, ?reason, "abandoning path");
683
684 let pending_space = &mut self.spaces[SpaceId::Data].pending;
685 pending_space
687 .path_abandon
688 .insert(path_id, reason.error_code());
689
690 pending_space.new_cids.retain(|cid| cid.path_id != path_id);
692 pending_space.path_cids_blocked.retain(|&id| id != path_id);
693 pending_space.path_status.retain(|&id| id != path_id);
694
695 for space in self.spaces[SpaceId::Data].iter_paths_mut() {
697 for sent_packet in space.sent_packets.values_mut() {
698 if let Some(retransmits) = sent_packet.retransmits.get_mut() {
699 retransmits.new_cids.retain(|cid| cid.path_id != path_id);
700 retransmits.path_cids_blocked.retain(|&id| id != path_id);
701 retransmits.path_status.retain(|&id| id != path_id);
702 }
703 }
704 }
705
706 self.spaces[SpaceId::Data].for_path(path_id).loss_probes = 0;
711
712 debug_assert!(!self.state.is_drained()); self.endpoint_events
717 .push_back(EndpointEventInner::RetireResetToken(path_id));
718
719 self.abandoned_paths.insert(path_id);
720
721 for timer in timer::PathTimer::VALUES {
722 let keep_timer = match timer {
724 PathTimer::PathValidationFailed
728 | PathTimer::PathChallengeLost
729 | PathTimer::AbandonFromValidation => false,
730 PathTimer::PathKeepAlive | PathTimer::PathIdle => false,
733 PathTimer::MaxAckDelay => false,
736 PathTimer::PathDrained => false,
739 PathTimer::LossDetection => true,
742 PathTimer::Pacing => true,
746 };
747
748 if !keep_timer {
749 let qlog = self.qlog.with_time(now);
750 self.timers.stop(Timer::PerPath(path_id, timer), qlog);
751 }
752 }
753
754 self.set_loss_detection_timer(now, path_id);
759
760 self.events.push_back(Event::Path(PathEvent::Abandoned {
762 id: path_id,
763 reason,
764 }));
765 }
766
767 #[track_caller]
771 fn path_data(&self, path_id: PathId) -> &PathData {
772 if let Some(data) = self.paths.get(&path_id) {
773 &data.data
774 } else {
775 panic!(
776 "unknown path: {path_id}, currently known paths: {:?}",
777 self.paths.keys().collect::<Vec<_>>()
778 );
779 }
780 }
781
782 #[track_caller]
786 fn path_data_mut(&mut self, path_id: PathId) -> &mut PathData {
787 &mut self.paths.get_mut(&path_id).expect("known path").data
788 }
789
790 fn path(&self, path_id: PathId) -> Option<&PathData> {
792 self.paths.get(&path_id).map(|path_state| &path_state.data)
793 }
794
795 fn path_mut(&mut self, path_id: PathId) -> Option<&mut PathData> {
797 self.paths
798 .get_mut(&path_id)
799 .map(|path_state| &mut path_state.data)
800 }
801
802 pub fn paths(&self) -> Vec<PathId> {
806 self.paths.keys().copied().collect()
807 }
808
809 pub fn path_status(&self, path_id: PathId) -> Result<PathStatus, ClosedPath> {
811 self.path(path_id)
812 .map(PathData::local_status)
813 .ok_or(ClosedPath { _private: () })
814 }
815
816 pub fn network_path(&self, path_id: PathId) -> Result<FourTuple, ClosedPath> {
818 self.path(path_id)
819 .map(|path| path.network_path)
820 .ok_or(ClosedPath { _private: () })
821 }
822
823 pub fn set_path_status(
827 &mut self,
828 path_id: PathId,
829 status: PathStatus,
830 ) -> Result<PathStatus, SetPathStatusError> {
831 if !self.is_multipath_negotiated() {
832 return Err(SetPathStatusError::MultipathNotNegotiated);
833 }
834 let path = self
835 .path_mut(path_id)
836 .ok_or(SetPathStatusError::ClosedPath)?;
837 let prev = match path.status.local_update(status) {
838 Some(prev) => {
839 self.spaces[SpaceId::Data]
840 .pending
841 .path_status
842 .insert(path_id);
843 prev
844 }
845 None => path.local_status(),
846 };
847 Ok(prev)
848 }
849
850 pub fn remote_path_status(&self, path_id: PathId) -> Option<PathStatus> {
855 self.path(path_id).and_then(|path| path.remote_status())
856 }
857
858 pub fn set_path_max_idle_timeout(
867 &mut self,
868 now: Instant,
869 path_id: PathId,
870 timeout: Option<Duration>,
871 ) -> Result<Option<Duration>, ClosedPath> {
872 let path = self
873 .paths
874 .get_mut(&path_id)
875 .ok_or(ClosedPath { _private: () })?;
876 let prev = std::mem::replace(&mut path.data.idle_timeout, timeout);
877
878 if !self.state.is_closed() {
880 if let Some(new_timeout) = timeout {
881 let timer = Timer::PerPath(path_id, PathTimer::PathIdle);
882 let deadline = match (prev, self.timers.get(timer)) {
883 (Some(old_timeout), Some(old_deadline)) => {
884 let last_activity = old_deadline.checked_sub(old_timeout).unwrap_or(now);
885 last_activity + new_timeout
886 }
887 _ => now + new_timeout,
888 };
889 self.timers.set(timer, deadline, self.qlog.with_time(now));
890 } else {
891 self.timers.stop(
892 Timer::PerPath(path_id, PathTimer::PathIdle),
893 self.qlog.with_time(now),
894 );
895 }
896 }
897
898 Ok(prev)
899 }
900
901 pub fn set_path_keep_alive_interval(
907 &mut self,
908 path_id: PathId,
909 interval: Option<Duration>,
910 ) -> Result<Option<Duration>, ClosedPath> {
911 let path = self
912 .paths
913 .get_mut(&path_id)
914 .ok_or(ClosedPath { _private: () })?;
915 Ok(std::mem::replace(&mut path.data.keep_alive, interval))
916 }
917
918 fn find_validated_path_on_network_path(
922 &self,
923 network_path: FourTuple,
924 ) -> Option<(&PathId, &PathState)> {
925 self.paths.iter().find(|(path_id, path_state)| {
926 path_state.data.validated
927 && network_path.is_probably_same_path(&path_state.data.network_path)
929 && !self.abandoned_paths.contains(path_id)
930 })
931 }
935
936 fn ensure_path(
940 &mut self,
941 path_id: PathId,
942 network_path: FourTuple,
943 now: Instant,
944 pn: Option<u64>,
945 ) -> &mut PathData {
946 let valid_path = self.find_validated_path_on_network_path(network_path);
947 let validated = valid_path.is_some();
948 let initial_rtt = valid_path.map(|(_, path)| path.data.rtt.conservative());
949 let vacant_entry = match self.paths.entry(path_id) {
950 btree_map::Entry::Vacant(vacant_entry) => vacant_entry,
951 btree_map::Entry::Occupied(occupied_entry) => {
952 return &mut occupied_entry.into_mut().data;
953 }
954 };
955
956 debug!(%validated, %path_id, %network_path, "path added");
957
958 self.timers.stop(
960 Timer::Conn(ConnTimer::NoAvailablePath),
961 self.qlog.with_time(now),
962 );
963 let peer_max_udp_payload_size =
964 u16::try_from(self.peer_params.max_udp_payload_size.into_inner()).unwrap_or(u16::MAX);
965 self.path_generation_counter = self.path_generation_counter.wrapping_add(1);
966 let mut data = PathData::new(
967 network_path,
968 self.allow_mtud,
969 Some(peer_max_udp_payload_size),
970 self.path_generation_counter,
971 now,
972 &self.config,
973 );
974
975 data.validated = validated;
976 if let Some(initial_rtt) = initial_rtt {
977 data.rtt.reset_initial_rtt(initial_rtt);
978 }
979
980 data.pending_on_path_challenge = true;
983
984 let path = vacant_entry.insert(PathState { data, prev: None });
985
986 let mut pn_space = spaces::PacketNumberSpace::new(now, SpaceId::Data, &mut self.rng);
987 if let Some(pn) = pn {
988 pn_space.dedup.insert(pn);
989 }
990 self.spaces[SpaceId::Data]
991 .number_spaces
992 .insert(path_id, pn_space);
993 self.qlog.emit_tuple_assigned(path_id, network_path, now);
994
995 if !self.remote_cids.contains_key(&path_id) {
999 debug!(%path_id, "Remote opened path without issuing CIDs");
1000 self.spaces[SpaceId::Data]
1001 .pending
1002 .path_cids_blocked
1003 .insert(path_id);
1004 }
1007
1008 &mut path.data
1009 }
1010
1011 #[must_use]
1021 pub fn poll_transmit(
1022 &mut self,
1023 now: Instant,
1024 max_datagrams: NonZeroUsize,
1025 buf: &mut Vec<u8>,
1026 ) -> Option<Transmit> {
1027 let max_datagrams = match self.config.enable_segmentation_offload {
1028 false => NonZeroUsize::MIN,
1029 true => max_datagrams,
1030 };
1031
1032 let connection_close_pending = match self.state.as_type() {
1038 StateType::Drained => {
1039 for path in self.paths.values_mut() {
1040 path.data.app_limited = true;
1041 }
1042 return None;
1043 }
1044 StateType::Draining | StateType::Closed => {
1045 if !self.connection_close_pending {
1048 for path in self.paths.values_mut() {
1049 path.data.app_limited = true;
1050 }
1051 return None;
1052 }
1053 true
1054 }
1055 _ => false,
1056 };
1057
1058 if let Some(config) = &self.config.ack_frequency_config {
1060 let rtt = self
1061 .paths
1062 .values()
1063 .map(|p| p.data.rtt.get())
1064 .min()
1065 .expect("one path exists");
1066 self.spaces[SpaceId::Data].pending.ack_frequency = self
1067 .ack_frequency
1068 .should_send_ack_frequency(rtt, config, &self.peer_params)
1069 && self.highest_space == SpaceKind::Data
1070 && self.peer_supports_ack_frequency();
1071 }
1072
1073 let mut next_path_id = self.paths.first_entry().map(|e| *e.key());
1074 while let Some(path_id) = next_path_id {
1075 if !connection_close_pending
1076 && let Some(transmit) = self.poll_transmit_off_path(now, buf, path_id)
1077 {
1078 return Some(transmit);
1079 }
1080
1081 let info = self.scheduling_info(path_id);
1082 if let Some(transmit) = self.poll_transmit_on_path(
1083 now,
1084 buf,
1085 path_id,
1086 max_datagrams,
1087 &info,
1088 connection_close_pending,
1089 ) {
1090 return Some(transmit);
1091 }
1092
1093 debug_assert!(
1096 buf.is_empty(),
1097 "nothing to send on path but buffer not empty"
1098 );
1099
1100 next_path_id = self.paths.keys().find(|i| **i > path_id).copied();
1101 }
1102
1103 debug_assert!(
1105 buf.is_empty(),
1106 "there was data in the buffer, but it was not sent"
1107 );
1108
1109 if self.state.is_established() {
1110 let mut next_path_id = self.paths.first_entry().map(|e| *e.key());
1112 while let Some(path_id) = next_path_id {
1113 if let Some(transmit) = self.poll_transmit_mtu_probe(now, buf, path_id) {
1114 return Some(transmit);
1115 }
1116 next_path_id = self.paths.keys().find(|i| **i > path_id).copied();
1117 }
1118 }
1119
1120 None
1121 }
1122
1123 fn scheduling_info(&self, path_id: PathId) -> PathSchedulingInfo {
1141 let have_validated_status_available_space = self.paths.iter().any(|(path_id, path)| {
1143 self.remote_cids.contains_key(path_id)
1144 && !self.abandoned_paths.contains(path_id)
1145 && path.data.validated
1146 && path.data.local_status() == PathStatus::Available
1147 });
1148
1149 let have_validated_space = self.paths.iter().any(|(path_id, path)| {
1151 self.remote_cids.contains_key(path_id)
1152 && !self.abandoned_paths.contains(path_id)
1153 && path.data.validated
1154 });
1155
1156 let is_handshaking = self.is_handshaking();
1157 let has_cids = self.remote_cids.contains_key(&path_id);
1158 let is_abandoned = self.abandoned_paths.contains(&path_id);
1159 let path_data = self.path_data(path_id);
1160 let validated = path_data.validated;
1161 let status = path_data.local_status();
1162
1163 let may_send_data = has_cids
1166 && !is_abandoned
1167 && if is_handshaking {
1168 true
1172 } else if !validated {
1173 false
1180 } else {
1181 match status {
1182 PathStatus::Available => {
1183 true
1185 }
1186 PathStatus::Backup => {
1187 !have_validated_status_available_space
1189 }
1190 }
1191 };
1192
1193 let may_send_close = has_cids
1198 && !is_abandoned
1199 && if !validated && have_validated_status_available_space {
1200 false
1202 } else {
1203 true
1205 };
1206
1207 let may_self_abandon = has_cids && validated && !have_validated_space;
1211
1212 PathSchedulingInfo {
1213 is_abandoned,
1214 may_send_data,
1215 may_send_close,
1216 may_self_abandon,
1217 }
1218 }
1219
1220 fn build_transmit(&mut self, path_id: PathId, transmit: TransmitBuf<'_>) -> Transmit {
1221 debug_assert!(
1222 !transmit.is_empty(),
1223 "must not be called with an empty transmit buffer"
1224 );
1225
1226 let network_path = self.path_data(path_id).network_path;
1227 trace!(
1228 segment_size = transmit.segment_size(),
1229 last_datagram_len = transmit.len() % transmit.segment_size(),
1230 %network_path,
1231 "sending {} bytes in {} datagrams",
1232 transmit.len(),
1233 transmit.num_datagrams()
1234 );
1235 self.path_data_mut(path_id)
1236 .inc_total_sent(transmit.len() as u64);
1237
1238 self.path_stats
1239 .for_path(path_id)
1240 .udp_tx
1241 .on_sent(transmit.num_datagrams() as u64, transmit.len());
1242
1243 Transmit {
1244 destination: network_path.remote,
1245 size: transmit.len(),
1246 ecn: if self.path_data(path_id).sending_ecn {
1247 Some(EcnCodepoint::Ect0)
1248 } else {
1249 None
1250 },
1251 segment_size: match transmit.num_datagrams() {
1252 1 => None,
1253 _ => Some(transmit.segment_size()),
1254 },
1255 src_ip: network_path.local_ip,
1256 }
1257 }
1258
1259 fn poll_transmit_off_path(
1261 &mut self,
1262 now: Instant,
1263 buf: &mut Vec<u8>,
1264 path_id: PathId,
1265 ) -> Option<Transmit> {
1266 if let Some(challenge) = self.send_prev_path_challenge(now, buf, path_id) {
1267 return Some(challenge);
1268 }
1269 if let Some(response) = self.send_off_path_path_response(now, buf, path_id) {
1270 return Some(response);
1271 }
1272 if let Some(challenge) = self.send_nat_traversal_path_challenge(now, buf, path_id) {
1273 return Some(challenge);
1274 }
1275 None
1276 }
1277
1278 #[must_use]
1285 fn poll_transmit_on_path(
1286 &mut self,
1287 now: Instant,
1288 buf: &mut Vec<u8>,
1289 path_id: PathId,
1290 max_datagrams: NonZeroUsize,
1291 scheduling_info: &PathSchedulingInfo,
1292 connection_close_pending: bool,
1293 ) -> Option<Transmit> {
1294 let Some(remote_cid) = self.remote_cids.get(&path_id).map(CidQueue::active) else {
1296 if !self.abandoned_paths.contains(&path_id) {
1297 debug!(%path_id, "no remote CIDs for path");
1298 }
1299 return None;
1300 };
1301
1302 let mut pad_datagram = PadDatagram::No;
1308
1309 let mut last_packet_number = None;
1313
1314 let mut congestion_blocked = false;
1317
1318 let pmtu = self.path_data(path_id).current_mtu().into();
1320 let mut transmit = TransmitBuf::new(buf, max_datagrams, pmtu);
1321
1322 for space_id in SpaceId::iter() {
1324 if path_id != PathId::ZERO && space_id != SpaceId::Data {
1326 continue;
1327 }
1328 match self.poll_transmit_path_space(
1329 now,
1330 &mut transmit,
1331 path_id,
1332 space_id,
1333 remote_cid,
1334 scheduling_info,
1335 connection_close_pending,
1336 pad_datagram,
1337 ) {
1338 PollPathSpaceStatus::NothingToSend {
1339 congestion_blocked: cb,
1340 } => {
1341 congestion_blocked |= cb;
1342 }
1345 PollPathSpaceStatus::WrotePacket {
1346 last_packet_number: pn,
1347 pad_datagram: pad,
1348 } => {
1349 debug_assert!(!transmit.is_empty(), "transmit must contain packets");
1350 last_packet_number = Some(pn);
1351 pad_datagram = pad;
1352 continue;
1357 }
1358 PollPathSpaceStatus::Send {
1359 last_packet_number: pn,
1360 } => {
1361 debug_assert!(!transmit.is_empty(), "transmit must contain packets");
1362 last_packet_number = Some(pn);
1363 break;
1364 }
1365 }
1366 }
1367
1368 if last_packet_number.is_some() || congestion_blocked {
1369 self.qlog.emit_recovery_metrics(
1370 path_id,
1371 &mut self
1372 .paths
1373 .get_mut(&path_id)
1374 .expect("path_id was iterated from self.paths above")
1375 .data,
1376 now,
1377 );
1378 }
1379
1380 self.path_data_mut(path_id).app_limited =
1381 last_packet_number.is_none() && !congestion_blocked;
1382
1383 match last_packet_number {
1384 Some(last_packet_number) => {
1385 self.path_data_mut(path_id).congestion.on_sent(
1388 now,
1389 transmit.len() as u64,
1390 last_packet_number,
1391 );
1392 Some(self.build_transmit(path_id, transmit))
1393 }
1394 None => None,
1395 }
1396 }
1397
1398 #[must_use]
1400 fn poll_transmit_path_space(
1401 &mut self,
1402 now: Instant,
1403 transmit: &mut TransmitBuf<'_>,
1404 path_id: PathId,
1405 space_id: SpaceId,
1406 remote_cid: ConnectionId,
1407 scheduling_info: &PathSchedulingInfo,
1408 connection_close_pending: bool,
1410 mut pad_datagram: PadDatagram,
1412 ) -> PollPathSpaceStatus {
1413 let mut last_packet_number = None;
1416
1417 loop {
1433 let max_packet_size = if transmit.datagram_remaining_mut() > 0 {
1435 transmit.datagram_remaining_mut()
1437 } else {
1438 transmit.segment_size()
1440 };
1441 let can_send =
1442 self.space_can_send(space_id, path_id, max_packet_size, connection_close_pending);
1443 let needs_loss_probe = self.spaces[space_id].for_path(path_id).loss_probes > 0;
1444 let space_will_send = {
1445 if scheduling_info.is_abandoned {
1446 scheduling_info.may_self_abandon
1451 && self.spaces[space_id]
1452 .pending
1453 .path_abandon
1454 .contains_key(&path_id)
1455 } else if can_send.close && scheduling_info.may_send_close {
1456 true
1458 } else if needs_loss_probe || can_send.space_specific {
1459 true
1462 } else {
1463 !can_send.is_empty() && scheduling_info.may_send_data
1466 }
1467 };
1468
1469 if !space_will_send {
1470 return match last_packet_number {
1473 Some(pn) => PollPathSpaceStatus::WrotePacket {
1474 last_packet_number: pn,
1475 pad_datagram,
1476 },
1477 None => {
1478 if self.crypto_state.has_keys(space_id.encryption_level())
1480 || (space_id == SpaceId::Data
1481 && self.crypto_state.has_keys(EncryptionLevel::ZeroRtt))
1482 {
1483 trace!(?space_id, %path_id, "nothing to send in space");
1484 }
1485 PollPathSpaceStatus::NothingToSend {
1486 congestion_blocked: false,
1487 }
1488 }
1489 };
1490 }
1491
1492 if transmit.datagram_remaining_mut() == 0 {
1496 let congestion_blocked =
1497 self.path_congestion_check(space_id, path_id, transmit, &can_send, now);
1498 if congestion_blocked != PathBlocked::No {
1499 return match last_packet_number {
1501 Some(pn) => PollPathSpaceStatus::WrotePacket {
1502 last_packet_number: pn,
1503 pad_datagram,
1504 },
1505 None => {
1506 return PollPathSpaceStatus::NothingToSend {
1507 congestion_blocked: true,
1508 };
1509 }
1510 };
1511 }
1512
1513 if transmit.num_datagrams() >= transmit.max_datagrams().get() {
1516 return match last_packet_number {
1519 Some(pn) => PollPathSpaceStatus::WrotePacket {
1520 last_packet_number: pn,
1521 pad_datagram,
1522 },
1523 None => {
1524 return PollPathSpaceStatus::NothingToSend {
1525 congestion_blocked: false,
1526 };
1527 }
1528 };
1529 }
1530
1531 if needs_loss_probe {
1532 let request_immediate_ack =
1534 space_id == SpaceId::Data && self.peer_supports_ack_frequency();
1535 self.spaces[space_id].queue_tail_loss_probe(
1536 path_id,
1537 request_immediate_ack,
1538 &self.streams,
1539 );
1540
1541 self.spaces[space_id].for_path(path_id).loss_probes -= 1; transmit.start_new_datagram_with_size(std::cmp::min(
1547 usize::from(INITIAL_MTU),
1548 transmit.segment_size(),
1549 ));
1550 } else {
1551 transmit.start_new_datagram();
1552 }
1553 trace!(count = transmit.num_datagrams(), "new datagram started");
1554
1555 pad_datagram = PadDatagram::No;
1557 }
1558
1559 if transmit.datagram_start_offset() < transmit.len() {
1562 debug_assert!(transmit.datagram_remaining_mut() >= MIN_PACKET_SPACE);
1563 }
1564
1565 if self.crypto_state.has_keys(EncryptionLevel::Initial)
1570 && space_id == SpaceId::Handshake
1571 && self.side.is_client()
1572 {
1573 self.discard_space(now, SpaceKind::Initial);
1576 }
1577 if let Some(ref mut prev) = self.crypto_state.prev_crypto {
1578 prev.update_unacked = false;
1579 }
1580
1581 let Some(mut builder) =
1582 PacketBuilder::new(now, space_id, path_id, remote_cid, transmit, self)
1583 else {
1584 return PollPathSpaceStatus::NothingToSend {
1591 congestion_blocked: false,
1592 };
1593 };
1594 last_packet_number = Some(builder.packet_number);
1595
1596 if space_id == SpaceId::Initial
1597 && (self.side.is_client() || can_send.is_ack_eliciting())
1598 {
1599 pad_datagram |= PadDatagram::ToMinMtu;
1601 }
1602 if space_id == SpaceId::Data && self.config.pad_to_mtu {
1603 pad_datagram |= PadDatagram::ToSegmentSize;
1604 }
1605
1606 if scheduling_info.may_send_close && can_send.close {
1607 trace!("sending CONNECTION_CLOSE");
1608 let is_multipath_negotiated = self.is_multipath_negotiated();
1613 for path_id in self.spaces[space_id]
1614 .number_spaces
1615 .iter()
1616 .filter(|(_, pns)| !pns.pending_acks.ranges().is_empty())
1617 .map(|(&path_id, _)| path_id)
1618 .collect::<Vec<_>>()
1619 {
1620 Self::populate_acks(
1621 now,
1622 self.receiving_ecn,
1623 path_id,
1624 space_id,
1625 &mut self.spaces[space_id],
1626 is_multipath_negotiated,
1627 &mut builder,
1628 &mut self.path_stats.for_path(path_id).frame_tx,
1629 self.crypto_state.has_keys(space_id.encryption_level()),
1630 );
1631 }
1632
1633 debug_assert!(
1641 builder.frame_space_remaining() > frame::ConnectionClose::SIZE_BOUND,
1642 "ACKs should leave space for ConnectionClose"
1643 );
1644 let stats = &mut self.path_stats.for_path(path_id).frame_tx;
1645 if frame::ConnectionClose::SIZE_BOUND < builder.frame_space_remaining() {
1646 let max_frame_size = builder.frame_space_remaining();
1647 let close: Close = match self.state.as_type() {
1648 StateType::Closed => {
1649 let reason: Close =
1650 self.state.as_closed().expect("checked").clone().into();
1651 if space_id == SpaceId::Data || reason.is_transport_layer() {
1652 reason
1653 } else {
1654 TransportError::APPLICATION_ERROR("").into()
1655 }
1656 }
1657 StateType::Draining => TransportError::NO_ERROR("").into(),
1658 _ => unreachable!(
1659 "tried to make a close packet when the connection wasn't closed"
1660 ),
1661 };
1662 builder.write_frame(close.encoder(max_frame_size), stats);
1663 }
1664 let last_pn = builder.packet_number;
1665 builder.finish_and_track(now, self, path_id, pad_datagram);
1666 if space_id.kind() == self.highest_space {
1667 self.connection_close_pending = false;
1670 }
1671 return PollPathSpaceStatus::WrotePacket {
1684 last_packet_number: last_pn,
1685 pad_datagram,
1686 };
1687 }
1688
1689 self.populate_packet(now, space_id, path_id, scheduling_info, &mut builder);
1690
1691 debug_assert!(
1698 !(builder.sent_frames().is_ack_only(&self.streams)
1699 && !can_send.acks
1700 && (can_send.other || can_send.space_specific)
1701 && builder.buf.segment_size()
1702 == self.path_data(path_id).current_mtu() as usize
1703 && self.datagrams.outgoing.is_empty()),
1704 "SendableFrames was {can_send:?}, but only ACKs have been written"
1705 );
1706 if builder.sent_frames().requires_padding {
1707 pad_datagram |= PadDatagram::ToMinMtu;
1708 }
1709
1710 for (path_id, _pn) in builder.sent_frames().largest_acked.iter() {
1711 self.spaces[space_id]
1712 .for_path(*path_id)
1713 .pending_acks
1714 .acks_sent();
1715 self.timers.stop(
1716 Timer::PerPath(*path_id, PathTimer::MaxAckDelay),
1717 self.qlog.with_time(now),
1718 );
1719 }
1720
1721 if builder.can_coalesce && path_id == PathId::ZERO && {
1729 let max_packet_size = builder
1730 .buf
1731 .datagram_remaining_mut()
1732 .saturating_sub(builder.predict_packet_end());
1733 max_packet_size > MIN_PACKET_SPACE
1734 && self.has_pending_packet(space_id, max_packet_size, connection_close_pending)
1735 } {
1736 trace!("will coalesce with next packet");
1739 builder.finish_and_track(now, self, path_id, PadDatagram::No);
1740 } else {
1741 if builder.buf.num_datagrams() > 1 && matches!(pad_datagram, PadDatagram::No) {
1747 const MAX_PADDING: usize = 32;
1755 if builder.buf.datagram_remaining_mut()
1756 > builder.predict_packet_end() + MAX_PADDING
1757 {
1758 trace!(
1759 "GSO truncated by demand for {} padding bytes",
1760 builder.buf.datagram_remaining_mut() - builder.predict_packet_end()
1761 );
1762 let last_pn = builder.packet_number;
1763 builder.finish_and_track(now, self, path_id, PadDatagram::No);
1764 return PollPathSpaceStatus::Send {
1765 last_packet_number: last_pn,
1766 };
1767 }
1768
1769 builder.finish_and_track(now, self, path_id, PadDatagram::ToSegmentSize);
1772 } else {
1773 builder.finish_and_track(now, self, path_id, pad_datagram);
1774 }
1775
1776 if transmit.num_datagrams() == 1 {
1779 transmit.clip_segment_size();
1780 }
1781 }
1782 }
1783 }
1784
1785 fn poll_transmit_mtu_probe(
1786 &mut self,
1787 now: Instant,
1788 buf: &mut Vec<u8>,
1789 path_id: PathId,
1790 ) -> Option<Transmit> {
1791 let (active_cid, probe_size) = self.get_mtu_probe_data(now, path_id)?;
1792
1793 let mut transmit = TransmitBuf::new(buf, NonZeroUsize::MIN, probe_size as usize);
1795 transmit.start_new_datagram_with_size(probe_size as usize);
1796
1797 let mut builder =
1798 PacketBuilder::new(now, SpaceId::Data, path_id, active_cid, &mut transmit, self)?;
1799
1800 trace!(?probe_size, "writing MTUD probe");
1802 builder.write_frame(frame::Ping, &mut self.path_stats.for_path(path_id).frame_tx);
1803
1804 if self.peer_supports_ack_frequency() {
1806 builder.write_frame(
1807 frame::ImmediateAck,
1808 &mut self.path_stats.for_path(path_id).frame_tx,
1809 );
1810 }
1811
1812 builder.finish_and_track(now, self, path_id, PadDatagram::ToSize(probe_size));
1813
1814 self.path_stats.for_path(path_id).sent_plpmtud_probes += 1;
1815
1816 Some(self.build_transmit(path_id, transmit))
1817 }
1818
1819 fn get_mtu_probe_data(&mut self, now: Instant, path_id: PathId) -> Option<(ConnectionId, u16)> {
1827 let active_cid = self.remote_cids.get(&path_id).map(CidQueue::active)?;
1828 let is_eligible = self.path_data(path_id).validated
1829 && !self.path_data(path_id).is_validating_path()
1830 && !self.abandoned_paths.contains(&path_id);
1831
1832 if !is_eligible {
1833 return None;
1834 }
1835 let next_pn = self.spaces[SpaceId::Data]
1836 .for_path(path_id)
1837 .peek_tx_number();
1838 let probe_size = self
1839 .path_data_mut(path_id)
1840 .mtud
1841 .poll_transmit(now, next_pn)?;
1842
1843 Some((active_cid, probe_size))
1844 }
1845
1846 fn has_pending_packet(
1863 &mut self,
1864 current_space_id: SpaceId,
1865 max_packet_size: usize,
1866 connection_close_pending: bool,
1867 ) -> bool {
1868 let mut space_id = current_space_id;
1869 loop {
1870 let can_send = self.space_can_send(
1871 space_id,
1872 PathId::ZERO,
1873 max_packet_size,
1874 connection_close_pending,
1875 );
1876 if !can_send.is_empty() {
1877 return true;
1878 }
1879 match space_id.next() {
1880 Some(next_space_id) => space_id = next_space_id,
1881 None => break,
1882 }
1883 }
1884 false
1885 }
1886
1887 fn path_congestion_check(
1889 &mut self,
1890 space_id: SpaceId,
1891 path_id: PathId,
1892 transmit: &TransmitBuf<'_>,
1893 can_send: &SendableFrames,
1894 now: Instant,
1895 ) -> PathBlocked {
1896 if self.side().is_server()
1902 && self
1903 .path_data(path_id)
1904 .anti_amplification_blocked(transmit.len() as u64 + 1)
1905 {
1906 trace!(?space_id, %path_id, "blocked by anti-amplification");
1907 return PathBlocked::AntiAmplification;
1908 }
1909
1910 let bytes_to_send = transmit.segment_size() as u64;
1913 let need_loss_probe = self.spaces[space_id].for_path(path_id).loss_probes > 0;
1914
1915 if can_send.other && !need_loss_probe && !can_send.close {
1916 let path = self.path_data(path_id);
1917 if path.in_flight.bytes + bytes_to_send >= path.congestion.window() {
1918 trace!(
1919 ?space_id,
1920 %path_id,
1921 in_flight=%path.in_flight.bytes,
1922 congestion_window=%path.congestion.window(),
1923 "blocked by congestion control",
1924 );
1925 return PathBlocked::Congestion;
1926 }
1927 }
1928
1929 if let Some(delay) = self.path_data_mut(path_id).pacing_delay(bytes_to_send, now) {
1931 let resume_time = now + delay;
1932 self.timers.set(
1933 Timer::PerPath(path_id, PathTimer::Pacing),
1934 resume_time,
1935 self.qlog.with_time(now),
1936 );
1937 trace!(?space_id, %path_id, ?delay, "blocked by pacing");
1940 return PathBlocked::Pacing;
1941 }
1942
1943 PathBlocked::No
1944 }
1945
1946 fn send_prev_path_challenge(
1951 &mut self,
1952 now: Instant,
1953 buf: &mut Vec<u8>,
1954 path_id: PathId,
1955 ) -> Option<Transmit> {
1956 let (prev_cid, prev_path) = self.paths.get_mut(&path_id)?.prev.as_mut()?;
1957 if !prev_path.pending_on_path_challenge {
1958 return None;
1959 };
1960 prev_path.pending_on_path_challenge = false;
1961 let token = self.rng.random();
1962 let network_path = prev_path.network_path;
1963 prev_path.record_path_challenge_sent(now, token, network_path);
1964
1965 debug_assert_eq!(
1966 self.highest_space,
1967 SpaceKind::Data,
1968 "PATH_CHALLENGE queued without 1-RTT keys"
1969 );
1970 let buf = &mut TransmitBuf::new(buf, NonZeroUsize::MIN, MIN_INITIAL_SIZE.into());
1971 buf.start_new_datagram();
1972
1973 let mut builder = PacketBuilder::new(now, SpaceId::Data, path_id, *prev_cid, buf, self)?;
1979 let challenge = frame::PathChallenge(token);
1980 let stats = &mut self.path_stats.for_path(path_id).frame_tx;
1981 builder.write_frame_with_log_msg(challenge, stats, Some("validating previous path"));
1982
1983 builder.pad_to(MIN_INITIAL_SIZE);
1988
1989 builder.finish(self, now);
1990 self.path_stats
1991 .for_path(path_id)
1992 .udp_tx
1993 .on_sent(1, buf.len());
1994
1995 trace!(
1996 dst = ?network_path.remote,
1997 src = ?network_path.local_ip,
1998 len = buf.len(),
1999 "sending prev_path off-path challenge",
2000 );
2001 Some(Transmit {
2002 destination: network_path.remote,
2003 size: buf.len(),
2004 ecn: None,
2005 segment_size: None,
2006 src_ip: network_path.local_ip,
2007 })
2008 }
2009
2010 fn send_off_path_path_response(
2011 &mut self,
2012 now: Instant,
2013 buf: &mut Vec<u8>,
2014 path_id: PathId,
2015 ) -> Option<Transmit> {
2016 let path = self.paths.get_mut(&path_id).map(|state| &mut state.data)?;
2017 let cid_queue = self.remote_cids.get_mut(&path_id)?;
2018 let (token, network_path) = path.path_responses.pop_off_path(path.network_path)?;
2019
2020 let cid = cid_queue.active();
2022
2023 let frame = frame::PathResponse(token);
2024
2025 let buf = &mut TransmitBuf::new(buf, NonZeroUsize::MIN, MIN_INITIAL_SIZE.into());
2026 buf.start_new_datagram();
2027
2028 let mut builder = PacketBuilder::new(now, SpaceId::Data, path_id, cid, buf, self)?;
2029 let stats = &mut self.path_stats.for_path(path_id).frame_tx;
2030 builder.write_frame_with_log_msg(frame, stats, Some("(off-path)"));
2031
2032 if self
2037 .find_validated_path_on_network_path(network_path)
2038 .is_none()
2039 && self.n0_nat_traversal.client_side().is_ok()
2040 {
2041 let token = self.rng.random();
2042 let stats = &mut self.path_stats.for_path(path_id).frame_tx;
2043 builder.write_frame(frame::PathChallenge(token), stats);
2044 let ip_port = (network_path.remote.ip(), network_path.remote.port());
2045 self.n0_nat_traversal.mark_probe_sent(ip_port, token);
2046 }
2047
2048 builder.pad_to(MIN_INITIAL_SIZE);
2051 builder.finish(self, now);
2052
2053 let size = buf.len();
2054 self.path_stats.for_path(path_id).udp_tx.on_sent(1, size);
2055
2056 trace!(
2057 dst = ?network_path.remote,
2058 src = ?network_path.local_ip,
2059 len = buf.len(),
2060 "sending off-path PATH_RESPONSE",
2061 );
2062 Some(Transmit {
2063 destination: network_path.remote,
2064 size,
2065 ecn: None,
2066 segment_size: None,
2067 src_ip: network_path.local_ip,
2068 })
2069 }
2070
2071 fn send_nat_traversal_path_challenge(
2073 &mut self,
2074 now: Instant,
2075 buf: &mut Vec<u8>,
2076 path_id: PathId,
2077 ) -> Option<Transmit> {
2078 let remote = self.n0_nat_traversal.next_probe_addr()?;
2079
2080 if !self.paths.get(&path_id)?.data.validated {
2081 return None;
2083 }
2084
2085 let Some(cid) = self
2090 .remote_cids
2091 .get(&path_id)
2092 .map(|cid_queue| cid_queue.active())
2093 else {
2094 trace!(%path_id, "Not sending NAT traversal probe for path with no CIDs");
2095 return None;
2096 };
2097 let token = self.rng.random();
2098
2099 let frame = frame::PathChallenge(token);
2100
2101 let mut buf = TransmitBuf::new(buf, NonZeroUsize::MIN, MIN_INITIAL_SIZE.into());
2102 buf.start_new_datagram();
2103
2104 let mut builder = PacketBuilder::new(now, SpaceId::Data, path_id, cid, &mut buf, self)?;
2105 let stats = &mut self.path_stats.for_path(path_id).frame_tx;
2106 builder.write_frame_with_log_msg(frame, stats, Some("(nat-traversal)"));
2107 builder.finish(self, now);
2110
2111 self.n0_nat_traversal.mark_probe_sent(remote, token);
2113
2114 let size = buf.len();
2115 self.path_stats.for_path(path_id).udp_tx.on_sent(1, size);
2116
2117 trace!(dst = ?remote, len = buf.len(), "sending off-path NAT probe");
2118 Some(Transmit {
2119 destination: remote.into(),
2120 size,
2121 ecn: None,
2122 segment_size: None,
2123 src_ip: None,
2124 })
2125 }
2126
2127 fn space_can_send(
2135 &mut self,
2136 space_id: SpaceId,
2137 path_id: PathId,
2138 packet_size: usize,
2139 connection_close_pending: bool,
2140 ) -> SendableFrames {
2141 let space = &mut self.spaces[space_id];
2142 let space_has_crypto = self.crypto_state.has_keys(space_id.encryption_level());
2143
2144 if !space_has_crypto
2145 && (space_id != SpaceId::Data
2146 || !self.crypto_state.has_keys(EncryptionLevel::ZeroRtt)
2147 || self.side.is_server())
2148 {
2149 return SendableFrames::empty();
2151 }
2152
2153 let mut can_send = space.can_send(path_id, &self.streams);
2154
2155 if space_id == SpaceId::Data {
2157 let pn = space.for_path(path_id).peek_tx_number();
2158 let frame_space_1rtt =
2164 packet_size.saturating_sub(self.predict_1rtt_overhead(pn, path_id));
2165 can_send |= self.can_send_1rtt(path_id, frame_space_1rtt);
2166 }
2167
2168 can_send.close = connection_close_pending && space_has_crypto;
2169
2170 can_send
2171 }
2172
2173 pub fn handle_event(&mut self, event: ConnectionEvent) {
2179 use ConnectionEventInner::*;
2180 match event.0 {
2181 Datagram(DatagramConnectionEvent {
2182 now,
2183 network_path,
2184 path_id,
2185 ecn,
2186 first_decode,
2187 remaining,
2188 }) => {
2189 let span = trace_span!("pkt", %path_id);
2190 let _guard = span.enter();
2191
2192 if self.early_discard_packet(network_path, path_id) {
2193 return;
2195 }
2196
2197 let was_anti_amplification_blocked = self
2198 .path(path_id)
2199 .map(|path| path.anti_amplification_blocked(1))
2200 .unwrap_or(false);
2203
2204 let rx = &mut self.path_stats.for_path(path_id).udp_rx;
2205 rx.datagrams += 1;
2206 rx.bytes += first_decode.len() as u64;
2207 let data_len = first_decode.len();
2208
2209 self.handle_decode(now, network_path, path_id, ecn, first_decode);
2210 if let Some(path) = self.path_mut(path_id) {
2215 path.inc_total_recvd(data_len as u64);
2216 }
2217
2218 if let Some(data) = remaining {
2219 self.path_stats.for_path(path_id).udp_rx.bytes += data.len() as u64;
2220 self.handle_coalesced(now, network_path, path_id, ecn, data);
2221 }
2222
2223 if let Some(path) = self.paths.get_mut(&path_id) {
2224 self.qlog
2225 .emit_recovery_metrics(path_id, &mut path.data, now);
2226 }
2227
2228 if was_anti_amplification_blocked {
2229 self.set_loss_detection_timer(now, path_id);
2233 }
2234 }
2235 NewIdentifiers(ids, now, cid_len, cid_lifetime) => {
2236 let path_id = ids.first().map(|issued| issued.path_id).unwrap_or_default();
2237 debug_assert!(ids.iter().all(|issued| issued.path_id == path_id));
2238
2239 if self.abandoned_paths.contains(&path_id) {
2242 if !self.state.is_drained() {
2243 for issued in &ids {
2244 self.endpoint_events
2245 .push_back(EndpointEventInner::RetireConnectionId(
2246 now,
2247 path_id,
2248 issued.sequence,
2249 false,
2250 ));
2251 }
2252 }
2253 return;
2254 }
2255
2256 let cid_state = self
2257 .local_cid_state
2258 .entry(path_id)
2259 .or_insert_with(|| CidState::new(cid_len, cid_lifetime, now, 0));
2260 cid_state.new_cids(&ids, now);
2261
2262 ids.into_iter().rev().for_each(|frame| {
2263 self.spaces[SpaceId::Data].pending.new_cids.push(frame);
2264 });
2265 self.reset_cid_retirement(now);
2267 }
2268 }
2269 }
2270
2271 fn early_discard_packet(&mut self, network_path: FourTuple, path_id: PathId) -> bool {
2279 if self.is_handshaking() && path_id != PathId::ZERO {
2280 debug!(%network_path, %path_id, "discarding multipath packet during handshake");
2281 return true;
2282 }
2283
2284 let peer_may_probe = self.peer_may_probe();
2289
2290 let local_ip_may_migrate = self.local_ip_may_migrate();
2291
2292 if let Some(known_path) = self.path_mut(path_id) {
2296 if network_path.remote != known_path.network_path.remote && !peer_may_probe {
2297 trace!(
2298 %path_id,
2299 %network_path,
2300 %known_path.network_path,
2301 "discarding packet from unrecognized peer"
2302 );
2303 return true;
2304 }
2305
2306 if known_path.network_path.local_ip.is_some()
2307 && network_path.local_ip.is_some()
2308 && known_path.network_path.local_ip != network_path.local_ip
2309 && !local_ip_may_migrate
2310 {
2311 trace!(
2312 %path_id,
2313 %network_path,
2314 %known_path.network_path,
2315 "discarding packet sent to incorrect interface"
2316 );
2317 return true;
2318 }
2319 }
2320 false
2321 }
2322
2323 fn peer_may_probe(&self) -> bool {
2334 match &self.side {
2335 ConnectionSide::Client { .. } => {
2336 if let Some(hs) = self.state.as_handshake() {
2337 hs.allow_server_migration
2338 } else {
2339 self.n0_nat_traversal.is_negotiated() && self.is_handshake_confirmed()
2340 }
2341 }
2342 ConnectionSide::Server { server_config } => {
2343 self.is_handshake_confirmed()
2344 && (server_config.migration || self.n0_nat_traversal.is_negotiated())
2345 }
2346 }
2347 }
2348
2349 fn remote_may_migrate(&self) -> bool {
2363 match &self.side {
2364 ConnectionSide::Server { server_config } => {
2365 server_config.migration && self.is_handshake_confirmed()
2366 }
2367 ConnectionSide::Client { .. } => {
2368 if let Some(hs) = self.state.as_handshake() {
2369 hs.allow_server_migration
2370 } else {
2371 self.n0_nat_traversal.is_negotiated() && self.is_handshake_confirmed()
2372 }
2373 }
2374 }
2375 }
2376
2377 fn local_ip_may_migrate(&self) -> bool {
2390 (self.side.is_client() || self.n0_nat_traversal.is_negotiated())
2391 && self.is_handshake_confirmed()
2392 }
2393 pub fn handle_timeout(&mut self, now: Instant) {
2403 while let Some((timer, _time)) = self.timers.expire_before(now, &self.qlog) {
2404 let span = match timer {
2405 Timer::Conn(timer) => trace_span!("timeout", scope = "conn", ?timer),
2406 Timer::PerPath(path_id, timer) => {
2407 trace_span!("timer_fired", scope="path", %path_id, ?timer)
2408 }
2409 };
2410 let _guard = span.enter();
2411 trace!("timeout");
2412 match timer {
2413 Timer::Conn(timer) => match timer {
2414 ConnTimer::Close => {
2415 self.state.move_to_drained(None);
2416 self.endpoint_events.push_back(EndpointEventInner::Drained);
2419 }
2420 ConnTimer::Idle => {
2421 self.kill(ConnectionError::TimedOut);
2422 }
2423 ConnTimer::KeepAlive => {
2424 self.ping();
2425 }
2426 ConnTimer::KeyDiscard => {
2427 self.crypto_state.discard_temporary_keys();
2428 }
2429 ConnTimer::PushNewCid => {
2430 while let Some((path_id, when)) = self.next_cid_retirement() {
2431 if when > now {
2432 break;
2433 }
2434 match self.local_cid_state.get_mut(&path_id) {
2435 None => error!(%path_id, "No local CID state for path"),
2436 Some(cid_state) => {
2437 let num_new_cid = cid_state.on_cid_timeout().into();
2439 if !self.state.is_closed() {
2440 trace!(
2441 "push a new CID to peer RETIRE_PRIOR_TO field {}",
2442 cid_state.retire_prior_to()
2443 );
2444 self.endpoint_events.push_back(
2445 EndpointEventInner::NeedIdentifiers(
2446 path_id,
2447 now,
2448 num_new_cid,
2449 ),
2450 );
2451 }
2452 }
2453 }
2454 }
2455 }
2456 ConnTimer::NoAvailablePath => {
2457 if self.state.is_closed() || self.state.is_drained() {
2462 error!("no viable path timer fired, but connection already closing");
2465 } else {
2466 trace!("no viable path grace period expired, closing connection");
2467 let err = TransportError::NO_VIABLE_PATH(
2468 "last path abandoned, no new path opened",
2469 );
2470 self.close_common();
2471 self.set_close_timer(now);
2472 self.connection_close_pending = true;
2473 self.state.move_to_closed(err);
2474 }
2475 }
2476 ConnTimer::NatTraversalProbeRetry => {
2477 self.n0_nat_traversal.queue_retries(self.is_ipv6());
2478 if let Some(delay) =
2479 self.n0_nat_traversal.retry_delay(self.config.initial_rtt)
2480 {
2481 self.timers.set(
2482 Timer::Conn(ConnTimer::NatTraversalProbeRetry),
2483 now + delay,
2484 self.qlog.with_time(now),
2485 );
2486 trace!("re-queued NAT probes");
2487 } else {
2488 trace!("no more NAT probes remaining");
2489 }
2490 }
2491 },
2492 Timer::PerPath(path_id, timer) => {
2493 match timer {
2494 PathTimer::PathIdle => {
2495 if let Err(err) =
2496 self.close_path_inner(now, path_id, PathAbandonReason::TimedOut)
2497 {
2498 warn!(?err, "failed closing path");
2499 }
2500 }
2501
2502 PathTimer::PathKeepAlive => {
2503 self.ping_path(path_id).ok();
2504 }
2505 PathTimer::LossDetection => {
2506 self.on_loss_detection_timeout(now, path_id);
2507 self.qlog.emit_recovery_metrics(
2508 path_id,
2509 &mut self
2510 .paths
2511 .get_mut(&path_id)
2512 .expect("loss-detection timer fires only on live paths")
2513 .data,
2514 now,
2515 );
2516 }
2517 PathTimer::PathValidationFailed => {
2518 let Some(path) = self.paths.get_mut(&path_id) else {
2519 continue;
2520 };
2521 self.timers.stop(
2522 Timer::PerPath(path_id, PathTimer::PathChallengeLost),
2523 self.qlog.with_time(now),
2524 );
2525 debug!("path migration validation failed");
2526 if let Some((_, prev)) = path.prev.take() {
2527 path.data = prev;
2528 }
2529 path.data.reset_on_path_challenges();
2530 }
2531 PathTimer::PathChallengeLost => {
2532 let Some(path) = self.paths.get_mut(&path_id) else {
2533 continue;
2534 };
2535 trace!("path challenge deemed lost");
2536 path.data.pending_on_path_challenge = true;
2537 }
2538 PathTimer::AbandonFromValidation => {
2539 let Some(path) = self.paths.get_mut(&path_id) else {
2540 continue;
2541 };
2542 path.data.reset_on_path_challenges();
2543 self.timers.stop(
2544 Timer::PerPath(path_id, PathTimer::PathChallengeLost),
2545 self.qlog.with_time(now),
2546 );
2547 debug!("new path validation failed");
2548 if let Err(err) = self.close_path_inner(
2549 now,
2550 path_id,
2551 PathAbandonReason::ValidationFailed,
2552 ) {
2553 warn!(?err, "failed closing path");
2554 }
2555 }
2556 PathTimer::Pacing => {}
2557 PathTimer::MaxAckDelay => {
2558 self.spaces[SpaceId::Data]
2560 .for_path(path_id)
2561 .pending_acks
2562 .on_max_ack_delay_timeout()
2563 }
2564 PathTimer::PathDrained => {
2565 self.timers.stop_per_path(path_id, self.qlog.with_time(now));
2568 if let Some(local_cid_state) = self.local_cid_state.remove(&path_id) {
2569 debug_assert!(!self.state.is_drained()); let (min_seq, max_seq) = local_cid_state.active_seq();
2571 for seq in min_seq..=max_seq {
2572 self.endpoint_events.push_back(
2573 EndpointEventInner::RetireConnectionId(
2574 now, path_id, seq, false,
2575 ),
2576 );
2577 }
2578 }
2579 self.discard_path(path_id, now);
2580 }
2581 }
2582 }
2583 }
2584 }
2585 }
2586
2587 pub fn close(&mut self, now: Instant, error_code: VarInt, reason: Bytes) {
2599 self.close_inner(
2600 now,
2601 Close::Application(frame::ApplicationClose { error_code, reason }),
2602 )
2603 }
2604
2605 fn close_inner(&mut self, now: Instant, reason: Close) {
2621 let was_closed = self.state.is_closed();
2622 if !was_closed {
2623 self.close_common();
2624 self.set_close_timer(now);
2625 self.connection_close_pending = true;
2626 self.state.move_to_closed_local(reason);
2627 }
2628 }
2629
2630 pub fn datagrams(&mut self) -> Datagrams<'_> {
2632 Datagrams { conn: self }
2633 }
2634
2635 pub fn stats(&mut self) -> ConnectionStats {
2637 let mut stats = self.partial_stats.clone();
2638
2639 for path_stats in self.path_stats.iter_stats() {
2640 stats += *path_stats;
2645 }
2646
2647 stats
2648 }
2649
2650 pub fn path_stats(&mut self, path_id: PathId) -> Option<PathStats> {
2652 let path = self.paths.get(&path_id)?;
2653 let stats = self.path_stats.for_path(path_id);
2654 stats.rtt = path.data.rtt.get();
2655 stats.cwnd = path.data.congestion.window();
2656 stats.current_mtu = path.data.mtud.current_mtu();
2657 Some(*stats)
2658 }
2659
2660 pub fn ping(&mut self) {
2664 for path_data in self.spaces[self.highest_space].number_spaces.values_mut() {
2667 path_data.ping_pending = true;
2668 }
2669 }
2670
2671 pub fn ping_path(&mut self, path: PathId) -> Result<(), ClosedPath> {
2675 let path_data = self.spaces[self.highest_space]
2676 .number_spaces
2677 .get_mut(&path)
2678 .ok_or(ClosedPath { _private: () })?;
2679 path_data.ping_pending = true;
2680 Ok(())
2681 }
2682
2683 pub fn force_key_update(&mut self) {
2687 if !self.state.is_established() {
2688 debug!("ignoring forced key update in illegal state");
2689 return;
2690 }
2691 if self.crypto_state.prev_crypto.is_some() {
2692 debug!("ignoring redundant forced key update");
2695 return;
2696 }
2697 self.crypto_state.update_keys(None, false);
2698 }
2699
2700 pub fn crypto_session(&self) -> &dyn crypto::Session {
2702 self.crypto_state.session.as_ref()
2703 }
2704
2705 pub fn is_handshaking(&self) -> bool {
2715 self.state.is_handshake()
2716 }
2717
2718 pub fn is_closed(&self) -> bool {
2729 self.state.is_closed()
2730 }
2731
2732 pub fn is_drained(&self) -> bool {
2737 self.state.is_drained()
2738 }
2739
2740 pub fn accepted_0rtt(&self) -> bool {
2744 self.crypto_state.accepted_0rtt
2745 }
2746
2747 pub fn has_0rtt(&self) -> bool {
2749 self.crypto_state.zero_rtt_enabled
2750 }
2751
2752 pub fn has_pending_retransmits(&self) -> bool {
2754 !self.spaces[SpaceId::Data].pending.is_empty(&self.streams)
2755 }
2756
2757 pub fn side(&self) -> Side {
2759 self.side.side()
2760 }
2761
2762 pub fn path_observed_address(&self, path_id: PathId) -> Result<Option<SocketAddr>, ClosedPath> {
2764 self.path(path_id)
2765 .map(|path_data| {
2766 path_data
2767 .last_observed_addr_report
2768 .as_ref()
2769 .map(|observed| observed.socket_addr())
2770 })
2771 .ok_or(ClosedPath { _private: () })
2772 }
2773
2774 pub fn rtt(&self, path_id: PathId) -> Option<Duration> {
2776 self.path(path_id).map(|d| d.rtt.get())
2777 }
2778
2779 pub fn congestion_state(&self, path_id: PathId) -> Option<&dyn Controller> {
2781 self.path(path_id).map(|d| d.congestion.as_ref())
2782 }
2783
2784 pub fn set_max_concurrent_streams(&mut self, dir: Dir, count: VarInt) {
2789 self.streams.set_max_concurrent(dir, count);
2790 let pending = &mut self.spaces[SpaceId::Data].pending;
2793 self.streams.queue_max_stream_id(pending);
2794 }
2795
2796 pub fn set_max_concurrent_paths(
2806 &mut self,
2807 now: Instant,
2808 count: NonZeroU32,
2809 ) -> Result<(), MultipathNotNegotiated> {
2810 if !self.is_multipath_negotiated() {
2811 return Err(MultipathNotNegotiated { _private: () });
2812 }
2813 self.max_concurrent_paths = count;
2814
2815 let in_use_count = self
2816 .local_max_path_id
2817 .next()
2818 .saturating_sub(self.abandoned_paths.len() as u32)
2819 .as_u32();
2820 let extra_needed = count.get().saturating_sub(in_use_count);
2821 let new_max_path_id = self.local_max_path_id.saturating_add(extra_needed);
2822
2823 self.set_max_path_id(now, new_max_path_id);
2824
2825 Ok(())
2826 }
2827
2828 fn set_max_path_id(&mut self, now: Instant, max_path_id: PathId) {
2830 if max_path_id <= self.local_max_path_id {
2831 return;
2832 }
2833
2834 self.local_max_path_id = max_path_id;
2835 self.spaces[SpaceId::Data].pending.max_path_id = true;
2836
2837 self.issue_first_path_cids(now);
2838 }
2839
2840 pub fn max_concurrent_streams(&self, dir: Dir) -> u64 {
2846 self.streams.max_concurrent(dir)
2847 }
2848
2849 pub fn set_send_window(&mut self, send_window: u64) {
2851 self.streams.set_send_window(send_window);
2852 }
2853
2854 pub fn set_receive_window(&mut self, receive_window: VarInt) {
2856 if self.streams.set_receive_window(receive_window) {
2857 self.spaces[SpaceId::Data].pending.max_data = true;
2858 }
2859 }
2860
2861 pub fn is_multipath_negotiated(&self) -> bool {
2866 !self.is_handshaking()
2867 && self.config.max_concurrent_multipath_paths.is_some()
2868 && self.peer_params.initial_max_path_id.is_some()
2869 }
2870
2871 fn on_ack_received(
2872 &mut self,
2873 now: Instant,
2874 space: SpaceId,
2875 ack: frame::Ack,
2876 ) -> Result<(), TransportError> {
2877 let path = PathId::ZERO;
2879 self.inner_on_ack_received(now, space, path, ack)
2880 }
2881
2882 fn on_path_ack_received(
2883 &mut self,
2884 now: Instant,
2885 space: SpaceId,
2886 path_ack: frame::PathAck,
2887 ) -> Result<(), TransportError> {
2888 let (ack, path) = path_ack.into_ack();
2889 self.inner_on_ack_received(now, space, path, ack)
2890 }
2891
2892 fn inner_on_ack_received(
2894 &mut self,
2895 now: Instant,
2896 space: SpaceId,
2897 path: PathId,
2898 ack: frame::Ack,
2899 ) -> Result<(), TransportError> {
2900 if !self.spaces[space].number_spaces.contains_key(&path) {
2901 if self.abandoned_paths.contains(&path) {
2902 trace!("silently ignoring PATH_ACK on discarded path");
2908 return Ok(());
2909 } else {
2910 return Err(TransportError::PROTOCOL_VIOLATION(
2911 "received PATH_ACK with path ID never used",
2912 ));
2913 }
2914 }
2915 if ack.largest >= self.spaces[space].for_path(path).next_packet_number {
2916 return Err(TransportError::PROTOCOL_VIOLATION("unsent packet acked"));
2917 }
2918 let new_largest_pn = {
2920 let space = &mut self.spaces[space].for_path(path);
2921 if space
2922 .largest_acked_packet_pn
2923 .is_none_or(|pn| ack.largest > pn)
2924 {
2925 space.largest_acked_packet_pn = Some(ack.largest);
2926 if let Some(info) = space.sent_packets.get(ack.largest) {
2927 space.largest_acked_packet_send_time = info.time_sent;
2931 }
2932 Some(ack.largest)
2933 } else {
2934 None
2935 }
2936 };
2937
2938 if self.detect_spurious_loss(&ack, space, path) {
2939 self.path_stats.for_path(path).spurious_congestion_events += 1;
2940 self.path_data_mut(path)
2941 .congestion
2942 .on_spurious_congestion_event();
2943 }
2944
2945 let mut newly_acked = ArrayRangeSet::new();
2947 for range in ack.iter() {
2948 self.spaces[space].for_path(path).check_ack(range.clone())?;
2949 for (pn, _) in self.spaces[space]
2950 .for_path(path)
2951 .sent_packets
2952 .iter_range(range)
2953 {
2954 newly_acked.insert_one(pn);
2955 }
2956 }
2957
2958 if newly_acked.is_empty() {
2959 return Ok(());
2960 }
2961
2962 let mut ack_eliciting_acked = false;
2963 for packet in newly_acked.elts() {
2964 if let Some(info) = self.spaces[space].for_path(path).take(packet) {
2965 for (acked_path_id, acked_pn) in info.largest_acked.iter() {
2966 if let Some(pns) = self.spaces[space].path_space_mut(*acked_path_id) {
2972 pns.pending_acks.subtract_below(*acked_pn);
2973 }
2974 }
2975 ack_eliciting_acked |= info.ack_eliciting;
2976
2977 let path_data = self.path_data_mut(path);
2979 let mtu_updated = path_data.mtud.on_acked(space.kind(), packet, info.size);
2980 if mtu_updated {
2981 path_data
2982 .congestion
2983 .on_mtu_update(path_data.mtud.current_mtu());
2984 }
2985
2986 self.ack_frequency.on_acked(path, packet);
2988
2989 self.on_packet_acked(now, path, packet, info);
2990 }
2991 }
2992
2993 let largest_ackd = self.spaces[space].for_path(path).largest_acked_packet_pn;
2994 let path_data = self.path_data_mut(path);
2995 let app_limited = path_data.app_limited;
2996 let in_flight = path_data.in_flight.bytes;
2997
2998 path_data
2999 .congestion
3000 .on_end_acks(now, in_flight, app_limited, largest_ackd);
3001
3002 if new_largest_pn.is_some() && ack_eliciting_acked {
3003 let ack_delay = if space != SpaceId::Data {
3004 Duration::from_micros(0)
3005 } else {
3006 cmp::min(
3007 self.ack_frequency.peer_max_ack_delay,
3008 Duration::from_micros(ack.delay << self.peer_params.ack_delay_exponent.0),
3009 )
3010 };
3011 let rtt = now.saturating_duration_since(
3012 self.spaces[space]
3013 .for_path(path)
3014 .largest_acked_packet_send_time,
3015 );
3016
3017 let next_pn = self.spaces[space].for_path(path).next_packet_number;
3018 let path_data = self.path_data_mut(path);
3019 path_data.rtt.update(ack_delay, rtt);
3021 if path_data.first_packet_after_rtt_sample.is_none() {
3022 path_data.first_packet_after_rtt_sample = Some((space.kind(), next_pn));
3023 }
3024 }
3025
3026 self.detect_lost_packets(now, space, path, true);
3028
3029 if self.peer_completed_handshake_address_validation() {
3034 self.path_data_mut(path).pto_count = 0;
3035 }
3036
3037 if self.path_data(path).sending_ecn {
3042 if let Some(ecn) = ack.ecn {
3043 if let Some(largest_sent_pn) = new_largest_pn {
3048 let sent = self.spaces[space]
3049 .for_path(path)
3050 .largest_acked_packet_send_time;
3051 self.process_ecn(
3052 now,
3053 space,
3054 path,
3055 newly_acked.len() as u64,
3056 ecn,
3057 sent,
3058 largest_sent_pn,
3059 );
3060 }
3061 } else {
3062 debug!("ECN not acknowledged by peer");
3064 self.path_data_mut(path).sending_ecn = false;
3065 }
3066 }
3067
3068 self.set_loss_detection_timer(now, path);
3069 Ok(())
3070 }
3071
3072 fn detect_spurious_loss(&mut self, ack: &frame::Ack, space: SpaceId, path: PathId) -> bool {
3073 let lost_packets = &mut self.spaces[space].for_path(path).lost_packets;
3074
3075 if lost_packets.is_empty() {
3076 return false;
3077 }
3078
3079 for range in ack.iter() {
3080 let spurious_losses: Vec<u64> = lost_packets
3081 .iter_range(range.clone())
3082 .map(|(pn, _info)| pn)
3083 .collect();
3084
3085 for pn in spurious_losses {
3086 lost_packets.remove(pn);
3087 }
3088 }
3089
3090 lost_packets.is_empty()
3095 }
3096
3097 fn drain_lost_packets(&mut self, now: Instant, space: SpaceId, path: PathId) {
3102 let two_pto = 2 * self.path_data(path).rtt.pto_base();
3103
3104 let lost_packets = &mut self.spaces[space].for_path(path).lost_packets;
3105 lost_packets.retain(|_pn, info| now.saturating_duration_since(info.time_sent) <= two_pto);
3106 }
3107
3108 fn process_ecn(
3110 &mut self,
3111 now: Instant,
3112 space: SpaceId,
3113 path: PathId,
3114 newly_acked_pn: u64,
3115 ecn: frame::EcnCounts,
3116 largest_sent_time: Instant,
3117 largest_sent_pn: u64,
3118 ) {
3119 match self.spaces[space]
3120 .for_path(path)
3121 .detect_ecn(newly_acked_pn, ecn)
3122 {
3123 Err(e) => {
3124 debug!("halting ECN due to verification failure: {}", e);
3125
3126 self.path_data_mut(path).sending_ecn = false;
3127 self.spaces[space].for_path(path).ecn_feedback = frame::EcnCounts::ZERO;
3130 }
3131 Ok(false) => {}
3132 Ok(true) => {
3133 self.path_stats.for_path(path).congestion_events += 1;
3134 self.path_data_mut(path).congestion.on_congestion_event(
3135 now,
3136 largest_sent_time,
3137 false,
3138 true,
3139 0,
3140 largest_sent_pn,
3141 );
3142 }
3143 }
3144 }
3145
3146 fn on_packet_acked(&mut self, now: Instant, path_id: PathId, pn: u64, info: SentPacket) {
3149 let path = self.path_data_mut(path_id);
3150 let app_limited = path.app_limited;
3151 path.remove_in_flight(&info);
3152 if info.ack_eliciting && info.path_generation == path.generation() {
3153 let rtt = path.rtt;
3157 path.congestion
3158 .on_ack(now, info.time_sent, info.size.into(), pn, app_limited, &rtt);
3159 }
3160
3161 if let Some(retransmits) = info.retransmits.get() {
3163 for (id, _) in retransmits.reset_stream.iter() {
3164 self.streams.reset_acked(*id);
3165 }
3166 }
3167
3168 for frame in info.stream_frames {
3169 self.streams.received_ack_of(frame);
3170 }
3171 }
3172
3173 fn set_key_discard_timer(&mut self, now: Instant, space: SpaceKind) {
3174 let start = if self.crypto_state.has_keys(EncryptionLevel::ZeroRtt) {
3175 now
3176 } else {
3177 self.crypto_state
3178 .prev_crypto
3179 .as_ref()
3180 .expect("no previous keys")
3181 .end_packet
3182 .as_ref()
3183 .expect("update not acknowledged yet")
3184 .1
3185 };
3186
3187 self.timers.set(
3189 Timer::Conn(ConnTimer::KeyDiscard),
3190 start + self.max_pto_for_space(space) * 3,
3191 self.qlog.with_time(now),
3192 );
3193 }
3194
3195 fn on_loss_detection_timeout(&mut self, now: Instant, path_id: PathId) {
3208 if let Some((_, pn_space)) = self.loss_time_and_space(path_id) {
3209 self.detect_lost_packets(now, pn_space, path_id, false);
3211 self.set_loss_detection_timer(now, path_id);
3212 return;
3213 }
3214
3215 let Some((_, space)) = self.pto_time_and_space(now, path_id) else {
3216 error!(%path_id, "PTO expired while unset");
3217 return;
3218 };
3219 trace!(
3220 in_flight = self.path_data(path_id).in_flight.bytes,
3221 count = self.path_data(path_id).pto_count,
3222 ?space,
3223 %path_id,
3224 "PTO fired"
3225 );
3226
3227 let count = match self.path_data(path_id).in_flight.ack_eliciting {
3228 0 => {
3231 debug_assert!(!self.peer_completed_handshake_address_validation());
3232 1
3233 }
3234 _ => 2,
3236 };
3237 let pns = self.spaces[space].for_path(path_id);
3238 pns.loss_probes = pns.loss_probes.saturating_add(count);
3239 let path_data = self.path_data_mut(path_id);
3240 path_data.pto_count = path_data.pto_count.saturating_add(1);
3241 self.set_loss_detection_timer(now, path_id);
3242 }
3243
3244 fn detect_lost_packets(
3261 &mut self,
3262 now: Instant,
3263 pn_space: SpaceId,
3264 path_id: PathId,
3265 due_to_ack: bool,
3266 ) {
3267 let mut lost_packets = Vec::<u64>::new();
3268 let mut lost_mtu_probe = None;
3269 let mut in_persistent_congestion = false;
3270 let mut size_of_lost_packets = 0u64;
3271 self.spaces[pn_space].for_path(path_id).loss_time = None;
3272
3273 let path = self.path_data(path_id);
3276 let in_flight_mtu_probe = path.mtud.in_flight_mtu_probe();
3277 let loss_delay = path
3278 .rtt
3279 .conservative()
3280 .mul_f32(self.config.time_threshold)
3281 .max(TIMER_GRANULARITY);
3282 let first_packet_after_rtt_sample = path.first_packet_after_rtt_sample;
3283
3284 let largest_acked_packet_pn = self.spaces[pn_space]
3285 .for_path(path_id)
3286 .largest_acked_packet_pn
3287 .expect("detect_lost_packets only to be called if path received at least one ACK");
3288 let packet_threshold = self.config.packet_threshold as u64;
3289
3290 let congestion_period = self
3294 .pto(SpaceKind::Data, path_id)
3295 .saturating_mul(self.config.persistent_congestion_threshold);
3296 let mut persistent_congestion_start: Option<Instant> = None;
3297 let mut prev_packet = None;
3298 let space = self.spaces[pn_space].for_path(path_id);
3299
3300 for (packet, info) in space.sent_packets.iter_range(0..largest_acked_packet_pn) {
3301 if prev_packet != Some(packet.wrapping_sub(1)) {
3302 persistent_congestion_start = None;
3304 }
3305
3306 let packet_too_old = now.saturating_duration_since(info.time_sent) >= loss_delay;
3310 if packet_too_old || largest_acked_packet_pn >= packet + packet_threshold {
3311 if Some(packet) == in_flight_mtu_probe {
3313 lost_mtu_probe = in_flight_mtu_probe;
3316 } else {
3317 lost_packets.push(packet);
3318 size_of_lost_packets += info.size as u64;
3319 if info.ack_eliciting && due_to_ack {
3320 match persistent_congestion_start {
3321 Some(start) if info.time_sent - start > congestion_period => {
3324 in_persistent_congestion = true;
3325 }
3326 None if first_packet_after_rtt_sample
3328 .is_some_and(|x| x < (pn_space.kind(), packet)) =>
3329 {
3330 persistent_congestion_start = Some(info.time_sent);
3331 }
3332 _ => {}
3333 }
3334 }
3335 }
3336 } else {
3337 if space.loss_time.is_none() {
3339 space.loss_time = Some(info.time_sent + loss_delay);
3342 }
3343 persistent_congestion_start = None;
3344 }
3345
3346 prev_packet = Some(packet);
3347 }
3348
3349 self.handle_lost_packets(
3350 pn_space,
3351 path_id,
3352 now,
3353 lost_packets,
3354 lost_mtu_probe,
3355 loss_delay,
3356 in_persistent_congestion,
3357 size_of_lost_packets,
3358 );
3359 }
3360
3361 fn discard_path(&mut self, path_id: PathId, now: Instant) {
3363 trace!(%path_id, "dropping path state");
3364 let path = self.path_data(path_id);
3365 let in_flight_mtu_probe = path.mtud.in_flight_mtu_probe();
3366
3367 let mut size_of_lost_packets = 0u64; let lost_pns: Vec<_> = self.spaces[SpaceId::Data]
3369 .for_path(path_id)
3370 .sent_packets
3371 .iter()
3372 .filter(|(pn, _info)| Some(*pn) != in_flight_mtu_probe)
3373 .map(|(pn, info)| {
3374 size_of_lost_packets += info.size as u64;
3375 pn
3376 })
3377 .collect();
3378
3379 if !lost_pns.is_empty() {
3380 trace!(
3381 %path_id,
3382 count = lost_pns.len(),
3383 lost_bytes = size_of_lost_packets,
3384 "packets lost on path abandon"
3385 );
3386 self.handle_lost_packets(
3387 SpaceId::Data,
3388 path_id,
3389 now,
3390 lost_pns,
3391 in_flight_mtu_probe,
3392 Duration::ZERO,
3393 false,
3394 size_of_lost_packets,
3395 );
3396 }
3397 let path_stats = self.path_stats.discard(&path_id);
3400 self.partial_stats += path_stats;
3401 self.paths.remove(&path_id);
3402 self.spaces[SpaceId::Data].number_spaces.remove(&path_id);
3403
3404 self.events.push_back(
3405 PathEvent::Discarded {
3406 id: path_id,
3407 path_stats: Box::new(path_stats),
3408 }
3409 .into(),
3410 );
3411 }
3412
3413 fn handle_lost_packets(
3414 &mut self,
3415 pn_space: SpaceId,
3416 path_id: PathId,
3417 now: Instant,
3418 lost_packets: Vec<u64>,
3419 lost_mtu_probe: Option<u64>,
3420 loss_delay: Duration,
3421 in_persistent_congestion: bool,
3422 size_of_lost_packets: u64,
3423 ) {
3424 debug_assert!(lost_packets.is_sorted(), "lost_packets must be sorted");
3425
3426 self.drain_lost_packets(now, pn_space, path_id);
3427
3428 if let Some(largest_lost) = lost_packets.last().cloned() {
3430 let old_bytes_in_flight = self.path_data_mut(path_id).in_flight.bytes;
3431 let largest_lost_sent = self.spaces[pn_space]
3432 .for_path(path_id)
3433 .sent_packets
3434 .get(largest_lost)
3435 .unwrap()
3436 .time_sent;
3437 let path_stats = self.path_stats.for_path(path_id);
3438 path_stats.lost_packets += lost_packets.len() as u64;
3439 path_stats.lost_bytes += size_of_lost_packets;
3440 trace!(
3441 %path_id,
3442 count = lost_packets.len(),
3443 lost_bytes = size_of_lost_packets,
3444 "packets lost",
3445 );
3446
3447 for &packet in &lost_packets {
3448 let Some(info) = self.spaces[pn_space].for_path(path_id).take(packet) else {
3449 continue;
3450 };
3451 self.qlog
3452 .emit_packet_lost(packet, &info, loss_delay, pn_space.kind(), now);
3453 self.paths
3454 .get_mut(&path_id)
3455 .unwrap()
3456 .remove_in_flight(&info);
3457
3458 for frame in info.stream_frames {
3459 self.streams.retransmit(frame);
3460 }
3461 self.spaces[pn_space].pending |= info.retransmits;
3462 let path = self.path_data_mut(path_id);
3463 path.mtud.on_non_probe_lost(packet, info.size);
3464 path.congestion.on_packet_lost(info.size, packet, now);
3465
3466 self.spaces[pn_space].for_path(path_id).lost_packets.insert(
3467 packet,
3468 LostPacket {
3469 time_sent: info.time_sent,
3470 },
3471 );
3472 }
3473
3474 let path = self.path_data_mut(path_id);
3475 if path.mtud.black_hole_detected(now) {
3476 path.congestion.on_mtu_update(path.mtud.current_mtu());
3477 if let Some(max_datagram_size) = self.datagrams().max_size()
3478 && self.datagrams.drop_oversized(max_datagram_size)
3479 && self.datagrams.send_blocked
3480 {
3481 self.datagrams.send_blocked = false;
3482 self.events.push_back(Event::DatagramsUnblocked);
3483 }
3484 self.path_stats.for_path(path_id).black_holes_detected += 1;
3485 }
3486
3487 let lost_ack_eliciting =
3489 old_bytes_in_flight != self.path_data_mut(path_id).in_flight.bytes;
3490
3491 if lost_ack_eliciting {
3492 self.path_stats.for_path(path_id).congestion_events += 1;
3493 self.path_data_mut(path_id).congestion.on_congestion_event(
3494 now,
3495 largest_lost_sent,
3496 in_persistent_congestion,
3497 false,
3498 size_of_lost_packets,
3499 largest_lost,
3500 );
3501 }
3502 }
3503
3504 if let Some(packet) = lost_mtu_probe {
3506 let info = self.spaces[SpaceId::Data]
3507 .for_path(path_id)
3508 .take(packet)
3509 .unwrap(); self.paths
3512 .get_mut(&path_id)
3513 .unwrap()
3514 .remove_in_flight(&info);
3515 self.path_data_mut(path_id).mtud.on_probe_lost();
3516 self.path_stats.for_path(path_id).lost_plpmtud_probes += 1;
3517 }
3518 }
3519
3520 fn loss_time_and_space(&self, path_id: PathId) -> Option<(Instant, SpaceId)> {
3526 SpaceId::iter()
3527 .filter_map(|id| {
3528 self.spaces[id]
3529 .number_spaces
3530 .get(&path_id)
3531 .and_then(|pns| pns.loss_time)
3532 .map(|time| (time, id))
3533 })
3534 .min_by_key(|&(time, _)| time)
3535 }
3536
3537 fn pto_time_and_space(&mut self, now: Instant, path_id: PathId) -> Option<(Instant, SpaceId)> {
3545 let path = self.path(path_id)?;
3546 let pto_count = path.pto_count;
3547
3548 let max_interval = if path.rtt.get() > SLOW_RTT_THRESHOLD {
3550 (path.rtt.get() * 3) / 2
3552 } else if let Some(idle) = path.idle_timeout.or(self.idle_timeout)
3553 && idle <= MIN_IDLE_FOR_FAST_PTO
3554 {
3555 MAX_PTO_FAST_INTERVAL
3558 } else {
3559 MAX_PTO_INTERVAL
3561 };
3562
3563 if path_id == PathId::ZERO
3564 && path.in_flight.ack_eliciting == 0
3565 && !self.peer_completed_handshake_address_validation()
3566 {
3567 let space = match self.highest_space {
3573 SpaceKind::Handshake => SpaceId::Handshake,
3574 _ => SpaceId::Initial,
3575 };
3576
3577 let backoff = 2u32.pow(path.pto_count.min(MAX_BACKOFF_EXPONENT));
3578 let duration = path.rtt.pto_base() * backoff;
3579 let duration = duration.min(max_interval);
3580 return Some((now + duration, space));
3581 }
3582
3583 let mut result = None;
3584 for space in SpaceId::iter() {
3585 let Some(pns) = self.spaces[space].number_spaces.get(&path_id) else {
3586 continue;
3587 };
3588
3589 if space == SpaceId::Data && !self.is_handshake_confirmed() {
3590 continue;
3594 }
3595
3596 if !pns.has_in_flight() {
3597 continue;
3598 }
3599
3600 let duration = {
3605 let max_ack_delay = if space == SpaceId::Data {
3606 self.ack_frequency.max_ack_delay_for_pto()
3607 } else {
3608 Duration::ZERO
3609 };
3610 let pto_base = path.rtt.pto_base() + max_ack_delay;
3611 let mut duration = pto_base;
3612 for i in 1..=pto_count {
3613 let exponential_duration = pto_base * 2u32.pow(i.min(MAX_BACKOFF_EXPONENT));
3614 let max_duration = duration + max_interval;
3615 duration = exponential_duration.min(max_duration);
3616 }
3617 duration
3618 };
3619
3620 let Some(last_ack_eliciting) = pns.time_of_last_ack_eliciting_packet else {
3621 continue;
3622 };
3623 let pto = last_ack_eliciting + duration;
3626 if result.is_none_or(|(earliest_pto, _)| pto < earliest_pto) {
3627 if path.anti_amplification_blocked(1) {
3628 continue;
3630 }
3631 if path.in_flight.ack_eliciting == 0 {
3632 continue;
3634 }
3635 result = Some((pto, space));
3636 }
3637 }
3638 result
3639 }
3640
3641 fn peer_completed_handshake_address_validation(&self) -> bool {
3643 if self.side.is_server() || self.state.is_closed() {
3644 return true;
3645 }
3646 self.spaces[SpaceId::Handshake]
3650 .path_space(PathId::ZERO)
3651 .and_then(|pns| pns.largest_acked_packet_pn)
3652 .is_some()
3653 || self.spaces[SpaceId::Data]
3654 .path_space(PathId::ZERO)
3655 .and_then(|pns| pns.largest_acked_packet_pn)
3656 .is_some()
3657 || (self.crypto_state.has_keys(EncryptionLevel::OneRtt)
3658 && !self.crypto_state.has_keys(EncryptionLevel::Handshake))
3659 }
3660
3661 fn set_loss_detection_timer(&mut self, now: Instant, path_id: PathId) {
3669 if self.state.is_closed() {
3670 return;
3674 }
3675
3676 if let Some((loss_time, _)) = self.loss_time_and_space(path_id) {
3677 self.timers.set(
3679 Timer::PerPath(path_id, PathTimer::LossDetection),
3680 loss_time,
3681 self.qlog.with_time(now),
3682 );
3683 return;
3684 }
3685
3686 if !self.abandoned_paths.contains(&path_id)
3689 && let Some((timeout, _)) = self.pto_time_and_space(now, path_id)
3690 {
3691 self.timers.set(
3692 Timer::PerPath(path_id, PathTimer::LossDetection),
3693 timeout,
3694 self.qlog.with_time(now),
3695 );
3696 } else {
3697 self.timers.stop(
3698 Timer::PerPath(path_id, PathTimer::LossDetection),
3699 self.qlog.with_time(now),
3700 );
3701 }
3702 }
3703
3704 fn max_pto_for_space(&self, space: SpaceKind) -> Duration {
3708 self.paths
3709 .keys()
3710 .map(|path_id| self.pto(space, *path_id))
3711 .max()
3712 .unwrap_or_else(|| {
3713 let rtt = self.config.initial_rtt;
3717 let max_ack_delay = match space {
3718 SpaceKind::Initial | SpaceKind::Handshake => Duration::ZERO,
3719 SpaceKind::Data => self.ack_frequency.max_ack_delay_for_pto(),
3720 };
3721 rtt + cmp::max(4 * (rtt / 2), TIMER_GRANULARITY) + max_ack_delay
3722 })
3723 }
3724
3725 fn pto(&self, space: SpaceKind, path_id: PathId) -> Duration {
3730 let max_ack_delay = match space {
3731 SpaceKind::Initial | SpaceKind::Handshake => Duration::ZERO,
3732 SpaceKind::Data => self.ack_frequency.max_ack_delay_for_pto(),
3733 };
3734 self.path_data(path_id).rtt.pto_base() + max_ack_delay
3735 }
3736
3737 fn on_packet_authenticated(
3738 &mut self,
3739 now: Instant,
3740 space_id: SpaceKind,
3741 path_id: PathId,
3742 ecn: Option<EcnCodepoint>,
3743 packet_number: Option<u64>,
3744 spin: bool,
3745 is_1rtt: bool,
3746 remote: &FourTuple,
3747 ) {
3748 let is_on_path = self
3755 .path_data(path_id)
3756 .network_path
3757 .is_probably_same_path(remote);
3758
3759 self.total_authed_packets += 1;
3760 self.reset_keep_alive(path_id, now);
3761 self.reset_idle_timeout(now, space_id, path_id);
3762 self.path_data_mut(path_id).permit_idle_reset = true;
3763
3764 if is_on_path {
3767 self.receiving_ecn |= ecn.is_some();
3768 if let Some(x) = ecn {
3769 let space = &mut self.spaces[space_id];
3770 space.for_path(path_id).ecn_counters += x;
3771
3772 if x.is_ce() {
3773 space
3774 .for_path(path_id)
3775 .pending_acks
3776 .set_immediate_ack_required();
3777 }
3778 }
3779 }
3780
3781 let Some(packet_number) = packet_number else {
3782 return;
3783 };
3784 match &self.side {
3785 ConnectionSide::Client { .. } => {
3786 if space_id == SpaceKind::Handshake
3790 && let Some(hs) = self.state.as_handshake_mut()
3791 {
3792 hs.allow_server_migration = false;
3793 }
3794 }
3795 ConnectionSide::Server { .. } => {
3796 if self.crypto_state.has_keys(EncryptionLevel::Initial)
3797 && space_id == SpaceKind::Handshake
3798 {
3799 self.discard_space(now, SpaceKind::Initial);
3801 }
3802 if self.crypto_state.has_keys(EncryptionLevel::ZeroRtt) && is_1rtt {
3803 self.set_key_discard_timer(now, space_id)
3805 }
3806 }
3807 }
3808 let space = self.spaces[space_id].for_path(path_id);
3809
3810 space.pending_acks.insert_one(packet_number, now);
3811 if packet_number >= space.largest_received_packet_number.unwrap_or_default() {
3812 space.largest_received_packet_number = Some(packet_number);
3813
3814 if is_on_path {
3816 self.spin = self.side.is_client() ^ spin;
3817 }
3818 }
3819 }
3820
3821 fn reset_idle_timeout(&mut self, now: Instant, space: SpaceKind, path_id: PathId) {
3826 if let Some(timeout) = self.idle_timeout {
3828 if self.state.is_closed() {
3829 self.timers
3830 .stop(Timer::Conn(ConnTimer::Idle), self.qlog.with_time(now));
3831 } else {
3832 let dt = cmp::max(timeout, 3 * self.max_pto_for_space(space));
3833 self.timers.set(
3834 Timer::Conn(ConnTimer::Idle),
3835 now + dt,
3836 self.qlog.with_time(now),
3837 );
3838 }
3839 }
3840
3841 if let Some(timeout) = self.path_data(path_id).idle_timeout {
3843 if self.state.is_closed() {
3844 self.timers.stop(
3845 Timer::PerPath(path_id, PathTimer::PathIdle),
3846 self.qlog.with_time(now),
3847 );
3848 } else {
3849 let dt = cmp::max(timeout, 3 * self.pto(space, path_id));
3850 self.timers.set(
3851 Timer::PerPath(path_id, PathTimer::PathIdle),
3852 now + dt,
3853 self.qlog.with_time(now),
3854 );
3855 }
3856 }
3857 }
3858
3859 fn reset_keep_alive(&mut self, path_id: PathId, now: Instant) {
3861 if !self.state.is_established() {
3862 return;
3863 }
3864
3865 if let Some(interval) = self.config.keep_alive_interval {
3866 self.timers.set(
3867 Timer::Conn(ConnTimer::KeepAlive),
3868 now + interval,
3869 self.qlog.with_time(now),
3870 );
3871 }
3872
3873 if let Some(interval) = self.path_data(path_id).keep_alive {
3874 self.timers.set(
3875 Timer::PerPath(path_id, PathTimer::PathKeepAlive),
3876 now + interval,
3877 self.qlog.with_time(now),
3878 );
3879 }
3880 }
3881
3882 fn reset_cid_retirement(&mut self, now: Instant) {
3884 if let Some((_path, t)) = self.next_cid_retirement() {
3885 self.timers.set(
3886 Timer::Conn(ConnTimer::PushNewCid),
3887 t,
3888 self.qlog.with_time(now),
3889 );
3890 }
3891 }
3892
3893 fn next_cid_retirement(&self) -> Option<(PathId, Instant)> {
3895 self.local_cid_state
3896 .iter()
3897 .filter_map(|(path_id, cid_state)| cid_state.next_timeout().map(|t| (*path_id, t)))
3898 .min_by_key(|(_path_id, timeout)| *timeout)
3899 }
3900
3901 pub(crate) fn handle_first_packet(
3906 &mut self,
3907 now: Instant,
3908 network_path: FourTuple,
3909 ecn: Option<EcnCodepoint>,
3910 packet_number: u64,
3911 packet: InitialPacket,
3912 remaining: Option<BytesMut>,
3913 ) -> Result<(), ConnectionError> {
3914 let span = trace_span!("first recv");
3915 let _guard = span.enter();
3916 debug_assert!(self.side.is_server());
3917 let len = packet.header_data.len() + packet.payload.len();
3918 let path_id = PathId::ZERO;
3919 self.path_data_mut(path_id).total_recvd = len as u64;
3920
3921 if let Some(hs) = self.state.as_handshake_mut() {
3922 hs.expected_token = packet.header.token.clone();
3923 } else {
3924 unreachable!("first packet must be delivered in Handshake state");
3925 }
3926
3927 self.on_packet_authenticated(
3929 now,
3930 SpaceKind::Initial,
3931 path_id,
3932 ecn,
3933 Some(packet_number),
3934 false,
3935 false,
3936 &network_path,
3937 );
3938
3939 let packet: Packet = packet.into();
3940
3941 let mut qlog = QlogRecvPacket::new(len);
3942 qlog.header(&packet.header, Some(packet_number), path_id);
3943
3944 self.process_decrypted_packet(
3945 now,
3946 network_path,
3947 path_id,
3948 Some(packet_number),
3949 packet,
3950 &mut qlog,
3951 )?;
3952 self.qlog.emit_packet_received(qlog, now);
3953 if let Some(data) = remaining {
3954 self.handle_coalesced(now, network_path, path_id, ecn, data);
3955 }
3956
3957 self.qlog.emit_recovery_metrics(
3958 path_id,
3959 &mut self
3960 .paths
3961 .get_mut(&path_id)
3962 .expect("path_id was supplied by the caller for an active path")
3963 .data,
3964 now,
3965 );
3966
3967 Ok(())
3968 }
3969
3970 fn init_0rtt(&mut self, now: Instant) {
3971 let Some((header, packet)) = self.crypto_state.session.early_crypto() else {
3972 return;
3973 };
3974 if self.side.is_client() {
3975 match self.crypto_state.session.transport_parameters() {
3976 Ok(params) => {
3977 let params = params
3978 .expect("crypto layer didn't supply transport parameters with ticket");
3979 let params = TransportParameters {
3981 initial_src_cid: None,
3982 original_dst_cid: None,
3983 preferred_address: None,
3984 retry_src_cid: None,
3985 stateless_reset_token: None,
3986 min_ack_delay: None,
3987 ack_delay_exponent: TransportParameters::default().ack_delay_exponent,
3988 max_ack_delay: TransportParameters::default().max_ack_delay,
3989 initial_max_path_id: None,
3990 ..params
3991 };
3992 self.set_peer_params(params);
3993 self.qlog.emit_peer_transport_params_restored(self, now);
3994 }
3995 Err(e) => {
3996 error!("session ticket has malformed transport parameters: {}", e);
3997 return;
3998 }
3999 }
4000 }
4001 trace!("0-RTT enabled");
4002 self.crypto_state.enable_zero_rtt(header, packet);
4003 }
4004
4005 fn read_crypto(
4006 &mut self,
4007 space: SpaceId,
4008 crypto: &frame::Crypto,
4009 payload_len: usize,
4010 ) -> Result<(), TransportError> {
4011 let expected = if !self.state.is_handshake() {
4012 SpaceId::Data
4013 } else if self.highest_space == SpaceKind::Initial {
4014 SpaceId::Initial
4015 } else {
4016 SpaceId::Handshake
4019 };
4020 debug_assert!(space <= expected, "received out-of-order CRYPTO data");
4024
4025 let end = crypto.offset + crypto.data.len() as u64;
4026 if space < expected
4027 && end
4028 > self.crypto_state.spaces[space.kind()]
4029 .crypto_stream
4030 .bytes_read()
4031 {
4032 warn!(
4033 "received new {:?} CRYPTO data when expecting {:?}",
4034 space, expected
4035 );
4036 return Err(TransportError::PROTOCOL_VIOLATION(
4037 "new data at unexpected encryption level",
4038 ));
4039 }
4040
4041 let crypto_space = &mut self.crypto_state.spaces[space.kind()];
4042 let max = end.saturating_sub(crypto_space.crypto_stream.bytes_read());
4043 if max > self.config.crypto_buffer_size as u64 {
4044 return Err(TransportError::CRYPTO_BUFFER_EXCEEDED(""));
4045 }
4046
4047 crypto_space
4048 .crypto_stream
4049 .insert(crypto.offset, crypto.data.clone(), payload_len);
4050 while let Some(chunk) = crypto_space.crypto_stream.read(usize::MAX, true) {
4051 trace!("consumed {} CRYPTO bytes", chunk.bytes.len());
4052 if self.crypto_state.session.read_handshake(&chunk.bytes)? {
4053 self.events.push_back(Event::HandshakeDataReady);
4054 }
4055 }
4056
4057 Ok(())
4058 }
4059
4060 fn write_crypto(&mut self) {
4061 loop {
4062 let space = self.highest_space;
4063 let mut outgoing = Vec::new();
4064 if let Some(crypto) = self.crypto_state.session.write_handshake(&mut outgoing) {
4065 match space {
4066 SpaceKind::Initial => {
4067 self.upgrade_crypto(SpaceKind::Handshake, crypto);
4068 }
4069 SpaceKind::Handshake => {
4070 self.upgrade_crypto(SpaceKind::Data, crypto);
4071 }
4072 SpaceKind::Data => unreachable!("got updated secrets during 1-RTT"),
4073 }
4074 }
4075 if outgoing.is_empty() {
4076 if space == self.highest_space {
4077 break;
4078 } else {
4079 continue;
4081 }
4082 }
4083 let offset = self.crypto_state.spaces[space].crypto_offset;
4084 let outgoing = Bytes::from(outgoing);
4085 if let Some(hs) = self.state.as_handshake_mut()
4086 && space == SpaceKind::Initial
4087 && offset == 0
4088 && self.side.is_client()
4089 {
4090 hs.client_hello = Some(outgoing.clone());
4091 }
4092 self.crypto_state.spaces[space].crypto_offset += outgoing.len() as u64;
4093 trace!("wrote {} {:?} CRYPTO bytes", outgoing.len(), space);
4094 self.spaces[space].pending.crypto.push_back(frame::Crypto {
4095 offset,
4096 data: outgoing,
4097 });
4098 }
4099 }
4100
4101 fn upgrade_crypto(&mut self, space: SpaceKind, crypto: Keys) {
4103 debug_assert!(
4104 !self.crypto_state.has_keys(space.encryption_level()),
4105 "already reached packet space {space:?}"
4106 );
4107 trace!("{:?} keys ready", space);
4108 if space == SpaceKind::Data {
4109 self.crypto_state.next_crypto = Some(
4111 self.crypto_state
4112 .session
4113 .next_1rtt_keys()
4114 .expect("handshake should be complete"),
4115 );
4116 }
4117
4118 self.crypto_state.spaces[space].keys = Some(crypto);
4119 debug_assert!(space > self.highest_space);
4120 self.highest_space = space;
4121 if space == SpaceKind::Data && self.side.is_client() {
4122 self.crypto_state.discard_zero_rtt();
4124 }
4125 }
4126
4127 fn discard_space(&mut self, now: Instant, space: SpaceKind) {
4128 debug_assert!(space != SpaceKind::Data);
4129 trace!("discarding {:?} keys", space);
4130 if space == SpaceKind::Initial {
4131 if let ConnectionSide::Client { token, .. } = &mut self.side {
4133 *token = Bytes::new();
4134 }
4135 }
4136 self.crypto_state.spaces[space].keys = None;
4137 let space = &mut self.spaces[space];
4138 let pns = space.for_path(PathId::ZERO);
4139 pns.time_of_last_ack_eliciting_packet = None;
4140 pns.loss_time = None;
4141 pns.loss_probes = 0;
4142 let sent_packets = mem::take(&mut pns.sent_packets);
4143 let path = self
4144 .paths
4145 .get_mut(&PathId::ZERO)
4146 .expect("PathId::ZERO is alive while Initial/Handshake spaces exist");
4147 for (_, packet) in sent_packets.into_iter() {
4148 path.data.remove_in_flight(&packet);
4149 }
4150
4151 self.set_loss_detection_timer(now, PathId::ZERO)
4152 }
4153
4154 fn handle_coalesced(
4155 &mut self,
4156 now: Instant,
4157 network_path: FourTuple,
4158 path_id: PathId,
4159 ecn: Option<EcnCodepoint>,
4160 data: BytesMut,
4161 ) {
4162 self.path_data_mut(path_id)
4163 .inc_total_recvd(data.len() as u64);
4164 let mut remaining = Some(data);
4165 let cid_len = self
4166 .local_cid_state
4167 .values()
4168 .map(|cid_state| cid_state.cid_len())
4169 .next()
4170 .expect("one cid_state must exist");
4171 while let Some(data) = remaining {
4172 match PartialDecode::new(
4173 data,
4174 &FixedLengthConnectionIdParser::new(cid_len),
4175 &[self.version],
4176 self.endpoint_config.grease_quic_bit,
4177 ) {
4178 Ok((partial_decode, rest)) => {
4179 remaining = rest;
4180 self.handle_decode(now, network_path, path_id, ecn, partial_decode);
4181 }
4182 Err(e) => {
4183 trace!("malformed header: {}", e);
4184 return;
4185 }
4186 }
4187 }
4188 }
4189
4190 fn handle_decode(
4196 &mut self,
4197 now: Instant,
4198 network_path: FourTuple,
4199 path_id: PathId,
4200 ecn: Option<EcnCodepoint>,
4201 partial_decode: PartialDecode,
4202 ) {
4203 let qlog = QlogRecvPacket::new(partial_decode.len());
4204 if let Some(decoded) = self
4205 .crypto_state
4206 .unprotect_header(partial_decode, self.peer_params.stateless_reset_token)
4207 {
4208 self.handle_packet(
4209 now,
4210 network_path,
4211 path_id,
4212 ecn,
4213 decoded.packet,
4214 decoded.stateless_reset,
4215 qlog,
4216 );
4217 }
4218 }
4219
4220 fn handle_packet(
4227 &mut self,
4228 now: Instant,
4229 network_path: FourTuple,
4230 path_id: PathId,
4231 ecn: Option<EcnCodepoint>,
4232 packet: Option<Packet>,
4233 stateless_reset: bool,
4234 mut qlog: QlogRecvPacket,
4235 ) {
4236 self.path_stats.for_path(path_id).udp_rx.ios += 1;
4237
4238 if let Some(ref packet) = packet {
4239 trace!(
4240 "got {:?} packet ({} bytes) from {} using id {}",
4241 packet.header.space(),
4242 packet.payload.len() + packet.header_data.len(),
4243 network_path,
4244 packet.header.dst_cid(),
4245 );
4246 }
4247
4248 let was_closed = self.state.is_closed();
4249 let was_drained = self.state.is_drained();
4250
4251 let decrypted = match packet {
4253 None => Err(None),
4254 Some(mut packet) => self
4255 .decrypt_packet(now, path_id, &mut packet)
4256 .map(move |number| (packet, number)),
4257 };
4258 let result = match decrypted {
4259 _ if stateless_reset => {
4260 debug!("got stateless reset");
4261 Err(ConnectionError::Reset)
4262 }
4263 Err(Some(e)) => {
4264 warn!("illegal packet: {}", e);
4265 Err(e.into())
4266 }
4267 Err(None) => {
4268 debug!("failed to authenticate packet");
4269 self.authentication_failures += 1;
4270 let integrity_limit = self
4271 .crypto_state
4272 .integrity_limit(self.highest_space)
4273 .unwrap();
4274 if self.authentication_failures > integrity_limit {
4275 Err(TransportError::AEAD_LIMIT_REACHED("integrity limit violated").into())
4276 } else {
4277 return;
4278 }
4279 }
4280 Ok((packet, pn)) => {
4281 qlog.header(&packet.header, pn, path_id);
4283 let span = match pn {
4284 Some(pn) => trace_span!("recv", space = ?packet.header.space(), pn),
4285 None => trace_span!("recv", space = ?packet.header.space()),
4286 };
4287 let _guard = span.enter();
4288
4289 if self.is_handshaking()
4297 && self
4298 .path(path_id)
4299 .map(|path_data| {
4300 !path_data.network_path.is_probably_same_path(&network_path)
4301 })
4302 .unwrap_or(false)
4303 {
4304 if let Some(hs) = self.state.as_handshake()
4305 && hs.allow_server_migration
4306 {
4307 trace!(
4308 %network_path,
4309 prev = %self.path_data(path_id).network_path,
4310 "server migrated to new remote",
4311 );
4312 self.path_data_mut(path_id).network_path = network_path;
4313 self.qlog.emit_tuple_assigned(path_id, network_path, now);
4314 } else {
4315 debug!(
4316 recv_path = %network_path,
4317 expected_path = %self.path_data_mut(path_id).network_path,
4318 "discarding packet with unexpected remote during handshake",
4319 );
4320 return;
4321 }
4322 }
4323
4324 let dedup = self.spaces[packet.header.space()]
4325 .path_space_mut(path_id)
4326 .map(|pns| &mut pns.dedup);
4327 if pn.zip(dedup).is_some_and(|(n, d)| d.insert(n)) {
4328 debug!("discarding possible duplicate packet");
4329 self.qlog.emit_packet_received(qlog, now);
4330 return;
4331 } else if self.state.is_handshake() && packet.header.is_short() {
4332 trace!("dropping short packet during handshake");
4334 self.qlog.emit_packet_received(qlog, now);
4335 return;
4336 } else {
4337 if let Header::Initial(InitialHeader { ref token, .. }) = packet.header
4338 && let Some(hs) = self.state.as_handshake()
4339 && self.side.is_server()
4340 && token != &hs.expected_token
4341 {
4342 warn!("discarding Initial with invalid retry token");
4346 self.qlog.emit_packet_received(qlog, now);
4347 return;
4348 }
4349
4350 if !self.state.is_closed() {
4351 let spin = match packet.header {
4352 Header::Short { spin, .. } => spin,
4353 _ => false,
4354 };
4355
4356 if self.side().is_server() && !self.abandoned_paths.contains(&path_id) {
4357 self.ensure_path(path_id, network_path, now, pn);
4359 }
4360 if self.paths.contains_key(&path_id) {
4361 self.on_packet_authenticated(
4362 now,
4363 packet.header.space(),
4364 path_id,
4365 ecn,
4366 pn,
4367 spin,
4368 packet.header.is_1rtt(),
4369 &network_path,
4370 );
4371 }
4372 }
4373
4374 let res = self.process_decrypted_packet(
4375 now,
4376 network_path,
4377 path_id,
4378 pn,
4379 packet,
4380 &mut qlog,
4381 );
4382
4383 self.qlog.emit_packet_received(qlog, now);
4384 res
4385 }
4386 }
4387 };
4388
4389 if let Err(conn_err) = result {
4391 match conn_err {
4392 ConnectionError::ApplicationClosed(reason) => self.state.move_to_closed(reason),
4393 ConnectionError::ConnectionClosed(reason) => self.state.move_to_closed(reason),
4394 ConnectionError::Reset
4395 | ConnectionError::TransportError(TransportError {
4396 code: TransportErrorCode::AEAD_LIMIT_REACHED,
4397 ..
4398 }) => {
4399 self.state.move_to_drained(Some(conn_err));
4400 }
4401 ConnectionError::TimedOut => {
4402 unreachable!("timeouts aren't generated by packet processing");
4403 }
4404 ConnectionError::TransportError(err) => {
4405 debug!("closing connection due to transport error: {}", err);
4406 self.state.move_to_closed(err);
4407 }
4408 ConnectionError::VersionMismatch => {
4409 self.state.move_to_draining(Some(conn_err));
4410 }
4411 ConnectionError::LocallyClosed => {
4412 unreachable!("LocallyClosed isn't generated by packet processing");
4413 }
4414 ConnectionError::CidsExhausted => {
4415 unreachable!("CidsExhausted isn't generated by packet processing");
4416 }
4417 };
4418 }
4419
4420 if !was_closed && self.state.is_closed() {
4421 self.close_common();
4422 if !self.state.is_drained() {
4423 self.set_close_timer(now);
4424 }
4425 }
4426 if !was_drained && self.state.is_drained() {
4427 self.endpoint_events.push_back(EndpointEventInner::Drained);
4428 self.timers
4431 .stop(Timer::Conn(ConnTimer::Close), self.qlog.with_time(now));
4432 }
4433
4434 if matches!(self.state.as_type(), StateType::Closed) {
4441 if self
4459 .paths
4460 .get(&path_id)
4461 .map(|p| p.data.validated && p.data.network_path == network_path)
4462 .unwrap_or(false)
4463 {
4464 self.connection_close_pending = true;
4465 }
4466 }
4467 }
4468
4469 fn process_decrypted_packet(
4470 &mut self,
4471 now: Instant,
4472 network_path: FourTuple,
4473 path_id: PathId,
4474 number: Option<u64>,
4475 packet: Packet,
4476 qlog: &mut QlogRecvPacket,
4477 ) -> Result<(), ConnectionError> {
4478 if !self.paths.contains_key(&path_id) {
4479 trace!(%path_id, ?number, "discarding packet for unknown path");
4483 return Ok(());
4484 }
4485 let state = match self.state.as_type() {
4486 StateType::Established => {
4487 match packet.header.space() {
4488 SpaceKind::Data => self.process_payload(
4489 now,
4490 network_path,
4491 path_id,
4492 number.unwrap(),
4493 packet,
4494 qlog,
4495 )?,
4496 _ if packet.header.has_frames() => {
4497 self.process_early_payload(now, path_id, packet, qlog)?
4498 }
4499 _ => {
4500 trace!("discarding unexpected pre-handshake packet");
4501 }
4502 }
4503 return Ok(());
4504 }
4505 StateType::Closed => {
4506 for result in frame::Iter::new(packet.payload.freeze())? {
4507 let frame = match result {
4508 Ok(frame) => frame,
4509 Err(err) => {
4510 debug!("frame decoding error: {err:?}");
4511 continue;
4512 }
4513 };
4514 qlog.frame(&frame);
4515
4516 if let Frame::Padding = frame {
4517 continue;
4518 };
4519
4520 self.path_stats
4521 .for_path(path_id)
4522 .frame_rx
4523 .record(frame.ty());
4524
4525 if let Frame::Close(_error) = frame {
4526 self.state.move_to_draining(None);
4527 break;
4528 }
4529 }
4530 return Ok(());
4531 }
4532 StateType::Draining | StateType::Drained => return Ok(()),
4533 StateType::Handshake => self.state.as_handshake_mut().expect("checked"),
4534 };
4535
4536 match packet.header {
4537 Header::Retry {
4538 src_cid: remote_cid,
4539 ..
4540 } => {
4541 debug_assert_eq!(path_id, PathId::ZERO);
4542 if self.side.is_server() {
4543 return Err(TransportError::PROTOCOL_VIOLATION("client sent Retry").into());
4544 }
4545
4546 let is_valid_retry = self
4547 .remote_cids
4548 .get(&path_id)
4549 .map(|cids| cids.active())
4550 .map(|orig_dst_cid| {
4551 self.crypto_state.session.is_valid_retry(
4552 orig_dst_cid,
4553 &packet.header_data,
4554 &packet.payload,
4555 )
4556 })
4557 .unwrap_or_default();
4558 if self.total_authed_packets > 1
4559 || packet.payload.len() <= 16 || !is_valid_retry
4561 {
4562 trace!("discarding invalid Retry");
4563 return Ok(());
4571 }
4572
4573 trace!("retrying with CID {}", remote_cid);
4574 let client_hello = state.client_hello.take().unwrap();
4575 self.retry_src_cid = Some(remote_cid);
4576 self.remote_cids
4577 .get_mut(&path_id)
4578 .expect("PathId::ZERO not yet abandoned, is_valid_retry would have been false")
4579 .update_initial_cid(remote_cid);
4580 self.remote_handshake_cid = remote_cid;
4581
4582 let space = &mut self.spaces[SpaceId::Initial];
4583 if let Some(info) = space.for_path(PathId::ZERO).take(0) {
4584 self.on_packet_acked(now, PathId::ZERO, 0, info);
4585 };
4586
4587 self.discard_space(now, SpaceKind::Initial); let crypto_space = &mut self.crypto_state.spaces[SpaceKind::Initial];
4590 crypto_space.keys = Some(
4591 self.crypto_state
4592 .session
4593 .initial_keys(remote_cid, self.side.side()),
4594 );
4595 crypto_space.crypto_offset = client_hello.len() as u64;
4596
4597 let next_pn = self.spaces[SpaceId::Initial]
4598 .for_path(path_id)
4599 .next_packet_number;
4600 self.spaces[SpaceId::Initial] = {
4601 let mut space = PacketSpace::new(now, SpaceId::Initial, &mut self.rng);
4602 space.for_path(path_id).next_packet_number = next_pn;
4603 space.pending.crypto.push_back(frame::Crypto {
4604 offset: 0,
4605 data: client_hello,
4606 });
4607 space
4608 };
4609
4610 let zero_rtt = mem::take(
4612 &mut self.spaces[SpaceId::Data]
4613 .for_path(PathId::ZERO)
4614 .sent_packets,
4615 );
4616 for (_, info) in zero_rtt.into_iter() {
4617 self.paths
4618 .get_mut(&PathId::ZERO)
4619 .unwrap()
4620 .remove_in_flight(&info);
4621 self.spaces[SpaceId::Data].pending |= info.retransmits;
4622 }
4623 self.streams.retransmit_all_for_0rtt();
4624
4625 let token_len = packet.payload.len() - 16;
4626 let ConnectionSide::Client { ref mut token, .. } = self.side else {
4627 unreachable!("we already short-circuited if we're server");
4628 };
4629 *token = packet.payload.freeze().split_to(token_len);
4630
4631 self.state = State::handshake(state::Handshake {
4632 expected_token: Bytes::new(),
4633 remote_cid_set: false,
4634 client_hello: None,
4635 allow_server_migration: true,
4636 });
4637 Ok(())
4638 }
4639 Header::Long {
4640 ty: LongType::Handshake,
4641 src_cid: remote_cid,
4642 dst_cid: local_cid,
4643 ..
4644 } => {
4645 debug_assert_eq!(path_id, PathId::ZERO);
4646 if remote_cid != self.remote_handshake_cid {
4647 debug!(
4648 "discarding packet with mismatched remote CID: {} != {}",
4649 self.remote_handshake_cid, remote_cid
4650 );
4651 return Ok(());
4652 }
4653 self.on_path_validated(path_id);
4654
4655 self.process_early_payload(now, path_id, packet, qlog)?;
4656 if self.state.is_closed() {
4657 return Ok(());
4658 }
4659
4660 if self.crypto_state.session.is_handshaking() {
4661 trace!("handshake ongoing");
4662 return Ok(());
4663 }
4664
4665 if self.side.is_client() {
4666 let params = self
4668 .crypto_state
4669 .session
4670 .transport_parameters()?
4671 .ok_or_else(|| {
4672 TransportError::new(
4673 TransportErrorCode::crypto(0x6d),
4674 "transport parameters missing".to_owned(),
4675 )
4676 })?;
4677
4678 if self.has_0rtt() {
4679 if !self.crypto_state.session.early_data_accepted().unwrap() {
4680 debug_assert!(self.side.is_client());
4681 debug!("0-RTT rejected");
4682 self.crypto_state.accepted_0rtt = false;
4683 self.streams.zero_rtt_rejected();
4684
4685 self.spaces[SpaceId::Data].pending = Retransmits::default();
4687
4688 let sent_packets = mem::take(
4690 &mut self.spaces[SpaceId::Data].for_path(path_id).sent_packets,
4691 );
4692 for (_, packet) in sent_packets.into_iter() {
4693 self.paths
4694 .get_mut(&path_id)
4695 .unwrap()
4696 .remove_in_flight(&packet);
4697 }
4698 } else {
4699 self.crypto_state.accepted_0rtt = true;
4700 params.validate_resumption_from(&self.peer_params)?;
4701 }
4702 }
4703 if let Some(token) = params.stateless_reset_token {
4704 let remote = self.path_data(path_id).network_path.remote;
4705 debug_assert!(!self.state.is_drained()); self.endpoint_events
4707 .push_back(EndpointEventInner::ResetToken(path_id, remote, token));
4708 }
4709 self.handle_peer_params(params, local_cid, remote_cid, now)?;
4710 self.issue_first_cids(now);
4711 } else {
4712 self.spaces[SpaceId::Data].pending.handshake_done = true;
4714 self.discard_space(now, SpaceKind::Handshake);
4715 self.events.push_back(Event::HandshakeConfirmed);
4716 trace!("handshake confirmed");
4717 }
4718
4719 self.events.push_back(Event::Connected);
4720 self.state.move_to_established();
4721 trace!("established");
4722
4723 self.issue_first_path_cids(now);
4726 Ok(())
4727 }
4728 Header::Initial(InitialHeader {
4729 src_cid: remote_cid,
4730 dst_cid: local_cid,
4731 ..
4732 }) => {
4733 debug_assert_eq!(path_id, PathId::ZERO);
4734 if !state.remote_cid_set {
4735 trace!("switching remote CID to {}", remote_cid);
4736 let mut state = state.clone();
4737 self.remote_cids
4738 .get_mut(&path_id)
4739 .expect("PathId::ZERO not yet abandoned")
4740 .update_initial_cid(remote_cid);
4741 self.remote_handshake_cid = remote_cid;
4742 self.original_remote_cid = remote_cid;
4743 state.remote_cid_set = true;
4744 self.state.move_to_handshake(state);
4745 } else if remote_cid != self.remote_handshake_cid {
4746 debug!(
4747 "discarding packet with mismatched remote CID: {} != {}",
4748 self.remote_handshake_cid, remote_cid
4749 );
4750 return Ok(());
4751 }
4752
4753 let starting_space = self.highest_space;
4754 self.process_early_payload(now, path_id, packet, qlog)?;
4755
4756 if self.side.is_server()
4757 && starting_space == SpaceKind::Initial
4758 && self.highest_space != SpaceKind::Initial
4759 {
4760 let params = self
4761 .crypto_state
4762 .session
4763 .transport_parameters()?
4764 .ok_or_else(|| {
4765 TransportError::new(
4766 TransportErrorCode::crypto(0x6d),
4767 "transport parameters missing".to_owned(),
4768 )
4769 })?;
4770 self.handle_peer_params(params, local_cid, remote_cid, now)?;
4771 self.issue_first_cids(now);
4772 self.init_0rtt(now);
4773 }
4774 Ok(())
4775 }
4776 Header::Long {
4777 ty: LongType::ZeroRtt,
4778 ..
4779 } => {
4780 self.process_payload(now, network_path, path_id, number.unwrap(), packet, qlog)?;
4781 Ok(())
4782 }
4783 Header::VersionNegotiate { .. } => {
4784 if self.total_authed_packets > 1 {
4785 return Ok(());
4786 }
4787 let supported = packet
4788 .payload
4789 .chunks(4)
4790 .any(|x| match <[u8; 4]>::try_from(x) {
4791 Ok(version) => self.version == u32::from_be_bytes(version),
4792 Err(_) => false,
4793 });
4794 if supported {
4795 return Ok(());
4796 }
4797 debug!("remote doesn't support our version");
4798 Err(ConnectionError::VersionMismatch)
4799 }
4800 Header::Short { .. } => unreachable!(
4801 "short packets received during handshake are discarded in handle_packet"
4802 ),
4803 }
4804 }
4805
4806 fn process_early_payload(
4808 &mut self,
4809 now: Instant,
4810 path_id: PathId,
4811 packet: Packet,
4812 #[allow(unused)] qlog: &mut QlogRecvPacket,
4813 ) -> Result<(), TransportError> {
4814 debug_assert_ne!(packet.header.space(), SpaceKind::Data);
4815 debug_assert_eq!(path_id, PathId::ZERO);
4816 let payload_len = packet.payload.len();
4817 let mut ack_eliciting = false;
4818 for result in frame::Iter::new(packet.payload.freeze())? {
4819 let frame = result?;
4820 qlog.frame(&frame);
4821 let span = match frame {
4822 Frame::Padding => continue,
4823 _ => Some(trace_span!("frame", ty = %frame.ty(), path = tracing::field::Empty)),
4824 };
4825
4826 self.path_stats
4827 .for_path(path_id)
4828 .frame_rx
4829 .record(frame.ty());
4830
4831 let _guard = span.as_ref().map(|x| x.enter());
4832 ack_eliciting |= frame.is_ack_eliciting();
4833
4834 if frame.is_1rtt() && packet.header.space() != SpaceKind::Data {
4836 return Err(TransportError::PROTOCOL_VIOLATION(
4837 "illegal frame type in handshake",
4838 ));
4839 }
4840
4841 match frame {
4842 Frame::Padding | Frame::Ping => {}
4843 Frame::Crypto(frame) => {
4844 self.read_crypto(packet.header.space().into(), &frame, payload_len)?;
4845 }
4846 Frame::Ack(ack) => {
4847 self.on_ack_received(now, packet.header.space().into(), ack)?;
4848 }
4849 Frame::PathAck(ack) => {
4850 span.as_ref()
4851 .map(|span| span.record("path", tracing::field::display(&ack.path_id)));
4852 self.on_path_ack_received(now, packet.header.space().into(), ack)?;
4853 }
4854 Frame::Close(reason) => {
4855 self.state.move_to_draining(Some(reason.into()));
4856 return Ok(());
4857 }
4858 _ => {
4859 let mut err =
4860 TransportError::PROTOCOL_VIOLATION("illegal frame type in handshake");
4861 err.frame = frame::MaybeFrame::Known(frame.ty());
4862 return Err(err);
4863 }
4864 }
4865 }
4866
4867 if ack_eliciting {
4868 self.spaces[packet.header.space()]
4870 .for_path(path_id)
4871 .pending_acks
4872 .set_immediate_ack_required();
4873 }
4874
4875 self.write_crypto();
4876 Ok(())
4877 }
4878
4879 fn process_payload(
4881 &mut self,
4882 now: Instant,
4883 network_path: FourTuple,
4884 path_id: PathId,
4885 number: u64,
4886 packet: Packet,
4887 #[allow(unused)] qlog: &mut QlogRecvPacket,
4888 ) -> Result<(), TransportError> {
4889 let is_multipath_negotiated = self.is_multipath_negotiated();
4890 let payload = packet.payload.freeze();
4891 let mut is_probing_packet = true;
4892 let mut close = None;
4893 let payload_len = payload.len();
4894 let mut ack_eliciting = false;
4895 let mut migration_observed_addr = None;
4898 for result in frame::Iter::new(payload)? {
4899 let frame = result?;
4900 qlog.frame(&frame);
4901 let span = match frame {
4902 Frame::Padding => continue,
4903 _ => trace_span!("frame", ty = %frame.ty(), path = tracing::field::Empty),
4904 };
4905
4906 self.path_stats
4907 .for_path(path_id)
4908 .frame_rx
4909 .record(frame.ty());
4910 match &frame {
4913 Frame::Crypto(f) => {
4914 trace!(offset = f.offset, len = f.data.len(), "got frame CRYPTO");
4915 }
4916 Frame::Stream(f) => {
4917 trace!(id = %f.id, offset = f.offset, len = f.data.len(), fin = f.fin, "got frame STREAM");
4918 }
4919 Frame::Datagram(f) => {
4920 trace!(len = f.data.len(), "got frame DATAGRAM");
4921 }
4922 f => {
4923 trace!("got frame {f}");
4924 }
4925 }
4926
4927 let _guard = span.enter();
4928 if packet.header.is_0rtt() {
4929 match frame {
4930 Frame::Crypto(_) | Frame::Close(Close::Application(_)) => {
4931 return Err(TransportError::PROTOCOL_VIOLATION(
4932 "illegal frame type in 0-RTT",
4933 ));
4934 }
4935 _ => {
4936 if frame.is_1rtt() {
4937 return Err(TransportError::PROTOCOL_VIOLATION(
4938 "illegal frame type in 0-RTT",
4939 ));
4940 }
4941 }
4942 }
4943 }
4944 ack_eliciting |= frame.is_ack_eliciting();
4945
4946 match frame {
4948 Frame::Padding
4949 | Frame::PathChallenge(_)
4950 | Frame::PathResponse(_)
4951 | Frame::NewConnectionId(_)
4952 | Frame::ObservedAddr(_) => {}
4953 _ => {
4954 is_probing_packet = false;
4955 }
4956 }
4957
4958 match frame {
4959 Frame::Crypto(frame) => {
4960 self.read_crypto(SpaceId::Data, &frame, payload_len)?;
4961 }
4962 Frame::Stream(frame) => {
4963 if self.streams.received(frame, payload_len)?.should_transmit() {
4964 self.spaces[SpaceId::Data].pending.max_data = true;
4965 }
4966 }
4967 Frame::Ack(ack) => {
4968 self.on_ack_received(now, SpaceId::Data, ack)?;
4969 }
4970 Frame::PathAck(ack) => {
4971 if !self.is_multipath_negotiated() {
4972 return Err(TransportError::PROTOCOL_VIOLATION(
4973 "received PATH_ACK frame when multipath was not negotiated",
4974 ));
4975 }
4976 span.record("path", tracing::field::display(&ack.path_id));
4977 self.on_path_ack_received(now, SpaceId::Data, ack)?;
4978 }
4979 Frame::Padding | Frame::Ping => {}
4980 Frame::Close(reason) => {
4981 close = Some(reason);
4982 }
4983 Frame::PathChallenge(challenge) => {
4984 let path = &mut self
4985 .path_mut(path_id)
4986 .expect("payload is processed only after the path becomes known");
4987 path.path_responses.push(number, challenge.0, network_path);
4988 if network_path.remote == path.network_path.remote {
4992 match self.peer_supports_ack_frequency() {
5000 true => self.immediate_ack(path_id),
5001 false => {
5002 self.ping_path(path_id).ok();
5003 }
5004 }
5005 }
5006 }
5007 Frame::PathResponse(response) => {
5008 if self
5010 .n0_nat_traversal
5011 .handle_path_response(network_path, response.0)
5012 {
5013 self.open_nat_traversed_paths(now);
5014 } else {
5015 let path = self
5018 .paths
5019 .get_mut(&path_id)
5020 .expect("payload is processed only after the path becomes known");
5021
5022 use PathTimer::*;
5023 use paths::OnPathResponseReceived::*;
5024 match path
5025 .data
5026 .on_path_response_received(now, response.0, network_path)
5027 {
5028 OnPath { was_open } => {
5029 let qlog = self.qlog.with_time(now);
5030
5031 self.timers.stop(
5032 Timer::PerPath(path_id, PathValidationFailed),
5033 qlog.clone(),
5034 );
5035 self.timers.stop(
5036 Timer::PerPath(path_id, AbandonFromValidation),
5037 qlog.clone(),
5038 );
5039
5040 let next_challenge = path
5041 .data
5042 .earliest_on_path_expiring_challenge()
5043 .map(|time| time + self.ack_frequency.max_ack_delay_for_pto());
5044 self.timers.set_or_stop(
5045 Timer::PerPath(path_id, PathChallengeLost),
5046 next_challenge,
5047 qlog,
5048 );
5049
5050 if !was_open {
5051 if is_multipath_negotiated {
5052 self.events.push_back(Event::Path(
5053 PathEvent::Established { id: path_id },
5054 ));
5055 }
5056 if let Some(observed) =
5057 path.data.last_observed_addr_report.as_ref()
5058 {
5059 self.events.push_back(Event::Path(
5060 PathEvent::ObservedAddr {
5061 id: path_id,
5062 addr: observed.socket_addr(),
5063 },
5064 ));
5065 }
5066 }
5067 if let Some((_, ref mut prev)) = path.prev {
5068 prev.reset_on_path_challenges();
5073 }
5074 }
5075 Ignored {
5076 sent_on,
5077 current_path,
5078 } => {
5079 debug!(%sent_on, %current_path, %response, "ignoring valid PATH_RESPONSE")
5080 }
5081 Unknown => debug!(%response, "ignoring invalid PATH_RESPONSE"),
5082 }
5083 }
5084 }
5085 Frame::MaxData(frame::MaxData(bytes)) => {
5086 self.streams.received_max_data(bytes);
5087 }
5088 Frame::MaxStreamData(frame::MaxStreamData { id, offset }) => {
5089 self.streams.received_max_stream_data(id, offset)?;
5090 }
5091 Frame::MaxStreams(frame::MaxStreams { dir, count }) => {
5092 self.streams.received_max_streams(dir, count)?;
5093 }
5094 Frame::ResetStream(frame) => {
5095 if self.streams.received_reset(frame)?.should_transmit() {
5096 self.spaces[SpaceId::Data].pending.max_data = true;
5097 }
5098 }
5099 Frame::DataBlocked(DataBlocked(offset)) => {
5100 debug!(offset, "peer claims to be blocked at connection level");
5101 }
5102 Frame::StreamDataBlocked(StreamDataBlocked { id, offset }) => {
5103 if id.initiator() == self.side.side() && id.dir() == Dir::Uni {
5104 debug!("got STREAM_DATA_BLOCKED on send-only {}", id);
5105 return Err(TransportError::STREAM_STATE_ERROR(
5106 "STREAM_DATA_BLOCKED on send-only stream",
5107 ));
5108 }
5109 debug!(
5110 stream = %id,
5111 offset, "peer claims to be blocked at stream level"
5112 );
5113 }
5114 Frame::StreamsBlocked(StreamsBlocked { dir, limit }) => {
5115 if limit > MAX_STREAM_COUNT {
5116 return Err(TransportError::FRAME_ENCODING_ERROR(
5117 "unrepresentable stream limit",
5118 ));
5119 }
5120 debug!(
5121 "peer claims to be blocked opening more than {} {} streams",
5122 limit, dir
5123 );
5124 }
5125 Frame::StopSending(frame::StopSending { id, error_code }) => {
5126 if id.initiator() != self.side.side() {
5127 if id.dir() == Dir::Uni {
5128 debug!("got STOP_SENDING on recv-only {}", id);
5129 return Err(TransportError::STREAM_STATE_ERROR(
5130 "STOP_SENDING on recv-only stream",
5131 ));
5132 }
5133 } else if self.streams.is_local_unopened(id) {
5134 return Err(TransportError::STREAM_STATE_ERROR(
5135 "STOP_SENDING on unopened stream",
5136 ));
5137 }
5138 self.streams.received_stop_sending(id, error_code);
5139 }
5140 Frame::RetireConnectionId(frame::RetireConnectionId { path_id, sequence }) => {
5141 if let Some(ref path_id) = path_id {
5142 span.record("path", tracing::field::display(&path_id));
5143 }
5144 let path_id = path_id.unwrap_or_default();
5145 match self.local_cid_state.get_mut(&path_id) {
5146 None => debug!(?path_id, "RETIRE_CONNECTION_ID for unknown path"),
5147 Some(cid_state) => {
5148 let allow_more_cids = cid_state
5149 .on_cid_retirement(sequence, self.peer_params.issue_cids_limit())?;
5150
5151 let has_path = !self.abandoned_paths.contains(&path_id);
5155 let allow_more_cids = allow_more_cids && has_path;
5156
5157 debug_assert!(!self.state.is_drained()); self.endpoint_events
5159 .push_back(EndpointEventInner::RetireConnectionId(
5160 now,
5161 path_id,
5162 sequence,
5163 allow_more_cids,
5164 ));
5165 }
5166 }
5167 }
5168 Frame::NewConnectionId(frame) => {
5169 let path_id = if let Some(path_id) = frame.path_id {
5170 if !self.is_multipath_negotiated() {
5171 return Err(TransportError::PROTOCOL_VIOLATION(
5172 "received PATH_NEW_CONNECTION_ID frame when multipath was not negotiated",
5173 ));
5174 }
5175 if path_id > self.local_max_path_id {
5176 return Err(TransportError::PROTOCOL_VIOLATION(
5177 "PATH_NEW_CONNECTION_ID contains path_id exceeding current max",
5178 ));
5179 }
5180 path_id
5181 } else {
5182 PathId::ZERO
5183 };
5184
5185 if let Some(ref path_id) = frame.path_id {
5186 span.record("path", tracing::field::display(&path_id));
5187 }
5188
5189 if self.abandoned_paths.contains(&path_id) {
5190 trace!("ignoring issued CID for abandoned path");
5191 continue;
5192 }
5193 let remote_cids = self
5194 .remote_cids
5195 .entry(path_id)
5196 .or_insert_with(|| CidQueue::new(frame.id));
5197 if remote_cids.active().is_empty() {
5198 return Err(TransportError::PROTOCOL_VIOLATION(
5199 "NEW_CONNECTION_ID when CIDs aren't in use",
5200 ));
5201 }
5202 if frame.retire_prior_to > frame.sequence {
5203 return Err(TransportError::PROTOCOL_VIOLATION(
5204 "NEW_CONNECTION_ID retiring unissued CIDs",
5205 ));
5206 }
5207
5208 use crate::cid_queue::InsertError;
5209 match remote_cids.insert(frame) {
5210 Ok(None) => {
5211 self.open_nat_traversed_paths(now);
5212 }
5213 Ok(Some((retired, reset_token))) => {
5214 let pending_retired =
5215 &mut self.spaces[SpaceId::Data].pending.retire_cids;
5216 const MAX_PENDING_RETIRED_CIDS: u64 = CidQueue::LEN as u64 * 10;
5219 if (pending_retired.len() as u64)
5222 .saturating_add(retired.end.saturating_sub(retired.start))
5223 > MAX_PENDING_RETIRED_CIDS
5224 {
5225 return Err(TransportError::CONNECTION_ID_LIMIT_ERROR(
5226 "queued too many retired CIDs",
5227 ));
5228 }
5229 pending_retired.extend(retired.map(|seq| (path_id, seq)));
5230 self.set_reset_token(path_id, network_path.remote, reset_token);
5231 self.open_nat_traversed_paths(now);
5232 }
5233 Err(InsertError::ExceedsLimit) => {
5234 return Err(TransportError::CONNECTION_ID_LIMIT_ERROR(""));
5235 }
5236 Err(InsertError::Retired) => {
5237 trace!("discarding already-retired");
5238 self.spaces[SpaceId::Data]
5242 .pending
5243 .retire_cids
5244 .push((path_id, frame.sequence));
5245 continue;
5246 }
5247 };
5248
5249 if self.side.is_server()
5250 && path_id == PathId::ZERO
5251 && self
5252 .remote_cids
5253 .get(&PathId::ZERO)
5254 .map(|cids| cids.active_seq() == 0)
5255 .unwrap_or_default()
5256 {
5257 self.update_remote_cid(PathId::ZERO);
5260 }
5261 }
5262 Frame::NewToken(NewToken { token }) => {
5263 let ConnectionSide::Client {
5264 token_store,
5265 server_name,
5266 ..
5267 } = &self.side
5268 else {
5269 return Err(TransportError::PROTOCOL_VIOLATION("client sent NEW_TOKEN"));
5270 };
5271 if token.is_empty() {
5272 return Err(TransportError::FRAME_ENCODING_ERROR("empty token"));
5273 }
5274 trace!("got new token");
5275 token_store.insert(server_name, token);
5276 }
5277 Frame::Datagram(datagram) => {
5278 if self
5279 .datagrams
5280 .received(datagram, &self.config.datagram_receive_buffer_size)?
5281 {
5282 self.events.push_back(Event::DatagramReceived);
5283 }
5284 }
5285 Frame::AckFrequency(ack_frequency) => {
5286 if !self.ack_frequency.ack_frequency_received(&ack_frequency)? {
5289 continue;
5292 }
5293
5294 for (path_id, space) in self.spaces[SpaceId::Data].number_spaces.iter_mut() {
5296 space.pending_acks.set_ack_frequency_params(&ack_frequency);
5297
5298 if !self.abandoned_paths.contains(path_id)
5302 && let Some(timeout) = space
5303 .pending_acks
5304 .max_ack_delay_timeout(self.ack_frequency.max_ack_delay)
5305 {
5306 self.timers.set(
5307 Timer::PerPath(*path_id, PathTimer::MaxAckDelay),
5308 timeout,
5309 self.qlog.with_time(now),
5310 );
5311 }
5312 }
5313 }
5314 Frame::ImmediateAck => {
5315 for pns in self.spaces[SpaceId::Data].iter_paths_mut() {
5317 pns.pending_acks.set_immediate_ack_required();
5318 }
5319 }
5320 Frame::HandshakeDone => {
5321 if self.side.is_server() {
5322 return Err(TransportError::PROTOCOL_VIOLATION(
5323 "client sent HANDSHAKE_DONE",
5324 ));
5325 }
5326 if self.crypto_state.has_keys(EncryptionLevel::Handshake) {
5327 self.discard_space(now, SpaceKind::Handshake);
5328 self.events.push_back(Event::HandshakeConfirmed);
5329 trace!("handshake confirmed");
5330 }
5331 }
5332 Frame::ObservedAddr(observed) => {
5333 trace!(seq_no = %observed.seq_no, ip = %observed.ip, port = observed.port);
5335 if !self
5336 .peer_params
5337 .address_discovery_role
5338 .should_report(&self.config.address_discovery_role)
5339 {
5340 return Err(TransportError::PROTOCOL_VIOLATION(
5341 "received OBSERVED_ADDRESS frame when not negotiated",
5342 ));
5343 }
5344 if packet.header.space() != SpaceKind::Data {
5346 return Err(TransportError::PROTOCOL_VIOLATION(
5347 "OBSERVED_ADDRESS frame outside data space",
5348 ));
5349 }
5350
5351 let path = self.path_data_mut(path_id);
5352 if path.network_path.is_probably_same_path(&network_path) {
5353 if let Some(updated) = path.update_observed_addr_report(observed)
5354 && path.open_status == paths::OpenStatus::Informed
5355 {
5356 self.events.push_back(Event::Path(PathEvent::ObservedAddr {
5357 id: path_id,
5358 addr: updated,
5359 }));
5360 }
5362 } else {
5363 migration_observed_addr = Some(observed)
5365 }
5366 }
5367 Frame::PathAbandon(frame::PathAbandon {
5368 path_id,
5369 error_code,
5370 }) => {
5371 span.record("path", tracing::field::display(&path_id));
5372 match self.close_path_inner(
5373 now,
5374 path_id,
5375 PathAbandonReason::RemoteAbandoned {
5376 error_code: error_code.into(),
5377 },
5378 ) {
5379 Ok(()) => {
5380 trace!("peer abandoned path");
5381 }
5382 Err(ClosePathError::ClosedPath) => {
5383 trace!("peer abandoned already closed path");
5384 }
5385 Err(ClosePathError::MultipathNotNegotiated) => {
5386 return Err(TransportError::PROTOCOL_VIOLATION(
5387 "received PATH_ABANDON frame when multipath was not negotiated",
5388 ));
5389 }
5390 Err(ClosePathError::LastOpenPath) => {
5391 error!(
5394 "peer abandoned last path but close_path_inner returned LastOpenPath"
5395 );
5396 }
5397 };
5398
5399 if let Some(path) = self.paths.get_mut(&path_id)
5401 && !mem::replace(&mut path.data.draining, true)
5402 {
5403 let ack_delay = self.ack_frequency.max_ack_delay_for_pto();
5404 let pto = path.data.rtt.pto_base() + ack_delay;
5405 self.timers.set(
5406 Timer::PerPath(path_id, PathTimer::PathDrained),
5407 now + 3 * pto,
5408 self.qlog.with_time(now),
5409 );
5410
5411 self.set_max_path_id(now, self.local_max_path_id.saturating_add(1u8));
5412 }
5413 }
5414 Frame::PathStatusAvailable(info) => {
5415 span.record("path", tracing::field::display(&info.path_id));
5416 if self.is_multipath_negotiated() {
5417 self.on_path_status(
5418 info.path_id,
5419 PathStatus::Available,
5420 info.status_seq_no,
5421 );
5422 } else {
5423 return Err(TransportError::PROTOCOL_VIOLATION(
5424 "received PATH_STATUS_AVAILABLE frame when multipath was not negotiated",
5425 ));
5426 }
5427 }
5428 Frame::PathStatusBackup(info) => {
5429 span.record("path", tracing::field::display(&info.path_id));
5430 if self.is_multipath_negotiated() {
5431 self.on_path_status(info.path_id, PathStatus::Backup, info.status_seq_no);
5432 } else {
5433 return Err(TransportError::PROTOCOL_VIOLATION(
5434 "received PATH_STATUS_BACKUP frame when multipath was not negotiated",
5435 ));
5436 }
5437 }
5438 Frame::MaxPathId(frame::MaxPathId(path_id)) => {
5439 span.record("path", tracing::field::display(&path_id));
5440 if !self.is_multipath_negotiated() {
5441 return Err(TransportError::PROTOCOL_VIOLATION(
5442 "received MAX_PATH_ID frame when multipath was not negotiated",
5443 ));
5444 }
5445 if path_id > self.remote_max_path_id {
5447 self.remote_max_path_id = path_id;
5448 self.issue_first_path_cids(now);
5449 self.open_nat_traversed_paths(now);
5450 }
5451 }
5452 Frame::PathsBlocked(frame::PathsBlocked(max_path_id)) => {
5453 if self.is_multipath_negotiated() {
5457 if max_path_id > self.local_max_path_id {
5458 return Err(TransportError::PROTOCOL_VIOLATION(
5459 "PATHS_BLOCKED maximum path identifier was larger than local maximum",
5460 ));
5461 }
5462 debug!("received PATHS_BLOCKED({:?})", max_path_id);
5463 } else {
5465 return Err(TransportError::PROTOCOL_VIOLATION(
5466 "received PATHS_BLOCKED frame when not multipath was not negotiated",
5467 ));
5468 }
5469 }
5470 Frame::PathCidsBlocked(frame::PathCidsBlocked { path_id, next_seq }) => {
5471 if self.is_multipath_negotiated() {
5479 if path_id > self.local_max_path_id {
5480 return Err(TransportError::PROTOCOL_VIOLATION(
5481 "PATH_CIDS_BLOCKED path identifier was larger than local maximum",
5482 ));
5483 }
5484 if next_seq.0
5485 > self
5486 .local_cid_state
5487 .get(&path_id)
5488 .map(|cid_state| cid_state.active_seq().1 + 1)
5489 .unwrap_or_default()
5490 {
5491 return Err(TransportError::PROTOCOL_VIOLATION(
5492 "PATH_CIDS_BLOCKED next sequence number larger than in local state",
5493 ));
5494 }
5495 debug!(%path_id, %next_seq, "received PATH_CIDS_BLOCKED");
5496 } else {
5497 return Err(TransportError::PROTOCOL_VIOLATION(
5498 "received PATH_CIDS_BLOCKED frame when not multipath was not negotiated",
5499 ));
5500 }
5501 }
5502 Frame::AddAddress(addr) => {
5503 let client_state = match self.n0_nat_traversal.client_side_mut() {
5504 Ok(state) => state,
5505 Err(err) => {
5506 return Err(TransportError::PROTOCOL_VIOLATION(format!(
5507 "Nat traversal(ADD_ADDRESS): {err}"
5508 )));
5509 }
5510 };
5511
5512 if !client_state.check_remote_address(&addr) {
5513 warn!(?addr, "server sent illegal ADD_ADDRESS frame");
5515 }
5516
5517 match client_state.add_remote_address(addr) {
5518 Ok(maybe_added) => {
5519 if let Some(added) = maybe_added {
5520 self.events.push_back(Event::NatTraversal(
5521 n0_nat_traversal::Event::AddressAdded(added),
5522 ));
5523 }
5524 }
5525 Err(e) => {
5526 warn!(%e, "failed to add remote address")
5527 }
5528 }
5529 }
5530 Frame::RemoveAddress(addr) => {
5531 let client_state = match self.n0_nat_traversal.client_side_mut() {
5532 Ok(state) => state,
5533 Err(err) => {
5534 return Err(TransportError::PROTOCOL_VIOLATION(format!(
5535 "Nat traversal(REMOVE_ADDRESS): {err}"
5536 )));
5537 }
5538 };
5539 if let Some(removed_addr) = client_state.remove_remote_address(addr) {
5540 self.events.push_back(Event::NatTraversal(
5541 n0_nat_traversal::Event::AddressRemoved(removed_addr),
5542 ));
5543 }
5544 }
5545 Frame::ReachOut(reach_out) => {
5546 let ipv6 = self.is_ipv6();
5547 let server_state = match self.n0_nat_traversal.server_side_mut() {
5548 Ok(state) => state,
5549 Err(err) => {
5550 return Err(TransportError::PROTOCOL_VIOLATION(format!(
5551 "Nat traversal(REACH_OUT): {err}"
5552 )));
5553 }
5554 };
5555
5556 let round_before = server_state.current_round();
5557
5558 if let Err(err) = server_state.handle_reach_out(reach_out, ipv6) {
5559 return Err(TransportError::PROTOCOL_VIOLATION(format!(
5560 "Nat traversal(REACH_OUT): {err}"
5561 )));
5562 }
5563
5564 if server_state.current_round() > round_before {
5565 if let Some(delay) =
5567 self.n0_nat_traversal.retry_delay(self.config.initial_rtt)
5568 {
5569 self.timers.set(
5570 Timer::Conn(ConnTimer::NatTraversalProbeRetry),
5571 now + delay,
5572 self.qlog.with_time(now),
5573 );
5574 }
5575 }
5576 }
5577 }
5578 }
5579
5580 let space = self.spaces[SpaceId::Data].for_path(path_id);
5581 if space
5582 .pending_acks
5583 .packet_received(now, number, ack_eliciting, &space.dedup)
5584 {
5585 if self.abandoned_paths.contains(&path_id) {
5586 space.pending_acks.set_immediate_ack_required();
5589 } else {
5590 self.timers.set(
5591 Timer::PerPath(path_id, PathTimer::MaxAckDelay),
5592 now + self.ack_frequency.max_ack_delay,
5593 self.qlog.with_time(now),
5594 );
5595 }
5596 }
5597
5598 let pending = &mut self.spaces[SpaceId::Data].pending;
5603 self.streams.queue_max_stream_id(pending);
5604
5605 if let Some(reason) = close {
5606 self.state.move_to_draining(Some(reason.into()));
5607 self.connection_close_pending = true;
5608 }
5609
5610 let migrate_on_any_packet =
5613 self.is_multipath_negotiated() && !self.n0_nat_traversal.is_negotiated();
5614
5615 let is_largest_received_pn = Some(number)
5617 == self.spaces[SpaceId::Data]
5618 .for_path(path_id)
5619 .largest_received_packet_number;
5620
5621 if (migrate_on_any_packet || !is_probing_packet)
5626 && is_largest_received_pn
5627 && self.local_ip_may_migrate()
5628 && let Some(new_local_ip) = network_path.local_ip
5629 {
5630 let path_data = self.path_data_mut(path_id);
5631 if path_data
5632 .network_path
5633 .local_ip
5634 .is_some_and(|ip| ip != new_local_ip)
5635 {
5636 debug!(
5637 %path_id,
5638 new_4tuple = %network_path,
5639 prev_4tuple = %path_data.network_path,
5640 "local address passive migration"
5641 );
5642 }
5643 path_data.network_path.local_ip = Some(new_local_ip)
5644 }
5645
5646 if (migrate_on_any_packet || !is_probing_packet)
5648 && is_largest_received_pn
5649 && network_path.remote != self.path_data(path_id).network_path.remote
5650 && self.remote_may_migrate()
5651 {
5652 self.migrate(path_id, now, network_path, migration_observed_addr);
5653 self.update_remote_cid(path_id);
5655 self.spin = false;
5656 }
5657
5658 Ok(())
5659 }
5660
5661 fn open_nat_traversed_paths(&mut self, now: Instant) {
5663 while let Some(network_path) = self
5664 .n0_nat_traversal
5665 .client_side_mut()
5666 .ok()
5667 .and_then(|s| s.pop_pending_path_open())
5668 {
5669 match self.open_path_ensure(network_path, PathStatus::Backup, now) {
5670 Ok((path_id, already_existed)) => {
5671 debug!(
5672 %path_id,
5673 ?network_path,
5674 new_path = !already_existed,
5675 "Opened NAT traversal path",
5676 );
5677 }
5678 Err(err) => match err {
5679 PathError::MultipathNotNegotiated
5680 | PathError::ServerSideNotAllowed
5681 | PathError::ValidationFailed
5682 | PathError::InvalidRemoteAddress(_) => {
5683 error!(
5684 ?err,
5685 ?network_path,
5686 "Failed to open path for successful NAT traversal"
5687 );
5688 }
5689 PathError::MaxPathIdReached | PathError::RemoteCidsExhausted => {
5690 self.n0_nat_traversal
5692 .client_side_mut()
5693 .map(|s| s.push_pending_path_open(network_path))
5694 .ok();
5695 debug!(
5696 ?err,
5697 ?network_path,
5698 "Blocked opening NAT traversal path, enqueued"
5699 );
5700 return;
5701 }
5702 },
5703 }
5704 }
5705 }
5706
5707 fn migrate(
5712 &mut self,
5713 path_id: PathId,
5714 now: Instant,
5715 network_path: FourTuple,
5716 observed_addr: Option<ObservedAddr>,
5717 ) {
5718 trace!(
5719 new_4tuple = %network_path,
5720 prev_4tuple = %self.path_data(path_id).network_path,
5721 %path_id,
5722 "migration initiated",
5723 );
5724 self.path_generation_counter = self.path_generation_counter.wrapping_add(1);
5725 let prev_pto = self.pto(SpaceKind::Data, path_id);
5732 let path = self.paths.get_mut(&path_id).expect("known path");
5733 let mut new_path_data = if network_path.remote.is_ipv4()
5734 && network_path.remote.ip() == path.data.network_path.remote.ip()
5735 {
5736 PathData::from_previous(network_path, &path.data, self.path_generation_counter, now)
5737 } else {
5738 let peer_max_udp_payload_size =
5739 u16::try_from(self.peer_params.max_udp_payload_size.into_inner())
5740 .unwrap_or(u16::MAX);
5741 PathData::new(
5742 network_path,
5743 self.allow_mtud,
5744 Some(peer_max_udp_payload_size),
5745 self.path_generation_counter,
5746 now,
5747 &self.config,
5748 )
5749 };
5750 new_path_data.last_observed_addr_report = path.data.last_observed_addr_report.clone();
5751 if let Some(report) = observed_addr
5752 && let Some(updated) = new_path_data.update_observed_addr_report(report)
5753 {
5754 tracing::info!("adding observed addr event from migration");
5755 self.events.push_back(Event::Path(PathEvent::ObservedAddr {
5756 id: path_id,
5757 addr: updated,
5758 }));
5759 }
5760 new_path_data.pending_on_path_challenge = true;
5761
5762 let mut prev_path_data = mem::replace(&mut path.data, new_path_data);
5763
5764 if !prev_path_data.validated
5773 && let Some(cid) = self.remote_cids.get(&path_id).map(CidQueue::active)
5774 {
5775 prev_path_data.pending_on_path_challenge = true;
5776 path.prev = Some((cid, prev_path_data));
5779 }
5780
5781 self.qlog.emit_tuple_assigned(path_id, network_path, now);
5783
5784 self.timers.set(
5785 Timer::PerPath(path_id, PathTimer::PathValidationFailed),
5786 now + 3 * cmp::max(self.pto(SpaceKind::Data, path_id), prev_pto),
5787 self.qlog.with_time(now),
5788 );
5789 }
5790
5791 pub fn handle_network_change(&mut self, hint: Option<&dyn NetworkChangeHint>, now: Instant) {
5808 debug!("network changed");
5809 if self.state.is_drained() {
5810 return;
5811 }
5812 if self.highest_space < SpaceKind::Data {
5813 for path in self.paths.values_mut() {
5814 path.data.network_path.local_ip = None;
5816 }
5817
5818 self.update_remote_cid(PathId::ZERO);
5819 self.ping();
5820
5821 return;
5822 }
5823
5824 let mut non_recoverable_paths = Vec::default();
5827 let mut recoverable_paths = Vec::default();
5828 let mut open_paths = 0;
5829
5830 let is_multipath_negotiated = self.is_multipath_negotiated();
5831 let is_client = self.side().is_client();
5832 let immediate_ack_allowed = self.peer_supports_ack_frequency();
5833
5834 for (path_id, path) in self.paths.iter_mut() {
5835 if self.abandoned_paths.contains(path_id) {
5836 continue;
5837 }
5838 open_paths += 1;
5839
5840 let network_path = path.data.network_path;
5843
5844 path.data.network_path.local_ip = None;
5847 let remote = network_path.remote;
5848
5849 let attempt_to_recover = if is_multipath_negotiated {
5853 hint.map(|h| h.is_path_recoverable(*path_id, network_path))
5857 .unwrap_or(!is_client)
5858 } else {
5859 true
5861 };
5862
5863 if attempt_to_recover {
5864 recoverable_paths.push((*path_id, remote));
5865 } else {
5866 non_recoverable_paths.push((*path_id, remote, path.data.local_status()))
5867 }
5868 }
5869
5870 let open_first = open_paths == non_recoverable_paths.len();
5879
5880 for (path_id, remote, status) in non_recoverable_paths.into_iter() {
5881 let network_path = FourTuple {
5882 remote,
5883 local_ip: None, };
5885
5886 if open_first && let Err(e) = self.open_path(network_path, status, now) {
5887 if self.side().is_client() {
5888 debug!(%e, "Failed to open new path for network change");
5889 }
5890 recoverable_paths.push((path_id, remote));
5892 continue;
5893 }
5894
5895 if let Err(e) =
5896 self.close_path_inner(now, path_id, PathAbandonReason::UnusableAfterNetworkChange)
5897 {
5898 debug!(%e,"Failed to close unrecoverable path after network change");
5899 recoverable_paths.push((path_id, remote));
5900 continue;
5901 }
5902
5903 if !open_first && let Err(e) = self.open_path(network_path, status, now) {
5904 debug!(%e,"Failed to open new path for network change");
5908 }
5909 }
5910
5911 for (path_id, remote) in recoverable_paths.into_iter() {
5914 if let Some(path_space) = self.spaces[SpaceId::Data].number_spaces.get_mut(&path_id) {
5916 path_space.ping_pending = true;
5917
5918 if immediate_ack_allowed {
5919 path_space.immediate_ack_pending = true;
5920 }
5921 }
5922
5923 if let Some(path) = self.paths.get_mut(&path_id) {
5928 path.data.pto_count = 0;
5929 }
5930 self.set_loss_detection_timer(now, path_id);
5931
5932 let Some((reset_token, retired)) =
5933 self.remote_cids.get_mut(&path_id).and_then(CidQueue::next)
5934 else {
5935 continue;
5936 };
5937
5938 self.spaces[SpaceId::Data]
5940 .pending
5941 .retire_cids
5942 .extend(retired.map(|seq| (path_id, seq)));
5943
5944 debug_assert!(!self.state.is_drained()); self.endpoint_events
5946 .push_back(EndpointEventInner::ResetToken(path_id, remote, reset_token));
5947 }
5948 }
5949
5950 fn update_remote_cid(&mut self, path_id: PathId) {
5952 let Some((reset_token, retired)) = self
5953 .remote_cids
5954 .get_mut(&path_id)
5955 .and_then(|cids| cids.next())
5956 else {
5957 return;
5958 };
5959
5960 self.spaces[SpaceId::Data]
5962 .pending
5963 .retire_cids
5964 .extend(retired.map(|seq| (path_id, seq)));
5965 let remote = self.path_data(path_id).network_path.remote;
5966 self.set_reset_token(path_id, remote, reset_token);
5967 }
5968
5969 fn set_reset_token(&mut self, path_id: PathId, remote: SocketAddr, reset_token: ResetToken) {
5978 debug_assert!(!self.state.is_drained()); self.endpoint_events
5980 .push_back(EndpointEventInner::ResetToken(path_id, remote, reset_token));
5981
5982 if path_id == PathId::ZERO {
5988 self.peer_params.stateless_reset_token = Some(reset_token);
5989 }
5990 }
5991
5992 fn issue_first_cids(&mut self, now: Instant) {
5994 if self
5995 .local_cid_state
5996 .get(&PathId::ZERO)
5997 .expect("PathId::ZERO exists when the connection is created")
5998 .cid_len()
5999 == 0
6000 {
6001 return;
6002 }
6003
6004 let mut n = self.peer_params.issue_cids_limit() - 1;
6006 if let ConnectionSide::Server { server_config } = &self.side
6007 && server_config.has_preferred_address()
6008 {
6009 n -= 1;
6011 }
6012 debug_assert!(!self.state.is_drained()); self.endpoint_events
6014 .push_back(EndpointEventInner::NeedIdentifiers(PathId::ZERO, now, n));
6015 }
6016
6017 fn issue_first_path_cids(&mut self, now: Instant) {
6021 if let Some(max_path_id) = self.max_path_id() {
6022 let mut path_id = self.max_path_id_with_cids.next();
6023 while path_id <= max_path_id {
6024 self.endpoint_events
6025 .push_back(EndpointEventInner::NeedIdentifiers(
6026 path_id,
6027 now,
6028 self.peer_params.issue_cids_limit(),
6029 ));
6030 path_id = path_id.next();
6031 }
6032 self.max_path_id_with_cids = max_path_id;
6033 }
6034 }
6035
6036 fn populate_packet<'a, 'b>(
6044 &mut self,
6045 now: Instant,
6046 space_id: SpaceId,
6047 path_id: PathId,
6048 scheduling_info: &PathSchedulingInfo,
6049 builder: &mut PacketBuilder<'a, 'b>,
6050 ) {
6051 let is_multipath_negotiated = self.is_multipath_negotiated();
6052 let space_has_keys = self.crypto_state.has_keys(space_id.encryption_level());
6053 let is_0rtt = space_id == SpaceId::Data && !space_has_keys;
6054 let stats = &mut self.path_stats.for_path(path_id).frame_tx;
6055 let space = &mut self.spaces[space_id];
6056 let path = &mut self.paths.get_mut(&path_id).expect("known path").data;
6057 space
6058 .for_path(path_id)
6059 .pending_acks
6060 .maybe_ack_non_eliciting();
6061
6062 if !is_0rtt
6064 && !scheduling_info.is_abandoned
6065 && scheduling_info.may_send_data
6066 && mem::replace(&mut space.pending.handshake_done, false)
6067 {
6068 builder.write_frame(frame::HandshakeDone, stats);
6069 }
6070
6071 if !scheduling_info.is_abandoned
6073 && mem::replace(&mut space.for_path(path_id).ping_pending, false)
6074 {
6075 builder.write_frame(frame::Ping, stats);
6076 }
6077
6078 if !scheduling_info.is_abandoned
6080 && mem::replace(&mut space.for_path(path_id).immediate_ack_pending, false)
6081 {
6082 debug_assert_eq!(
6083 space_id,
6084 SpaceId::Data,
6085 "immediate acks must be sent in the data space"
6086 );
6087 builder.write_frame(frame::ImmediateAck, stats);
6088 }
6089
6090 if !scheduling_info.is_abandoned && scheduling_info.may_send_data {
6092 for path_id in space
6093 .number_spaces
6094 .iter_mut()
6095 .filter(|(_, pns)| pns.pending_acks.can_send())
6096 .map(|(&path_id, _)| path_id)
6097 .collect::<Vec<_>>()
6098 {
6099 Self::populate_acks(
6100 now,
6101 self.receiving_ecn,
6102 path_id,
6103 space_id,
6104 space,
6105 is_multipath_negotiated,
6106 builder,
6107 stats,
6108 space_has_keys,
6109 );
6110 }
6111 }
6112
6113 if !scheduling_info.is_abandoned
6115 && scheduling_info.may_send_data
6116 && mem::replace(&mut space.pending.ack_frequency, false)
6117 {
6118 let sequence_number = self.ack_frequency.next_sequence_number();
6119
6120 let config = self.config.ack_frequency_config.as_ref().unwrap();
6122
6123 let max_ack_delay = self.ack_frequency.candidate_max_ack_delay(
6125 path.rtt.get(),
6126 config,
6127 &self.peer_params,
6128 );
6129
6130 let frame = frame::AckFrequency {
6131 sequence: sequence_number,
6132 ack_eliciting_threshold: config.ack_eliciting_threshold,
6133 request_max_ack_delay: max_ack_delay.as_micros().try_into().unwrap_or(VarInt::MAX),
6134 reordering_threshold: config.reordering_threshold,
6135 };
6136 builder.write_frame(frame, stats);
6137
6138 self.ack_frequency
6139 .ack_frequency_sent(path_id, builder.packet_number, max_ack_delay);
6140 }
6141
6142 if !scheduling_info.is_abandoned
6144 && space_id == SpaceId::Data
6145 && path.pending_on_path_challenge
6146 && !self.state.is_closed()
6147 && builder.frame_space_remaining() > frame::PathChallenge::SIZE_BOUND
6148 {
6150 path.pending_on_path_challenge = false;
6151
6152 let token = self.rng.random();
6153 path.record_path_challenge_sent(now, token, path.network_path);
6154 let challenge = frame::PathChallenge(token);
6156 builder.write_frame(challenge, stats);
6157 builder.require_padding();
6158 let pto = self.ack_frequency.max_ack_delay_for_pto() + path.rtt.pto_base();
6159 match path.open_status {
6160 paths::OpenStatus::Sent | paths::OpenStatus::Informed => {}
6161 paths::OpenStatus::Pending => {
6162 path.open_status = paths::OpenStatus::Sent;
6163 self.timers.set(
6164 Timer::PerPath(path_id, PathTimer::AbandonFromValidation),
6165 now + 3 * pto,
6166 self.qlog.with_time(now),
6167 );
6168 }
6169 }
6170
6171 self.timers.set(
6172 Timer::PerPath(path_id, PathTimer::PathChallengeLost),
6173 now + pto,
6174 self.qlog.with_time(now),
6175 );
6176
6177 if is_multipath_negotiated && !path.validated && path.pending_on_path_challenge {
6178 space.pending.path_status.insert(path_id);
6180 }
6181
6182 if space_id == SpaceId::Data
6185 && self
6186 .config
6187 .address_discovery_role
6188 .should_report(&self.peer_params.address_discovery_role)
6189 {
6190 let frame = frame::ObservedAddr::new(
6191 path.network_path.remote,
6192 self.next_observed_addr_seq_no,
6193 );
6194 if builder.frame_space_remaining() > frame.size() {
6195 builder.write_frame(frame, stats);
6196
6197 self.next_observed_addr_seq_no =
6198 self.next_observed_addr_seq_no.saturating_add(1u8);
6199 path.observed_addr_sent = true;
6200
6201 space.pending.observed_addr = false;
6202 }
6203 }
6204 }
6205
6206 if !scheduling_info.is_abandoned
6208 && space_id == SpaceId::Data
6209 && builder.frame_space_remaining() > frame::PathResponse::SIZE_BOUND
6210 && let Some(token) = path.path_responses.pop_on_path(path.network_path)
6211 {
6212 let response = frame::PathResponse(token);
6213 builder.write_frame(response, stats);
6214 builder.require_padding();
6215
6216 if space_id == SpaceId::Data
6220 && self
6221 .config
6222 .address_discovery_role
6223 .should_report(&self.peer_params.address_discovery_role)
6224 {
6225 let frame = frame::ObservedAddr::new(
6226 path.network_path.remote,
6227 self.next_observed_addr_seq_no,
6228 );
6229 if builder.frame_space_remaining() > frame.size() {
6230 builder.write_frame(frame, stats);
6231
6232 self.next_observed_addr_seq_no =
6233 self.next_observed_addr_seq_no.saturating_add(1u8);
6234 path.observed_addr_sent = true;
6235
6236 space.pending.observed_addr = false;
6237 }
6238 }
6239 }
6240
6241 while !scheduling_info.is_abandoned
6243 && scheduling_info.may_send_data
6244 && let Some(reach_out) = space
6245 .pending
6246 .reach_out
6247 .pop_if(|frame| builder.frame_space_remaining() >= frame.size())
6248 {
6249 builder.write_frame(reach_out, stats);
6250 }
6251
6252 if space_id == SpaceId::Data
6254 && scheduling_info.is_abandoned
6255 && scheduling_info.may_self_abandon
6256 && frame::PathAbandon::SIZE_BOUND <= builder.frame_space_remaining()
6257 && let Some(error_code) = space.pending.path_abandon.remove(&path_id)
6258 {
6259 let frame = frame::PathAbandon {
6260 path_id,
6261 error_code,
6262 };
6263 builder.write_frame(frame, stats);
6264
6265 self.remote_cids.remove(&path_id);
6268 }
6269 while space_id == SpaceId::Data
6270 && scheduling_info.may_send_data
6271 && frame::PathAbandon::SIZE_BOUND <= builder.frame_space_remaining()
6272 && let Some((abandoned_path_id, error_code)) = space.pending.path_abandon.pop_first()
6273 {
6274 let frame = frame::PathAbandon {
6275 path_id: abandoned_path_id,
6276 error_code,
6277 };
6278 builder.write_frame(frame, stats);
6279
6280 self.remote_cids.remove(&abandoned_path_id);
6283 }
6284
6285 if !scheduling_info.is_abandoned
6287 && scheduling_info.may_send_data
6288 && space_id == SpaceId::Data
6289 && self
6290 .config
6291 .address_discovery_role
6292 .should_report(&self.peer_params.address_discovery_role)
6293 && (!path.observed_addr_sent || space.pending.observed_addr)
6294 {
6295 let frame =
6296 frame::ObservedAddr::new(path.network_path.remote, self.next_observed_addr_seq_no);
6297 if builder.frame_space_remaining() > frame.size() {
6298 builder.write_frame(frame, stats);
6299
6300 self.next_observed_addr_seq_no = self.next_observed_addr_seq_no.saturating_add(1u8);
6301 path.observed_addr_sent = true;
6302
6303 space.pending.observed_addr = false;
6304 }
6305 }
6306
6307 while !is_0rtt
6309 && !scheduling_info.is_abandoned
6310 && scheduling_info.may_send_data
6311 && builder.frame_space_remaining() > frame::Crypto::SIZE_BOUND
6312 {
6313 let Some(mut frame) = space.pending.crypto.pop_front() else {
6314 break;
6315 };
6316
6317 let max_crypto_data_size = builder.frame_space_remaining()
6322 - 1 - VarInt::size(unsafe { VarInt::from_u64_unchecked(frame.offset) })
6324 - 2; let len = frame
6327 .data
6328 .len()
6329 .min(2usize.pow(14) - 1)
6330 .min(max_crypto_data_size);
6331
6332 let data = frame.data.split_to(len);
6333 let offset = frame.offset;
6334 let truncated = frame::Crypto { offset, data };
6335 builder.write_frame(truncated, stats);
6336
6337 if !frame.data.is_empty() {
6338 frame.offset += len as u64;
6339 space.pending.crypto.push_front(frame);
6340 }
6341 }
6342
6343 while space_id == SpaceId::Data
6345 && !scheduling_info.is_abandoned
6346 && scheduling_info.may_send_data
6347 && frame::PathStatusAvailable::SIZE_BOUND <= builder.frame_space_remaining()
6348 {
6349 let Some(path_id) = space.pending.path_status.pop_first() else {
6350 break;
6351 };
6352 let Some(path) = self.paths.get(&path_id).map(|path_state| &path_state.data) else {
6353 trace!(%path_id, "discarding queued path status for unknown path");
6354 continue;
6355 };
6356
6357 let seq = path.status.seq();
6358 match path.local_status() {
6359 PathStatus::Available => {
6360 let frame = frame::PathStatusAvailable {
6361 path_id,
6362 status_seq_no: seq,
6363 };
6364 builder.write_frame(frame, stats);
6365 }
6366 PathStatus::Backup => {
6367 let frame = frame::PathStatusBackup {
6368 path_id,
6369 status_seq_no: seq,
6370 };
6371 builder.write_frame(frame, stats);
6372 }
6373 }
6374 }
6375
6376 if space_id == SpaceId::Data
6378 && !scheduling_info.is_abandoned
6379 && scheduling_info.may_send_data
6380 && space.pending.max_path_id
6381 && frame::MaxPathId::SIZE_BOUND <= builder.frame_space_remaining()
6382 {
6383 let frame = frame::MaxPathId(self.local_max_path_id);
6384 builder.write_frame(frame, stats);
6385 space.pending.max_path_id = false;
6386 }
6387
6388 if space_id == SpaceId::Data
6390 && !scheduling_info.is_abandoned
6391 && scheduling_info.may_send_data
6392 && space.pending.paths_blocked
6393 && frame::PathsBlocked::SIZE_BOUND <= builder.frame_space_remaining()
6394 {
6395 let frame = frame::PathsBlocked(self.remote_max_path_id);
6396 builder.write_frame(frame, stats);
6397 space.pending.paths_blocked = false;
6398 }
6399
6400 while space_id == SpaceId::Data
6402 && !scheduling_info.is_abandoned
6403 && scheduling_info.may_send_data
6404 && frame::PathCidsBlocked::SIZE_BOUND <= builder.frame_space_remaining()
6405 {
6406 let Some(path_id) = space.pending.path_cids_blocked.pop_first() else {
6407 break;
6408 };
6409 let next_seq = match self.remote_cids.get(&path_id) {
6410 Some(cid_queue) => VarInt(cid_queue.active_seq() + 1),
6411 None => VarInt(0),
6412 };
6413 let frame = frame::PathCidsBlocked { path_id, next_seq };
6414 builder.write_frame(frame, stats);
6415 }
6416
6417 if space_id == SpaceId::Data
6419 && !scheduling_info.is_abandoned
6420 && scheduling_info.may_send_data
6421 {
6422 self.streams
6423 .write_control_frames(builder, &mut space.pending, stats);
6424 }
6425
6426 let cid_len = self
6428 .local_cid_state
6429 .values()
6430 .map(|cid_state| cid_state.cid_len())
6431 .max()
6432 .expect("some local CID state must exist");
6433 let new_cid_size_bound =
6434 frame::NewConnectionId::size_bound(is_multipath_negotiated, cid_len);
6435 while !scheduling_info.is_abandoned
6436 && scheduling_info.may_send_data
6437 && builder.frame_space_remaining() > new_cid_size_bound
6438 {
6439 let Some(issued) = space.pending.new_cids.pop() else {
6440 break;
6441 };
6442 let Some(cid_state) = self.local_cid_state.get(&issued.path_id) else {
6444 debug!(
6445 path = %issued.path_id, seq = issued.sequence,
6446 "dropping queued NEW_CONNECTION_ID for discarded path",
6447 );
6448 continue;
6449 };
6450 let retire_prior_to = cid_state.retire_prior_to();
6451
6452 let cid_path_id = match is_multipath_negotiated {
6453 true => Some(issued.path_id),
6454 false => {
6455 debug_assert_eq!(issued.path_id, PathId::ZERO);
6456 None
6457 }
6458 };
6459 let frame = frame::NewConnectionId {
6460 path_id: cid_path_id,
6461 sequence: issued.sequence,
6462 retire_prior_to,
6463 id: issued.id,
6464 reset_token: issued.reset_token,
6465 };
6466 builder.write_frame(frame, stats);
6467 }
6468
6469 let retire_cid_bound = frame::RetireConnectionId::size_bound(is_multipath_negotiated);
6471 while !scheduling_info.is_abandoned
6472 && scheduling_info.may_send_data
6473 && builder.frame_space_remaining() > retire_cid_bound
6474 {
6475 let (path_id, sequence) = match space.pending.retire_cids.pop() {
6476 Some((PathId::ZERO, seq)) if !is_multipath_negotiated => (None, seq),
6477 Some((path_id, seq)) => (Some(path_id), seq),
6478 None => break,
6479 };
6480 let frame = frame::RetireConnectionId { path_id, sequence };
6481 builder.write_frame(frame, stats);
6482 }
6483
6484 let mut sent_datagrams = false;
6486 while !scheduling_info.is_abandoned
6487 && scheduling_info.may_send_data
6488 && builder.frame_space_remaining() > Datagram::SIZE_BOUND
6489 && space_id == SpaceId::Data
6490 {
6491 match self.datagrams.write(builder, stats) {
6492 true => {
6493 sent_datagrams = true;
6494 }
6495 false => break,
6496 }
6497 }
6498 if self.datagrams.send_blocked && sent_datagrams {
6499 self.events.push_back(Event::DatagramsUnblocked);
6500 self.datagrams.send_blocked = false;
6501 }
6502
6503 let path = &mut self.paths.get_mut(&path_id).expect("known path").data;
6504
6505 if !scheduling_info.is_abandoned && scheduling_info.may_send_data {
6507 while let Some(network_path) = space.pending.new_tokens.pop() {
6508 debug_assert_eq!(space_id, SpaceId::Data);
6509 let ConnectionSide::Server { server_config } = &self.side else {
6510 panic!("NEW_TOKEN frames should not be enqueued by clients");
6511 };
6512
6513 if !network_path.is_probably_same_path(&path.network_path) {
6514 continue;
6519 }
6520
6521 let token = Token::new(
6522 TokenPayload::Validation {
6523 ip: network_path.remote.ip(),
6524 issued: server_config.time_source.now(),
6525 },
6526 &mut self.rng,
6527 );
6528 let new_token = NewToken {
6529 token: token.encode(&*server_config.token_key).into(),
6530 };
6531
6532 if builder.frame_space_remaining() < new_token.size() {
6533 space.pending.new_tokens.push(network_path);
6534 break;
6535 }
6536
6537 builder.write_frame(new_token, stats);
6538 builder.retransmits_mut().new_tokens.push(network_path);
6539 }
6540 }
6541
6542 while space_id == SpaceId::Data
6544 && !scheduling_info.is_abandoned
6545 && scheduling_info.may_send_data
6546 && frame::AddAddress::SIZE_BOUND <= builder.frame_space_remaining()
6547 {
6548 if let Some(added_address) = space.pending.add_address.pop_last() {
6549 builder.write_frame(added_address, stats);
6550 } else {
6551 break;
6552 }
6553 }
6554
6555 while space_id == SpaceId::Data
6557 && !scheduling_info.is_abandoned
6558 && scheduling_info.may_send_data
6559 && frame::RemoveAddress::SIZE_BOUND <= builder.frame_space_remaining()
6560 {
6561 if let Some(removed_address) = space.pending.remove_address.pop_last() {
6562 builder.write_frame(removed_address, stats);
6563 } else {
6564 break;
6565 }
6566 }
6567
6568 if !scheduling_info.is_abandoned
6570 && scheduling_info.may_send_data
6571 && space_id == SpaceId::Data
6572 {
6573 self.streams
6574 .write_stream_frames(builder, self.config.send_fairness, stats);
6575 }
6576 }
6577
6578 fn populate_acks<'a, 'b>(
6580 now: Instant,
6581 receiving_ecn: bool,
6582 path_id: PathId,
6583 space_id: SpaceId,
6584 space: &mut PacketSpace,
6585 is_multipath_negotiated: bool,
6586 builder: &mut PacketBuilder<'a, 'b>,
6587 stats: &mut FrameStats,
6588 space_has_keys: bool,
6589 ) {
6590 debug_assert!(space_has_keys, "tried to send ACK in 0-RTT");
6592
6593 debug_assert!(
6594 is_multipath_negotiated || path_id == PathId::ZERO,
6595 "Only PathId::ZERO allowed without multipath (have {path_id:?})"
6596 );
6597 if is_multipath_negotiated {
6598 debug_assert!(
6599 space_id == SpaceId::Data || path_id == PathId::ZERO,
6600 "path acks must be sent in 1RTT space (have {space_id:?})"
6601 );
6602 }
6603
6604 let pns = space.for_path(path_id);
6605 let ranges = pns.pending_acks.ranges();
6606 debug_assert!(!ranges.is_empty(), "can not send empty ACK range");
6607 let ecn = if receiving_ecn {
6608 Some(&pns.ecn_counters)
6609 } else {
6610 None
6611 };
6612
6613 let delay_micros = pns.pending_acks.ack_delay(now).as_micros() as u64;
6614 let ack_delay_exp = TransportParameters::default().ack_delay_exponent;
6616 let delay = delay_micros >> ack_delay_exp.into_inner();
6617
6618 if is_multipath_negotiated && space_id == SpaceId::Data {
6619 if !ranges.is_empty() {
6620 let frame = frame::PathAck::encoder(path_id, delay, ranges, ecn);
6621 builder.write_frame(frame, stats);
6622 }
6623 } else {
6624 builder.write_frame(frame::Ack::encoder(delay, ranges, ecn), stats);
6625 }
6626 }
6627
6628 fn close_common(&mut self) {
6629 trace!("connection closed");
6630 self.timers.reset();
6631 }
6632
6633 fn set_close_timer(&mut self, now: Instant) {
6634 let pto_max = self.max_pto_for_space(self.highest_space);
6637 self.timers.set(
6638 Timer::Conn(ConnTimer::Close),
6639 now + 3 * pto_max,
6640 self.qlog.with_time(now),
6641 );
6642 }
6643
6644 fn handle_peer_params(
6649 &mut self,
6650 params: TransportParameters,
6651 local_cid: ConnectionId,
6652 remote_cid: ConnectionId,
6653 now: Instant,
6654 ) -> Result<(), TransportError> {
6655 if Some(self.original_remote_cid) != params.initial_src_cid
6656 || (self.side.is_client()
6657 && (Some(self.initial_dst_cid) != params.original_dst_cid
6658 || self.retry_src_cid != params.retry_src_cid))
6659 {
6660 return Err(TransportError::TRANSPORT_PARAMETER_ERROR(
6661 "CID authentication failure",
6662 ));
6663 }
6664 if params.initial_max_path_id.is_some() && (local_cid.is_empty() || remote_cid.is_empty()) {
6665 return Err(TransportError::PROTOCOL_VIOLATION(
6666 "multipath must not use zero-length CIDs",
6667 ));
6668 }
6669
6670 self.set_peer_params(params);
6671 self.qlog.emit_peer_transport_params_received(self, now);
6672
6673 Ok(())
6674 }
6675
6676 fn set_peer_params(&mut self, params: TransportParameters) {
6677 self.streams.set_params(¶ms);
6678 self.idle_timeout =
6679 negotiate_max_idle_timeout(self.config.max_idle_timeout, Some(params.max_idle_timeout));
6680 trace!("negotiated max idle timeout {:?}", self.idle_timeout);
6681
6682 if let Some(ref info) = params.preferred_address {
6683 self.remote_cids.get_mut(&PathId::ZERO).expect("not yet abandoned").insert(frame::NewConnectionId {
6685 path_id: None,
6686 sequence: 1,
6687 id: info.connection_id,
6688 reset_token: info.stateless_reset_token,
6689 retire_prior_to: 0,
6690 })
6691 .expect(
6692 "preferred address CID is the first received, and hence is guaranteed to be legal",
6693 );
6694 let remote = self.path_data(PathId::ZERO).network_path.remote;
6695 self.set_reset_token(PathId::ZERO, remote, info.stateless_reset_token);
6696 }
6697 self.ack_frequency.peer_max_ack_delay = get_max_ack_delay(¶ms);
6698
6699 let mut multipath_enabled = false;
6700 if let (Some(local_max_path_id), Some(remote_max_path_id)) = (
6701 self.config.get_initial_max_path_id(),
6702 params.initial_max_path_id,
6703 ) {
6704 self.local_max_path_id = local_max_path_id;
6706 self.remote_max_path_id = remote_max_path_id;
6707 let initial_max_path_id = local_max_path_id.min(remote_max_path_id);
6708 debug!(%initial_max_path_id, "multipath negotiated");
6709 multipath_enabled = true;
6710 }
6711
6712 if let Some((max_locally_allowed_remote_addresses, max_remotely_allowed_remote_addresses)) =
6713 self.config
6714 .max_remote_nat_traversal_addresses
6715 .zip(params.max_remote_nat_traversal_addresses)
6716 {
6717 if multipath_enabled {
6718 let max_local_addresses = max_remotely_allowed_remote_addresses.get();
6719 let max_remote_addresses = max_locally_allowed_remote_addresses.get();
6720 self.n0_nat_traversal = n0_nat_traversal::State::new(
6721 max_remote_addresses,
6722 max_local_addresses,
6723 self.side(),
6724 );
6725 debug!(
6726 %max_remote_addresses, %max_local_addresses,
6727 "n0's nat traversal negotiated"
6728 );
6729 } else {
6730 debug!("n0 nat traversal enabled for both endpoints, but multipath is missing")
6731 }
6732 }
6733
6734 self.peer_params = params;
6735 let peer_max_udp_payload_size =
6736 u16::try_from(self.peer_params.max_udp_payload_size.into_inner()).unwrap_or(u16::MAX);
6737 self.path_data_mut(PathId::ZERO)
6738 .mtud
6739 .on_peer_max_udp_payload_size_received(peer_max_udp_payload_size);
6740 }
6741
6742 fn decrypt_packet(
6744 &mut self,
6745 now: Instant,
6746 path_id: PathId,
6747 packet: &mut Packet,
6748 ) -> Result<Option<u64>, Option<TransportError>> {
6749 let result = self
6750 .crypto_state
6751 .decrypt_packet_body(packet, path_id, &self.spaces)?;
6752
6753 let Some(result) = result else {
6754 return Ok(None);
6755 };
6756
6757 if result.outgoing_key_update_acked
6758 && let Some(prev) = self.crypto_state.prev_crypto.as_mut()
6759 {
6760 prev.end_packet = Some((result.packet_number, now));
6761 self.set_key_discard_timer(now, packet.header.space());
6762 }
6763
6764 if result.incoming_key_update {
6765 trace!("key update authenticated");
6766 self.crypto_state
6767 .update_keys(Some((result.packet_number, now)), true);
6768 self.set_key_discard_timer(now, packet.header.space());
6769 }
6770
6771 Ok(Some(result.packet_number))
6772 }
6773
6774 fn peer_supports_ack_frequency(&self) -> bool {
6775 self.peer_params.min_ack_delay.is_some()
6776 }
6777
6778 pub(crate) fn immediate_ack(&mut self, path_id: PathId) {
6783 debug_assert_eq!(
6784 self.highest_space,
6785 SpaceKind::Data,
6786 "immediate ack must be written in the data space"
6787 );
6788 self.spaces[SpaceId::Data]
6789 .for_path(path_id)
6790 .immediate_ack_pending = true;
6791 }
6792
6793 #[cfg(test)]
6795 pub(crate) fn decode_packet(&self, event: &ConnectionEvent) -> Option<Vec<u8>> {
6796 let ConnectionEventInner::Datagram(DatagramConnectionEvent {
6797 path_id,
6798 first_decode,
6799 remaining,
6800 ..
6801 }) = &event.0
6802 else {
6803 return None;
6804 };
6805
6806 if remaining.is_some() {
6807 panic!("Packets should never be coalesced in tests");
6808 }
6809
6810 let decrypted_header = self
6811 .crypto_state
6812 .unprotect_header(first_decode.clone(), self.peer_params.stateless_reset_token)?;
6813
6814 let mut packet = decrypted_header.packet?;
6815 self.crypto_state
6816 .decrypt_packet_body(&mut packet, *path_id, &self.spaces)
6817 .ok()?;
6818
6819 Some(packet.payload.to_vec())
6820 }
6821
6822 #[cfg(test)]
6825 pub(crate) fn bytes_in_flight(&self) -> u64 {
6826 self.path_data(PathId::ZERO).in_flight.bytes
6828 }
6829
6830 #[cfg(test)]
6832 pub(crate) fn congestion_window(&self) -> u64 {
6833 let path = self.path_data(PathId::ZERO);
6834 path.congestion
6835 .window()
6836 .saturating_sub(path.in_flight.bytes)
6837 }
6838
6839 #[cfg(test)]
6841 pub(crate) fn is_idle(&self) -> bool {
6842 let current_timers = self.timers.values();
6843 current_timers
6844 .into_iter()
6845 .filter(|(timer, _)| {
6846 !matches!(
6847 timer,
6848 Timer::Conn(ConnTimer::KeepAlive)
6849 | Timer::PerPath(_, PathTimer::PathKeepAlive)
6850 | Timer::Conn(ConnTimer::PushNewCid)
6851 | Timer::Conn(ConnTimer::KeyDiscard)
6852 )
6853 })
6854 .min_by_key(|(_, time)| *time)
6855 .is_none_or(|(timer, _)| {
6856 matches!(
6857 timer,
6858 Timer::Conn(ConnTimer::Idle) | Timer::PerPath(_, PathTimer::PathIdle)
6859 )
6860 })
6861 }
6862
6863 #[cfg(test)]
6865 pub(crate) fn using_ecn(&self) -> bool {
6866 self.path_data(PathId::ZERO).sending_ecn
6867 }
6868
6869 #[cfg(test)]
6871 pub(crate) fn total_recvd(&self) -> u64 {
6872 self.path_data(PathId::ZERO).total_recvd
6873 }
6874
6875 #[cfg(test)]
6876 pub(crate) fn active_local_cid_seq(&self) -> (u64, u64) {
6877 self.local_cid_state
6878 .get(&PathId::ZERO)
6879 .unwrap()
6880 .active_seq()
6881 }
6882
6883 #[cfg(test)]
6884 #[track_caller]
6885 pub(crate) fn active_local_path_cid_seq(&self, path_id: u32) -> (u64, u64) {
6886 self.local_cid_state
6887 .get(&PathId(path_id))
6888 .unwrap()
6889 .active_seq()
6890 }
6891
6892 #[cfg(test)]
6895 pub(crate) fn rotate_local_cid(&mut self, v: u64, now: Instant) {
6896 let n = self
6897 .local_cid_state
6898 .get_mut(&PathId::ZERO)
6899 .unwrap()
6900 .assign_retire_seq(v);
6901 debug_assert!(!self.state.is_drained()); self.endpoint_events
6903 .push_back(EndpointEventInner::NeedIdentifiers(PathId::ZERO, now, n));
6904 }
6905
6906 #[cfg(test)]
6908 pub(crate) fn active_remote_cid_seq(&self) -> u64 {
6909 self.remote_cids.get(&PathId::ZERO).unwrap().active_seq()
6910 }
6911
6912 #[cfg(test)]
6914 pub(crate) fn path_mtu(&self, path_id: PathId) -> u16 {
6915 self.path_data(path_id).current_mtu()
6916 }
6917
6918 #[cfg(test)]
6920 pub(crate) fn trigger_path_validation(&mut self) {
6921 for path in self.paths.values_mut() {
6922 path.data.pending_on_path_challenge = true;
6923 }
6924 }
6925
6926 #[cfg(test)]
6928 pub fn simulate_protocol_violation(&mut self, now: Instant) {
6929 if !self.state.is_closed() {
6930 self.state
6931 .move_to_closed(TransportError::PROTOCOL_VIOLATION("simulated violation"));
6932 self.close_common();
6933 if !self.state.is_drained() {
6934 self.set_close_timer(now);
6935 }
6936 self.connection_close_pending = true;
6937 }
6938 }
6939
6940 fn can_send_1rtt(&self, path_id: PathId, max_size: usize) -> SendableFrames {
6951 let space_specific = self.paths.get(&path_id).is_some_and(|path| {
6952 path.data.pending_on_path_challenge || !path.data.path_responses.is_empty()
6953 });
6954
6955 let other = self.streams.can_send_stream_data()
6957 || self
6958 .datagrams
6959 .outgoing
6960 .front()
6961 .is_some_and(|x| x.size(true) <= max_size);
6962
6963 SendableFrames {
6965 acks: false,
6966 close: false,
6967 space_specific,
6968 other,
6969 }
6970 }
6971
6972 fn kill(&mut self, reason: ConnectionError) {
6974 self.close_common();
6975 self.state.move_to_drained(Some(reason));
6976 self.endpoint_events.push_back(EndpointEventInner::Drained);
6979 }
6980
6981 pub fn current_mtu(&self) -> u16 {
6988 self.paths
6989 .iter()
6990 .filter(|&(path_id, _path_state)| !self.abandoned_paths.contains(path_id))
6991 .map(|(_path_id, path_state)| path_state.data.current_mtu())
6992 .min()
6993 .unwrap_or(INITIAL_MTU)
6994 }
6995
6996 fn predict_1rtt_overhead(&mut self, pn: u64, path: PathId) -> usize {
7003 let pn_len = PacketNumber::new(
7004 pn,
7005 self.spaces[SpaceId::Data]
7006 .for_path(path)
7007 .largest_acked_packet_pn
7008 .unwrap_or(0),
7009 )
7010 .len();
7011
7012 1 + self
7014 .remote_cids
7015 .get(&path)
7016 .map(|cids| cids.active().len())
7017 .unwrap_or(20) + pn_len
7019 + self.tag_len_1rtt()
7020 }
7021
7022 fn predict_1rtt_overhead_no_pn(&self) -> usize {
7023 let pn_len = 4;
7024
7025 let cid_len = self
7026 .remote_cids
7027 .values()
7028 .map(|cids| cids.active().len())
7029 .max()
7030 .unwrap_or(20); 1 + cid_len + pn_len + self.tag_len_1rtt()
7034 }
7035
7036 fn tag_len_1rtt(&self) -> usize {
7037 let packet_crypto = self
7039 .crypto_state
7040 .encryption_keys(SpaceKind::Data, self.side.side())
7041 .map(|(_header, packet, _level)| packet);
7042 packet_crypto.map_or(16, |x| x.tag_len())
7046 }
7047
7048 fn on_path_validated(&mut self, path_id: PathId) {
7050 self.path_data_mut(path_id).validated = true;
7051 let ConnectionSide::Server { server_config } = &self.side else {
7052 return;
7053 };
7054 let network_path = self.path_data(path_id).network_path;
7055 let new_tokens = &mut self.spaces[SpaceId::Data as usize].pending.new_tokens;
7056 new_tokens.clear();
7057 for _ in 0..server_config.validation_token.sent {
7058 new_tokens.push(network_path);
7059 }
7060 }
7061
7062 fn on_path_status(&mut self, path_id: PathId, status: PathStatus, status_seq_no: VarInt) {
7064 if let Some(path) = self.paths.get_mut(&path_id) {
7065 path.data.status.remote_update(status, status_seq_no);
7066 } else {
7067 debug!("PATH_STATUS_AVAILABLE received unknown path {:?}", path_id);
7068 }
7069 self.events.push_back(
7070 PathEvent::RemoteStatus {
7071 id: path_id,
7072 status,
7073 }
7074 .into(),
7075 );
7076 }
7077
7078 fn max_path_id(&self) -> Option<PathId> {
7087 if self.is_multipath_negotiated() {
7088 Some(self.remote_max_path_id.min(self.local_max_path_id))
7089 } else {
7090 None
7091 }
7092 }
7093
7094 fn is_ipv6(&self) -> bool {
7099 self.paths
7100 .values()
7101 .any(|p| p.data.network_path.remote.is_ipv6())
7102 }
7103
7104 pub fn add_nat_traversal_address(
7106 &mut self,
7107 address: SocketAddr,
7108 ) -> Result<(), n0_nat_traversal::Error> {
7109 if let Some(added) = self.n0_nat_traversal.add_local_address(address)? {
7110 self.spaces[SpaceId::Data].pending.add_address.insert(added);
7111 };
7112 Ok(())
7113 }
7114
7115 pub fn remove_nat_traversal_address(
7119 &mut self,
7120 address: SocketAddr,
7121 ) -> Result<(), n0_nat_traversal::Error> {
7122 if let Some(removed) = self.n0_nat_traversal.remove_local_address(address)? {
7123 self.spaces[SpaceId::Data]
7124 .pending
7125 .remove_address
7126 .insert(removed);
7127 }
7128 Ok(())
7129 }
7130
7131 pub fn get_local_nat_traversal_addresses(
7133 &self,
7134 ) -> Result<Vec<SocketAddr>, n0_nat_traversal::Error> {
7135 self.n0_nat_traversal.get_local_nat_traversal_addresses()
7136 }
7137
7138 pub fn get_remote_nat_traversal_addresses(
7140 &self,
7141 ) -> Result<Vec<SocketAddr>, n0_nat_traversal::Error> {
7142 Ok(self
7143 .n0_nat_traversal
7144 .client_side()?
7145 .get_remote_nat_traversal_addresses())
7146 }
7147
7148 pub fn initiate_nat_traversal_round(
7160 &mut self,
7161 now: Instant,
7162 ) -> Result<Vec<SocketAddr>, n0_nat_traversal::Error> {
7163 if self.state.is_closed() {
7164 return Err(n0_nat_traversal::Error::Closed);
7165 }
7166
7167 let ipv6 = self.is_ipv6();
7168 let client_state = self.n0_nat_traversal.client_side_mut()?;
7169 let (mut reach_out_frames, probed_addrs) =
7170 client_state.initiate_nat_traversal_round(ipv6)?;
7171 if let Some(delay) = self.n0_nat_traversal.retry_delay(self.config.initial_rtt) {
7172 self.timers.set(
7173 Timer::Conn(ConnTimer::NatTraversalProbeRetry),
7174 now + delay,
7175 self.qlog.with_time(now),
7176 );
7177 }
7178
7179 self.spaces[SpaceId::Data]
7180 .pending
7181 .reach_out
7182 .append(&mut reach_out_frames);
7183
7184 Ok(probed_addrs)
7185 }
7186
7187 fn is_handshake_confirmed(&self) -> bool {
7196 !self.is_handshaking() && !self.crypto_state.has_keys(EncryptionLevel::Handshake)
7197 }
7198}
7199
7200impl fmt::Debug for Connection {
7201 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7202 f.debug_struct("Connection")
7203 .field("handshake_cid", &self.handshake_cid)
7204 .finish()
7205 }
7206}
7207
7208pub trait NetworkChangeHint: std::fmt::Debug + 'static {
7210 fn is_path_recoverable(&self, path_id: PathId, network_path: FourTuple) -> bool;
7219}
7220
7221#[derive(Debug)]
7223enum PollPathSpaceStatus {
7224 NothingToSend {
7226 congestion_blocked: bool,
7228 },
7229 WrotePacket {
7231 last_packet_number: u64,
7233 pad_datagram: PadDatagram,
7247 },
7248 Send {
7255 last_packet_number: u64,
7257 },
7258}
7259
7260#[derive(Debug, Copy, Clone)]
7266struct PathSchedulingInfo {
7267 is_abandoned: bool,
7273 may_send_data: bool,
7291 may_send_close: bool,
7297 may_self_abandon: bool,
7298}
7299
7300#[derive(Debug, Copy, Clone, PartialEq, Eq)]
7301enum PathBlocked {
7302 No,
7303 AntiAmplification,
7304 Congestion,
7305 Pacing,
7306}
7307
7308enum ConnectionSide {
7310 Client {
7311 token: Bytes,
7313 token_store: Arc<dyn TokenStore>,
7314 server_name: String,
7315 },
7316 Server {
7317 server_config: Arc<ServerConfig>,
7318 },
7319}
7320
7321impl ConnectionSide {
7322 fn is_client(&self) -> bool {
7323 self.side().is_client()
7324 }
7325
7326 fn is_server(&self) -> bool {
7327 self.side().is_server()
7328 }
7329
7330 fn side(&self) -> Side {
7331 match *self {
7332 Self::Client { .. } => Side::Client,
7333 Self::Server { .. } => Side::Server,
7334 }
7335 }
7336}
7337
7338impl From<SideArgs> for ConnectionSide {
7339 fn from(side: SideArgs) -> Self {
7340 match side {
7341 SideArgs::Client {
7342 token_store,
7343 server_name,
7344 } => Self::Client {
7345 token: token_store.take(&server_name).unwrap_or_default(),
7346 token_store,
7347 server_name,
7348 },
7349 SideArgs::Server {
7350 server_config,
7351 pref_addr_cid: _,
7352 path_validated: _,
7353 } => Self::Server { server_config },
7354 }
7355 }
7356}
7357
7358pub(crate) enum SideArgs {
7360 Client {
7361 token_store: Arc<dyn TokenStore>,
7362 server_name: String,
7363 },
7364 Server {
7365 server_config: Arc<ServerConfig>,
7366 pref_addr_cid: Option<ConnectionId>,
7367 path_validated: bool,
7368 },
7369}
7370
7371impl SideArgs {
7372 pub(crate) fn pref_addr_cid(&self) -> Option<ConnectionId> {
7373 match *self {
7374 Self::Client { .. } => None,
7375 Self::Server { pref_addr_cid, .. } => pref_addr_cid,
7376 }
7377 }
7378
7379 pub(crate) fn path_validated(&self) -> bool {
7380 match *self {
7381 Self::Client { .. } => true,
7382 Self::Server { path_validated, .. } => path_validated,
7383 }
7384 }
7385
7386 pub(crate) fn side(&self) -> Side {
7387 match *self {
7388 Self::Client { .. } => Side::Client,
7389 Self::Server { .. } => Side::Server,
7390 }
7391 }
7392}
7393
7394#[derive(Debug, Error, Clone, PartialEq, Eq)]
7396pub enum ConnectionError {
7397 #[error("peer doesn't implement any supported version")]
7399 VersionMismatch,
7400 #[error(transparent)]
7402 TransportError(#[from] TransportError),
7403 #[error("aborted by peer: {0}")]
7405 ConnectionClosed(frame::ConnectionClose),
7406 #[error("closed by peer: {0}")]
7408 ApplicationClosed(frame::ApplicationClose),
7409 #[error("reset by peer")]
7411 Reset,
7412 #[error("timed out")]
7418 TimedOut,
7419 #[error("closed")]
7421 LocallyClosed,
7422 #[error("CIDs exhausted")]
7426 CidsExhausted,
7427}
7428
7429impl From<Close> for ConnectionError {
7430 fn from(x: Close) -> Self {
7431 match x {
7432 Close::Connection(reason) => Self::ConnectionClosed(reason),
7433 Close::Application(reason) => Self::ApplicationClosed(reason),
7434 }
7435 }
7436}
7437
7438impl From<ConnectionError> for io::Error {
7440 fn from(x: ConnectionError) -> Self {
7441 use ConnectionError::*;
7442 let kind = match x {
7443 TimedOut => io::ErrorKind::TimedOut,
7444 Reset => io::ErrorKind::ConnectionReset,
7445 ApplicationClosed(_) | ConnectionClosed(_) => io::ErrorKind::ConnectionAborted,
7446 TransportError(_) | VersionMismatch | LocallyClosed | CidsExhausted => {
7447 io::ErrorKind::Other
7448 }
7449 };
7450 Self::new(kind, x)
7451 }
7452}
7453
7454#[derive(Debug, Error, PartialEq, Eq, Clone, Copy)]
7457pub enum PathError {
7458 #[error("multipath extension not negotiated")]
7460 MultipathNotNegotiated,
7461 #[error("the server side may not open a path")]
7463 ServerSideNotAllowed,
7464 #[error("maximum number of concurrent paths reached")]
7466 MaxPathIdReached,
7467 #[error("remoted CIDs exhausted")]
7469 RemoteCidsExhausted,
7470 #[error("path validation failed")]
7472 ValidationFailed,
7473 #[error("invalid remote address")]
7475 InvalidRemoteAddress(SocketAddr),
7476}
7477
7478#[derive(Debug, Error, Clone, Eq, PartialEq)]
7480pub enum ClosePathError {
7481 #[error("Multipath extension not negotiated")]
7483 MultipathNotNegotiated,
7484 #[error("closed path")]
7486 ClosedPath,
7487 #[error("last open path")]
7491 LastOpenPath,
7492}
7493
7494#[derive(Debug, Error, Clone, Copy)]
7496#[error("Multipath extension not negotiated")]
7497pub struct MultipathNotNegotiated {
7498 _private: (),
7499}
7500
7501#[derive(Debug)]
7503pub enum Event {
7504 HandshakeDataReady,
7506 Connected,
7508 HandshakeConfirmed,
7510 ConnectionLost {
7517 reason: ConnectionError,
7519 },
7520 Stream(StreamEvent),
7522 DatagramReceived,
7524 DatagramsUnblocked,
7526 Path(PathEvent),
7528 NatTraversal(n0_nat_traversal::Event),
7530}
7531
7532impl From<PathEvent> for Event {
7533 fn from(source: PathEvent) -> Self {
7534 Self::Path(source)
7535 }
7536}
7537
7538fn get_max_ack_delay(params: &TransportParameters) -> Duration {
7539 Duration::from_micros(params.max_ack_delay.0 * 1000)
7540}
7541
7542const MAX_BACKOFF_EXPONENT: u32 = 16;
7544
7545const MAX_PTO_INTERVAL: Duration = Duration::from_secs(2);
7549
7550const MIN_IDLE_FOR_FAST_PTO: Duration = Duration::from_secs(25);
7552
7553const MAX_PTO_FAST_INTERVAL: Duration = Duration::from_secs(1);
7558
7559const SLOW_RTT_THRESHOLD: Duration =
7564 Duration::from_millis((MAX_PTO_INTERVAL.as_millis() as u64 * 2) / 3);
7565
7566const MIN_PACKET_SPACE: usize = MAX_HANDSHAKE_OR_0RTT_HEADER_SIZE + 32;
7574
7575const MAX_HANDSHAKE_OR_0RTT_HEADER_SIZE: usize =
7581 1 + 4 + 1 + MAX_CID_SIZE + 1 + MAX_CID_SIZE + VarInt::from_u32(u16::MAX as u32).size() + 4;
7582
7583#[derive(Default)]
7584struct SentFrames {
7585 retransmits: ThinRetransmits,
7586 largest_acked: FxHashMap<PathId, u64>,
7588 stream_frames: StreamMetaVec,
7589 non_retransmits: bool,
7591 requires_padding: bool,
7593}
7594
7595impl SentFrames {
7596 fn is_ack_only(&self, streams: &StreamsState) -> bool {
7598 !self.largest_acked.is_empty()
7599 && !self.non_retransmits
7600 && self.stream_frames.is_empty()
7601 && self.retransmits.is_empty(streams)
7602 }
7603
7604 fn retransmits_mut(&mut self) -> &mut Retransmits {
7605 self.retransmits.get_or_create()
7606 }
7607
7608 fn record_sent_frame(&mut self, frame: frame::EncodableFrame<'_>) {
7609 use frame::EncodableFrame::*;
7610 match frame {
7611 PathAck(path_ack_encoder) => {
7612 if let Some(max) = path_ack_encoder.ranges.max() {
7613 self.largest_acked.insert(path_ack_encoder.path_id, max);
7614 }
7615 }
7616 Ack(ack_encoder) => {
7617 if let Some(max) = ack_encoder.ranges.max() {
7618 self.largest_acked.insert(PathId::ZERO, max);
7619 }
7620 }
7621 Close(_) => { }
7622 PathResponse(_) => self.non_retransmits = true,
7623 HandshakeDone(_) => self.retransmits_mut().handshake_done = true,
7624 ReachOut(frame) => self.retransmits_mut().reach_out.push(frame),
7625 ObservedAddr(_) => self.retransmits_mut().observed_addr = true,
7626 Ping(_) => self.non_retransmits = true,
7627 ImmediateAck(_) => self.non_retransmits = true,
7628 AckFrequency(_) => self.retransmits_mut().ack_frequency = true,
7629 PathChallenge(_) => self.non_retransmits = true,
7630 Crypto(crypto) => self.retransmits_mut().crypto.push_back(crypto),
7631 PathAbandon(path_abandon) => {
7632 self.retransmits_mut()
7633 .path_abandon
7634 .entry(path_abandon.path_id)
7635 .or_insert(path_abandon.error_code);
7636 }
7637 PathStatusAvailable(frame::PathStatusAvailable { path_id, .. })
7638 | PathStatusBackup(frame::PathStatusBackup { path_id, .. }) => {
7639 self.retransmits_mut().path_status.insert(path_id);
7640 }
7641 MaxPathId(_) => self.retransmits_mut().max_path_id = true,
7642 PathsBlocked(_) => self.retransmits_mut().paths_blocked = true,
7643 PathCidsBlocked(path_cids_blocked) => {
7644 self.retransmits_mut()
7645 .path_cids_blocked
7646 .insert(path_cids_blocked.path_id);
7647 }
7648 ResetStream(reset) => self
7649 .retransmits_mut()
7650 .reset_stream
7651 .push((reset.id, reset.error_code)),
7652 StopSending(stop_sending) => self.retransmits_mut().stop_sending.push(stop_sending),
7653 NewConnectionId(new_cid) => self.retransmits_mut().new_cids.push(new_cid.issued()),
7654 RetireConnectionId(retire_cid) => self
7655 .retransmits_mut()
7656 .retire_cids
7657 .push((retire_cid.path_id.unwrap_or_default(), retire_cid.sequence)),
7658 Datagram(_) => self.non_retransmits = true,
7659 NewToken(_) => {}
7660 AddAddress(add_address) => {
7661 self.retransmits_mut().add_address.insert(add_address);
7662 }
7663 RemoveAddress(remove_address) => {
7664 self.retransmits_mut().remove_address.insert(remove_address);
7665 }
7666 StreamMeta(stream_meta_encoder) => self.stream_frames.push(stream_meta_encoder.meta),
7667 MaxData(_) => self.retransmits_mut().max_data = true,
7668 MaxStreamData(max) => {
7669 self.retransmits_mut().max_stream_data.insert(max.id);
7670 }
7671 MaxStreams(max_streams) => {
7672 self.retransmits_mut().max_stream_id[max_streams.dir as usize] = true
7673 }
7674 StreamsBlocked(streams_blocked) => {
7675 self.retransmits_mut().streams_blocked[streams_blocked.dir as usize] = true
7676 }
7677 }
7678 }
7679}
7680
7681fn negotiate_max_idle_timeout(x: Option<VarInt>, y: Option<VarInt>) -> Option<Duration> {
7689 match (x, y) {
7690 (Some(VarInt(0)) | None, Some(VarInt(0)) | None) => None,
7691 (Some(VarInt(0)) | None, Some(y)) => Some(Duration::from_millis(y.0)),
7692 (Some(x), Some(VarInt(0)) | None) => Some(Duration::from_millis(x.0)),
7693 (Some(x), Some(y)) => Some(Duration::from_millis(cmp::min(x, y).0)),
7694 }
7695}
7696
7697#[cfg(test)]
7698mod tests {
7699 use super::*;
7700
7701 #[test]
7702 fn negotiate_max_idle_timeout_commutative() {
7703 let test_params = [
7704 (None, None, None),
7705 (None, Some(VarInt(0)), None),
7706 (None, Some(VarInt(2)), Some(Duration::from_millis(2))),
7707 (Some(VarInt(0)), Some(VarInt(0)), None),
7708 (
7709 Some(VarInt(2)),
7710 Some(VarInt(0)),
7711 Some(Duration::from_millis(2)),
7712 ),
7713 (
7714 Some(VarInt(1)),
7715 Some(VarInt(4)),
7716 Some(Duration::from_millis(1)),
7717 ),
7718 ];
7719
7720 for (left, right, result) in test_params {
7721 assert_eq!(negotiate_max_idle_timeout(left, right), result);
7722 assert_eq!(negotiate_max_idle_timeout(right, left), result);
7723 }
7724 }
7725}