1use std::{
2 cmp,
3 collections::{BTreeMap, VecDeque, btree_map},
4 convert::TryFrom,
5 fmt, io, mem,
6 net::{IpAddr, SocketAddr},
7 num::NonZeroU32,
8 ops::Not,
9 sync::Arc,
10};
11
12use bytes::{BufMut, Bytes, BytesMut};
13use frame::StreamMetaVec;
14
15use rand::{Rng, SeedableRng, rngs::StdRng};
16use rustc_hash::{FxHashMap, FxHashSet};
17use thiserror::Error;
18use tracing::{debug, error, trace, trace_span, warn};
19
20use crate::{
21 Dir, Duration, EndpointConfig, Frame, INITIAL_MTU, Instant, MAX_CID_SIZE, MAX_STREAM_COUNT,
22 MIN_INITIAL_SIZE, Side, StreamId, TIMER_GRANULARITY, TokenStore, Transmit, TransportError,
23 TransportErrorCode, VarInt,
24 cid_generator::ConnectionIdGenerator,
25 cid_queue::CidQueue,
26 coding::BufMutExt,
27 config::{ServerConfig, TransportConfig},
28 congestion::Controller,
29 connection::{
30 qlog::{QlogRecvPacket, QlogSentPacket, QlogSink},
31 spaces::LostPacket,
32 timer::{ConnTimer, PathTimer},
33 },
34 crypto::{self, KeyPair, Keys, PacketKey},
35 frame::{self, Close, Datagram, FrameStruct, NewToken, ObservedAddr},
36 iroh_hp,
37 packet::{
38 FixedLengthConnectionIdParser, Header, InitialHeader, InitialPacket, LongType, Packet,
39 PacketNumber, PartialDecode, SpaceId,
40 },
41 range_set::ArrayRangeSet,
42 shared::{
43 ConnectionEvent, ConnectionEventInner, ConnectionId, DatagramConnectionEvent, EcnCodepoint,
44 EndpointEvent, EndpointEventInner,
45 },
46 token::{ResetToken, Token, TokenPayload},
47 transport_parameters::TransportParameters,
48};
49
50mod ack_frequency;
51use ack_frequency::AckFrequencyState;
52
53mod assembler;
54pub use assembler::Chunk;
55
56mod cid_state;
57use cid_state::CidState;
58
59mod datagrams;
60use datagrams::DatagramState;
61pub use datagrams::{Datagrams, SendDatagramError};
62
63mod mtud;
64mod pacing;
65
66mod packet_builder;
67use packet_builder::{PacketBuilder, PadDatagram};
68
69mod packet_crypto;
70use packet_crypto::{PrevCrypto, ZeroRttCrypto};
71
72mod paths;
73pub use paths::{ClosedPath, PathEvent, PathId, PathStatus, RttEstimator, SetPathStatusError};
74use paths::{PathData, PathState};
75
76pub(crate) mod qlog;
77
78mod send_buffer;
79
80mod spaces;
81#[cfg(fuzzing)]
82pub use spaces::Retransmits;
83#[cfg(not(fuzzing))]
84use spaces::Retransmits;
85use spaces::{PacketSpace, SendableFrames, SentPacket, ThinRetransmits};
86
87mod stats;
88pub use stats::{ConnectionStats, FrameStats, PathStats, UdpStats};
89
90mod streams;
91#[cfg(fuzzing)]
92pub use streams::StreamsState;
93#[cfg(not(fuzzing))]
94use streams::StreamsState;
95pub use streams::{
96 Chunks, ClosedStream, FinishError, ReadError, ReadableError, RecvStream, SendStream,
97 ShouldTransmit, StreamEvent, Streams, WriteError, Written,
98};
99
100mod timer;
101use timer::{Timer, TimerTable};
102
103mod transmit_buf;
104use transmit_buf::TransmitBuf;
105
106mod state;
107
108#[cfg(not(fuzzing))]
109use state::State;
110#[cfg(fuzzing)]
111pub use state::State;
112use state::StateType;
113
114pub struct Connection {
154 endpoint_config: Arc<EndpointConfig>,
155 config: Arc<TransportConfig>,
156 rng: StdRng,
157 crypto: Box<dyn crypto::Session>,
158 handshake_cid: ConnectionId,
160 rem_handshake_cid: ConnectionId,
162 local_ip: Option<IpAddr>,
165 paths: BTreeMap<PathId, PathState>,
171 path_counter: u64,
175 allow_mtud: bool,
177 state: State,
178 side: ConnectionSide,
179 zero_rtt_enabled: bool,
181 zero_rtt_crypto: Option<ZeroRttCrypto>,
183 key_phase: bool,
184 key_phase_size: u64,
186 peer_params: TransportParameters,
188 orig_rem_cid: ConnectionId,
190 initial_dst_cid: ConnectionId,
192 retry_src_cid: Option<ConnectionId>,
195 events: VecDeque<Event>,
197 endpoint_events: VecDeque<EndpointEventInner>,
198 spin_enabled: bool,
200 spin: bool,
202 spaces: [PacketSpace; 3],
204 highest_space: SpaceId,
206 prev_crypto: Option<PrevCrypto>,
208 next_crypto: Option<KeyPair<Box<dyn PacketKey>>>,
213 accepted_0rtt: bool,
214 permit_idle_reset: bool,
216 idle_timeout: Option<Duration>,
218 timers: TimerTable,
219 authentication_failures: u64,
221
222 close: bool,
227
228 ack_frequency: AckFrequencyState,
232
233 receiving_ecn: bool,
238 total_authed_packets: u64,
240 app_limited: bool,
243
244 next_observed_addr_seq_no: VarInt,
249
250 streams: StreamsState,
251 rem_cids: FxHashMap<PathId, CidQueue>,
257 local_cid_state: FxHashMap<PathId, CidState>,
264 datagrams: DatagramState,
266 stats: ConnectionStats,
268 path_stats: FxHashMap<PathId, PathStats>,
270 version: u32,
272
273 max_concurrent_paths: NonZeroU32,
282 local_max_path_id: PathId,
297 remote_max_path_id: PathId,
303 max_path_id_with_cids: PathId,
309 abandoned_paths: FxHashSet<PathId>,
317
318 iroh_hp: iroh_hp::State,
319 qlog: QlogSink,
320}
321
322impl Connection {
323 pub(crate) fn new(
324 endpoint_config: Arc<EndpointConfig>,
325 config: Arc<TransportConfig>,
326 init_cid: ConnectionId,
327 loc_cid: ConnectionId,
328 rem_cid: ConnectionId,
329 remote: SocketAddr,
330 local_ip: Option<IpAddr>,
331 crypto: Box<dyn crypto::Session>,
332 cid_gen: &dyn ConnectionIdGenerator,
333 now: Instant,
334 version: u32,
335 allow_mtud: bool,
336 rng_seed: [u8; 32],
337 side_args: SideArgs,
338 qlog: QlogSink,
339 ) -> Self {
340 let pref_addr_cid = side_args.pref_addr_cid();
341 let path_validated = side_args.path_validated();
342 let connection_side = ConnectionSide::from(side_args);
343 let side = connection_side.side();
344 let mut rng = StdRng::from_seed(rng_seed);
345 let initial_space = {
346 let mut space = PacketSpace::new(now, SpaceId::Initial, &mut rng);
347 space.crypto = Some(crypto.initial_keys(init_cid, side));
348 space
349 };
350 let handshake_space = PacketSpace::new(now, SpaceId::Handshake, &mut rng);
351 #[cfg(test)]
352 let data_space = match config.deterministic_packet_numbers {
353 true => PacketSpace::new_deterministic(now, SpaceId::Data),
354 false => PacketSpace::new(now, SpaceId::Data, &mut rng),
355 };
356 #[cfg(not(test))]
357 let data_space = PacketSpace::new(now, SpaceId::Data, &mut rng);
358 let state = State::handshake(state::Handshake {
359 rem_cid_set: side.is_server(),
360 expected_token: Bytes::new(),
361 client_hello: None,
362 allow_server_migration: side.is_client(),
363 });
364 let local_cid_state = FxHashMap::from_iter([(
365 PathId::ZERO,
366 CidState::new(
367 cid_gen.cid_len(),
368 cid_gen.cid_lifetime(),
369 now,
370 if pref_addr_cid.is_some() { 2 } else { 1 },
371 ),
372 )]);
373
374 let mut path = PathData::new(remote, allow_mtud, None, 0, now, &config);
375 path.open = true;
377 let mut this = Self {
378 endpoint_config,
379 crypto,
380 handshake_cid: loc_cid,
381 rem_handshake_cid: rem_cid,
382 local_cid_state,
383 paths: BTreeMap::from_iter([(
384 PathId::ZERO,
385 PathState {
386 data: path,
387 prev: None,
388 },
389 )]),
390 path_counter: 0,
391 allow_mtud,
392 local_ip,
393 state,
394 side: connection_side,
395 zero_rtt_enabled: false,
396 zero_rtt_crypto: None,
397 key_phase: false,
398 key_phase_size: rng.random_range(10..1000),
405 peer_params: TransportParameters::default(),
406 orig_rem_cid: rem_cid,
407 initial_dst_cid: init_cid,
408 retry_src_cid: None,
409 events: VecDeque::new(),
410 endpoint_events: VecDeque::new(),
411 spin_enabled: config.allow_spin && rng.random_ratio(7, 8),
412 spin: false,
413 spaces: [initial_space, handshake_space, data_space],
414 highest_space: SpaceId::Initial,
415 prev_crypto: None,
416 next_crypto: None,
417 accepted_0rtt: false,
418 permit_idle_reset: true,
419 idle_timeout: match config.max_idle_timeout {
420 None | Some(VarInt(0)) => None,
421 Some(dur) => Some(Duration::from_millis(dur.0)),
422 },
423 timers: TimerTable::default(),
424 authentication_failures: 0,
425 close: false,
426
427 ack_frequency: AckFrequencyState::new(get_max_ack_delay(
428 &TransportParameters::default(),
429 )),
430
431 app_limited: false,
432 receiving_ecn: false,
433 total_authed_packets: 0,
434
435 next_observed_addr_seq_no: 0u32.into(),
436
437 streams: StreamsState::new(
438 side,
439 config.max_concurrent_uni_streams,
440 config.max_concurrent_bidi_streams,
441 config.send_window,
442 config.receive_window,
443 config.stream_receive_window,
444 ),
445 datagrams: DatagramState::default(),
446 config,
447 rem_cids: FxHashMap::from_iter([(PathId::ZERO, CidQueue::new(rem_cid))]),
448 rng,
449 stats: ConnectionStats::default(),
450 path_stats: Default::default(),
451 version,
452
453 max_concurrent_paths: NonZeroU32::MIN,
455 local_max_path_id: PathId::ZERO,
456 remote_max_path_id: PathId::ZERO,
457 max_path_id_with_cids: PathId::ZERO,
458 abandoned_paths: Default::default(),
459
460 iroh_hp: Default::default(),
462 qlog,
463 };
464 if path_validated {
465 this.on_path_validated(PathId::ZERO);
466 }
467 if side.is_client() {
468 this.write_crypto();
470 this.init_0rtt(now);
471 }
472 this.qlog.emit_tuple_assigned(PathId::ZERO, remote, now);
473 this
474 }
475
476 #[must_use]
484 pub fn poll_timeout(&mut self) -> Option<Instant> {
485 self.timers.peek()
486 }
487
488 #[must_use]
494 pub fn poll(&mut self) -> Option<Event> {
495 if let Some(x) = self.events.pop_front() {
496 return Some(x);
497 }
498
499 if let Some(event) = self.streams.poll() {
500 return Some(Event::Stream(event));
501 }
502
503 if let Some(reason) = self.state.take_error() {
504 return Some(Event::ConnectionLost { reason });
505 }
506
507 None
508 }
509
510 #[must_use]
512 pub fn poll_endpoint_events(&mut self) -> Option<EndpointEvent> {
513 self.endpoint_events.pop_front().map(EndpointEvent)
514 }
515
516 #[must_use]
518 pub fn streams(&mut self) -> Streams<'_> {
519 Streams {
520 state: &mut self.streams,
521 conn_state: &self.state,
522 }
523 }
524
525 #[must_use]
527 pub fn recv_stream(&mut self, id: StreamId) -> RecvStream<'_> {
528 assert!(id.dir() == Dir::Bi || id.initiator() != self.side.side());
529 RecvStream {
530 id,
531 state: &mut self.streams,
532 pending: &mut self.spaces[SpaceId::Data].pending,
533 }
534 }
535
536 #[must_use]
538 pub fn send_stream(&mut self, id: StreamId) -> SendStream<'_> {
539 assert!(id.dir() == Dir::Bi || id.initiator() == self.side.side());
540 SendStream {
541 id,
542 state: &mut self.streams,
543 pending: &mut self.spaces[SpaceId::Data].pending,
544 conn_state: &self.state,
545 }
546 }
547
548 pub fn open_path_ensure(
555 &mut self,
556 remote: SocketAddr,
557 initial_status: PathStatus,
558 now: Instant,
559 ) -> Result<(PathId, bool), PathError> {
560 match self
561 .paths
562 .iter()
563 .find(|(_id, path)| path.data.remote == remote)
564 {
565 Some((path_id, _state)) => Ok((*path_id, true)),
566 None => self
567 .open_path(remote, initial_status, now)
568 .map(|id| (id, false)),
569 }
570 }
571
572 pub fn open_path(
577 &mut self,
578 remote: SocketAddr,
579 initial_status: PathStatus,
580 now: Instant,
581 ) -> Result<PathId, PathError> {
582 if !self.is_multipath_negotiated() {
583 return Err(PathError::MultipathNotNegotiated);
584 }
585 if self.side().is_server() {
586 return Err(PathError::ServerSideNotAllowed);
587 }
588
589 let max_abandoned = self.abandoned_paths.iter().max().copied();
590 let max_used = self.paths.keys().last().copied();
591 let path_id = max_abandoned
592 .max(max_used)
593 .unwrap_or(PathId::ZERO)
594 .saturating_add(1u8);
595
596 if Some(path_id) > self.max_path_id() {
597 return Err(PathError::MaxPathIdReached);
598 }
599 if path_id > self.remote_max_path_id {
600 self.spaces[SpaceId::Data].pending.paths_blocked = true;
601 return Err(PathError::MaxPathIdReached);
602 }
603 if self.rem_cids.get(&path_id).map(CidQueue::active).is_none() {
604 self.spaces[SpaceId::Data]
605 .pending
606 .path_cids_blocked
607 .push(path_id);
608 return Err(PathError::RemoteCidsExhausted);
609 }
610
611 let path = self.ensure_path(path_id, remote, now, None);
612 path.status.local_update(initial_status);
613
614 Ok(path_id)
615 }
616
617 pub fn close_path(
623 &mut self,
624 now: Instant,
625 path_id: PathId,
626 error_code: VarInt,
627 ) -> Result<(), ClosePathError> {
628 if self.abandoned_paths.contains(&path_id)
629 || Some(path_id) > self.max_path_id()
630 || !self.paths.contains_key(&path_id)
631 {
632 return Err(ClosePathError::ClosedPath);
633 }
634 if self
635 .paths
636 .iter()
637 .any(|(id, path)| {
639 *id != path_id && !self.abandoned_paths.contains(id) && path.data.validated
640 })
641 .not()
642 {
643 return Err(ClosePathError::LastOpenPath);
644 }
645
646 self.spaces[SpaceId::Data]
648 .pending
649 .path_abandon
650 .insert(path_id, error_code.into());
651
652 let pending_space = &mut self.spaces[SpaceId::Data].pending;
654 pending_space.new_cids.retain(|cid| cid.path_id != path_id);
655 pending_space.path_cids_blocked.retain(|&id| id != path_id);
656 pending_space.path_status.retain(|&id| id != path_id);
657
658 for space in self.spaces[SpaceId::Data].iter_paths_mut() {
660 for sent_packet in space.sent_packets.values_mut() {
661 if let Some(retransmits) = sent_packet.retransmits.get_mut() {
662 retransmits.new_cids.retain(|cid| cid.path_id != path_id);
663 retransmits.path_cids_blocked.retain(|&id| id != path_id);
664 retransmits.path_status.retain(|&id| id != path_id);
665 }
666 }
667 }
668
669 self.rem_cids.remove(&path_id);
675 self.endpoint_events
676 .push_back(EndpointEventInner::RetireResetToken(path_id));
677
678 let pto = self.pto_max_path(SpaceId::Data);
679
680 let path = self.paths.get_mut(&path_id).expect("checked above");
681
682 path.data.last_allowed_receive = Some(now + 3 * pto);
684 self.abandoned_paths.insert(path_id);
685
686 self.set_max_path_id(now, self.local_max_path_id.saturating_add(1u8));
687
688 self.timers.set(
693 Timer::PerPath(path_id, PathTimer::DiscardPath),
694 now + 6 * pto,
695 self.qlog.with_time(now),
696 );
697 Ok(())
698 }
699
700 #[track_caller]
704 fn path_data(&self, path_id: PathId) -> &PathData {
705 if let Some(data) = self.paths.get(&path_id) {
706 &data.data
707 } else {
708 panic!(
709 "unknown path: {path_id}, currently known paths: {:?}",
710 self.paths.keys().collect::<Vec<_>>()
711 );
712 }
713 }
714
715 fn path(&self, path_id: PathId) -> Option<&PathData> {
717 self.paths.get(&path_id).map(|path_state| &path_state.data)
718 }
719
720 fn path_mut(&mut self, path_id: PathId) -> Option<&mut PathData> {
722 self.paths
723 .get_mut(&path_id)
724 .map(|path_state| &mut path_state.data)
725 }
726
727 pub fn paths(&self) -> Vec<PathId> {
731 self.paths.keys().copied().collect()
732 }
733
734 pub fn path_status(&self, path_id: PathId) -> Result<PathStatus, ClosedPath> {
736 self.path(path_id)
737 .map(PathData::local_status)
738 .ok_or(ClosedPath { _private: () })
739 }
740
741 pub fn path_remote_address(&self, path_id: PathId) -> Result<SocketAddr, ClosedPath> {
743 self.path(path_id)
744 .map(|path| path.remote)
745 .ok_or(ClosedPath { _private: () })
746 }
747
748 pub fn set_path_status(
752 &mut self,
753 path_id: PathId,
754 status: PathStatus,
755 ) -> Result<PathStatus, SetPathStatusError> {
756 if !self.is_multipath_negotiated() {
757 return Err(SetPathStatusError::MultipathNotNegotiated);
758 }
759 let path = self
760 .path_mut(path_id)
761 .ok_or(SetPathStatusError::ClosedPath)?;
762 let prev = match path.status.local_update(status) {
763 Some(prev) => {
764 self.spaces[SpaceId::Data]
765 .pending
766 .path_status
767 .insert(path_id);
768 prev
769 }
770 None => path.local_status(),
771 };
772 Ok(prev)
773 }
774
775 pub fn remote_path_status(&self, path_id: PathId) -> Option<PathStatus> {
780 self.path(path_id).and_then(|path| path.remote_status())
781 }
782
783 pub fn set_path_max_idle_timeout(
789 &mut self,
790 path_id: PathId,
791 timeout: Option<Duration>,
792 ) -> Result<Option<Duration>, ClosedPath> {
793 let path = self
794 .paths
795 .get_mut(&path_id)
796 .ok_or(ClosedPath { _private: () })?;
797 Ok(std::mem::replace(&mut path.data.idle_timeout, timeout))
798 }
799
800 pub fn set_path_keep_alive_interval(
806 &mut self,
807 path_id: PathId,
808 interval: Option<Duration>,
809 ) -> Result<Option<Duration>, ClosedPath> {
810 let path = self
811 .paths
812 .get_mut(&path_id)
813 .ok_or(ClosedPath { _private: () })?;
814 Ok(std::mem::replace(&mut path.data.keep_alive, interval))
815 }
816
817 #[track_caller]
821 fn path_data_mut(&mut self, path_id: PathId) -> &mut PathData {
822 &mut self.paths.get_mut(&path_id).expect("known path").data
823 }
824
825 fn ensure_path(
826 &mut self,
827 path_id: PathId,
828 remote: SocketAddr,
829 now: Instant,
830 pn: Option<u64>,
831 ) -> &mut PathData {
832 let vacant_entry = match self.paths.entry(path_id) {
833 btree_map::Entry::Vacant(vacant_entry) => vacant_entry,
834 btree_map::Entry::Occupied(occupied_entry) => {
835 return &mut occupied_entry.into_mut().data;
836 }
837 };
838
839 debug!(%path_id, ?remote, "path added");
842 let peer_max_udp_payload_size =
843 u16::try_from(self.peer_params.max_udp_payload_size.into_inner()).unwrap_or(u16::MAX);
844 self.path_counter = self.path_counter.wrapping_add(1);
845 let mut data = PathData::new(
846 remote,
847 self.allow_mtud,
848 Some(peer_max_udp_payload_size),
849 self.path_counter,
850 now,
851 &self.config,
852 );
853
854 let pto = self.ack_frequency.max_ack_delay_for_pto() + data.rtt.pto_base();
855 self.timers.set(
856 Timer::PerPath(path_id, PathTimer::PathOpen),
857 now + 3 * pto,
858 self.qlog.with_time(now),
859 );
860
861 data.send_new_challenge = true;
864
865 let path = vacant_entry.insert(PathState { data, prev: None });
866
867 let mut pn_space = spaces::PacketNumberSpace::new(now, SpaceId::Data, &mut self.rng);
868 if let Some(pn) = pn {
869 pn_space.dedup.insert(pn);
870 }
871 self.spaces[SpaceId::Data]
872 .number_spaces
873 .insert(path_id, pn_space);
874 self.qlog.emit_tuple_assigned(path_id, remote, now);
875 &mut path.data
876 }
877
878 #[must_use]
888 pub fn poll_transmit(
889 &mut self,
890 now: Instant,
891 max_datagrams: usize,
892 buf: &mut Vec<u8>,
893 ) -> Option<Transmit> {
894 if let Some(probing) = self
895 .iroh_hp
896 .server_side_mut()
897 .ok()
898 .and_then(iroh_hp::ServerState::next_probe)
899 {
900 let destination = probing.remote();
901 trace!(%destination, "RAND_DATA packet");
902 let token: u64 = self.rng.random();
903 buf.put_u64(token);
904 probing.finish(token);
905 return Some(Transmit {
906 destination,
907 ecn: None,
908 size: 8,
909 segment_size: None,
910 src_ip: None,
911 });
912 }
913
914 assert!(max_datagrams != 0);
915 let max_datagrams = match self.config.enable_segmentation_offload {
916 false => 1,
917 true => max_datagrams,
918 };
919
920 let close = match self.state.as_type() {
939 StateType::Drained => {
940 self.app_limited = true;
941 return None;
942 }
943 StateType::Draining | StateType::Closed => {
944 if !self.close {
947 self.app_limited = true;
948 return None;
949 }
950 true
951 }
952 _ => false,
953 };
954
955 if let Some(config) = &self.config.ack_frequency_config {
957 let rtt = self
958 .paths
959 .values()
960 .map(|p| p.data.rtt.get())
961 .min()
962 .expect("one path exists");
963 self.spaces[SpaceId::Data].pending.ack_frequency = self
964 .ack_frequency
965 .should_send_ack_frequency(rtt, config, &self.peer_params)
966 && self.highest_space == SpaceId::Data
967 && self.peer_supports_ack_frequency();
968 }
969
970 let mut coalesce = true;
972
973 let mut pad_datagram = PadDatagram::No;
976
977 let mut congestion_blocked = false;
981
982 let mut last_packet_number = None;
984
985 let mut path_id = *self.paths.first_key_value().expect("one path must exist").0;
986
987 let have_available_path = self.paths.iter().any(|(id, path)| {
990 path.data.validated
991 && path.data.local_status() == PathStatus::Available
992 && self.rem_cids.contains_key(id)
993 });
994
995 let mut transmit = TransmitBuf::new(
997 buf,
998 max_datagrams,
999 self.path_data(path_id).current_mtu().into(),
1000 );
1001 if let Some(challenge) = self.send_prev_path_challenge(now, &mut transmit, path_id) {
1002 return Some(challenge);
1003 }
1004 let mut space_id = match path_id {
1005 PathId::ZERO => SpaceId::Initial,
1006 _ => SpaceId::Data,
1007 };
1008
1009 loop {
1010 let Some(remote_cid) = self.rem_cids.get(&path_id).map(CidQueue::active) else {
1012 let err = PathError::RemoteCidsExhausted;
1013 if !self.abandoned_paths.contains(&path_id) {
1014 debug!(?err, %path_id, "no active CID for path");
1015 self.events.push_back(Event::Path(PathEvent::LocallyClosed {
1016 id: path_id,
1017 error: err,
1018 }));
1019 self.close_path(
1023 now,
1024 path_id,
1025 TransportErrorCode::NO_CID_AVAILABLE_FOR_PATH.into(),
1026 )
1027 .ok();
1028 self.spaces[SpaceId::Data]
1029 .pending
1030 .path_cids_blocked
1031 .push(path_id);
1032 } else {
1033 trace!(%path_id, "remote CIDs retired for abandoned path");
1034 }
1035
1036 match self.paths.keys().find(|&&next| next > path_id) {
1037 Some(next_path_id) => {
1038 path_id = *next_path_id;
1040 space_id = SpaceId::Data;
1041
1042 transmit.set_segment_size(self.path_data(path_id).current_mtu().into());
1044 if let Some(challenge) =
1045 self.send_prev_path_challenge(now, &mut transmit, path_id)
1046 {
1047 return Some(challenge);
1048 }
1049
1050 continue;
1051 }
1052 None => {
1053 trace!(
1055 ?space_id,
1056 %path_id,
1057 "no CIDs to send on path, no more paths"
1058 );
1059 break;
1060 }
1061 }
1062 };
1063
1064 let max_packet_size = if transmit.datagram_remaining_mut() > 0 {
1067 transmit.datagram_remaining_mut()
1069 } else {
1070 transmit.segment_size()
1072 };
1073 let can_send = self.space_can_send(space_id, path_id, max_packet_size, close);
1074 let path_should_send = {
1075 let path_exclusive_only = space_id == SpaceId::Data
1076 && have_available_path
1077 && self.path_data(path_id).local_status() == PathStatus::Backup;
1078 let path_should_send = if path_exclusive_only {
1079 can_send.path_exclusive
1080 } else {
1081 !can_send.is_empty()
1082 };
1083 let needs_loss_probe = self.spaces[space_id].for_path(path_id).loss_probes > 0;
1084 path_should_send || needs_loss_probe || can_send.close
1085 };
1086
1087 if !path_should_send && space_id < SpaceId::Data {
1088 if self.spaces[space_id].crypto.is_some() {
1089 trace!(?space_id, %path_id, "nothing to send in space");
1090 }
1091 space_id = space_id.next();
1092 continue;
1093 }
1094
1095 let send_blocked = if path_should_send && transmit.datagram_remaining_mut() == 0 {
1096 self.path_congestion_check(space_id, path_id, &transmit, &can_send, now)
1098 } else {
1099 PathBlocked::No
1100 };
1101 if send_blocked != PathBlocked::No {
1102 trace!(?space_id, %path_id, ?send_blocked, "congestion blocked");
1103 congestion_blocked = true;
1104 }
1105 if send_blocked != PathBlocked::No && space_id < SpaceId::Data {
1106 space_id = space_id.next();
1109 continue;
1110 }
1111 if !path_should_send || send_blocked != PathBlocked::No {
1112 if transmit.num_datagrams() > 0 {
1117 break;
1118 }
1119
1120 match self.paths.keys().find(|&&next| next > path_id) {
1121 Some(next_path_id) => {
1122 trace!(
1124 ?space_id,
1125 %path_id,
1126 %next_path_id,
1127 "nothing to send on path"
1128 );
1129 path_id = *next_path_id;
1130 space_id = SpaceId::Data;
1131
1132 transmit.set_segment_size(self.path_data(path_id).current_mtu().into());
1134 if let Some(challenge) =
1135 self.send_prev_path_challenge(now, &mut transmit, path_id)
1136 {
1137 return Some(challenge);
1138 }
1139
1140 continue;
1141 }
1142 None => {
1143 trace!(
1145 ?space_id,
1146 %path_id,
1147 next_path_id=?None::<PathId>,
1148 "nothing to send on path"
1149 );
1150 break;
1151 }
1152 }
1153 }
1154
1155 if transmit.datagram_remaining_mut() == 0 {
1157 if transmit.num_datagrams() >= transmit.max_datagrams() {
1158 break;
1160 }
1161
1162 match self.spaces[space_id].for_path(path_id).loss_probes {
1163 0 => transmit.start_new_datagram(),
1164 _ => {
1165 let request_immediate_ack =
1167 space_id == SpaceId::Data && self.peer_supports_ack_frequency();
1168 self.spaces[space_id].maybe_queue_probe(
1169 path_id,
1170 request_immediate_ack,
1171 &self.streams,
1172 );
1173
1174 self.spaces[space_id].for_path(path_id).loss_probes -= 1;
1175
1176 transmit.start_new_datagram_with_size(std::cmp::min(
1180 usize::from(INITIAL_MTU),
1181 transmit.segment_size(),
1182 ));
1183 }
1184 }
1185 trace!(count = transmit.num_datagrams(), "new datagram started");
1186 coalesce = true;
1187 pad_datagram = PadDatagram::No;
1188 }
1189
1190 if transmit.datagram_start_offset() < transmit.len() {
1193 debug_assert!(transmit.datagram_remaining_mut() >= MIN_PACKET_SPACE);
1194 }
1195
1196 if self.spaces[SpaceId::Initial].crypto.is_some()
1201 && space_id == SpaceId::Handshake
1202 && self.side.is_client()
1203 {
1204 self.discard_space(now, SpaceId::Initial);
1207 }
1208 if let Some(ref mut prev) = self.prev_crypto {
1209 prev.update_unacked = false;
1210 }
1211
1212 let mut qlog = QlogSentPacket::default();
1213 let mut builder = PacketBuilder::new(
1214 now,
1215 space_id,
1216 path_id,
1217 remote_cid,
1218 &mut transmit,
1219 can_send.other,
1220 self,
1221 &mut qlog,
1222 )?;
1223 last_packet_number = Some(builder.exact_number);
1224 coalesce = coalesce && !builder.short_header;
1225
1226 if space_id == SpaceId::Initial && (self.side.is_client() || can_send.other) {
1227 pad_datagram |= PadDatagram::ToMinMtu;
1229 }
1230 if space_id == SpaceId::Data && self.config.pad_to_mtu {
1231 pad_datagram |= PadDatagram::ToSegmentSize;
1232 }
1233
1234 if can_send.close {
1235 trace!("sending CONNECTION_CLOSE");
1236 let mut sent_frames = SentFrames::default();
1241 let is_multipath_negotiated = self.is_multipath_negotiated();
1242 for path_id in self.spaces[space_id]
1243 .number_spaces
1244 .iter()
1245 .filter(|(_, pns)| !pns.pending_acks.ranges().is_empty())
1246 .map(|(&path_id, _)| path_id)
1247 .collect::<Vec<_>>()
1248 {
1249 Self::populate_acks(
1250 now,
1251 self.receiving_ecn,
1252 &mut sent_frames,
1253 path_id,
1254 space_id,
1255 &mut self.spaces[space_id],
1256 is_multipath_negotiated,
1257 &mut builder.frame_space_mut(),
1258 &mut self.stats,
1259 &mut qlog,
1260 );
1261 }
1262
1263 debug_assert!(
1267 builder.frame_space_remaining() > frame::ConnectionClose::SIZE_BOUND,
1268 "ACKs should leave space for ConnectionClose"
1269 );
1270 if frame::ConnectionClose::SIZE_BOUND < builder.frame_space_remaining() {
1271 let max_frame_size = builder.frame_space_remaining();
1272 match self.state.as_type() {
1273 StateType::Closed => {
1274 let reason: Close =
1275 self.state.as_closed().expect("checked").clone().into();
1276 if space_id == SpaceId::Data || reason.is_transport_layer() {
1277 reason.encode(&mut builder.frame_space_mut(), max_frame_size);
1278 qlog.frame(&Frame::Close(reason));
1279 } else {
1280 let frame = frame::ConnectionClose {
1281 error_code: TransportErrorCode::APPLICATION_ERROR,
1282 frame_type: None,
1283 reason: Bytes::new(),
1284 };
1285 frame.encode(&mut builder.frame_space_mut(), max_frame_size);
1286 qlog.frame(&Frame::Close(frame::Close::Connection(frame)));
1287 }
1288 }
1289 StateType::Draining => {
1290 let frame = frame::ConnectionClose {
1291 error_code: TransportErrorCode::NO_ERROR,
1292 frame_type: None,
1293 reason: Bytes::new(),
1294 };
1295 frame.encode(&mut builder.frame_space_mut(), max_frame_size);
1296 qlog.frame(&Frame::Close(frame::Close::Connection(frame)));
1297 }
1298 _ => unreachable!(
1299 "tried to make a close packet when the connection wasn't closed"
1300 ),
1301 };
1302 }
1303 builder.finish_and_track(now, self, path_id, sent_frames, pad_datagram, qlog);
1304 if space_id == self.highest_space {
1305 self.close = false;
1308 break;
1310 } else {
1311 space_id = space_id.next();
1315 continue;
1316 }
1317 }
1318
1319 if space_id == SpaceId::Data && builder.buf.num_datagrams() == 1 {
1322 let path = self.path_data_mut(path_id);
1323 if let Some((token, remote)) = path.path_responses.pop_off_path(path.remote) {
1324 let response = frame::PathResponse(token);
1328 trace!(%response, "(off-path)");
1329 builder.frame_space_mut().write(response);
1330 qlog.frame(&Frame::PathResponse(response));
1331 self.stats.frame_tx.path_response += 1;
1332 builder.finish_and_track(
1333 now,
1334 self,
1335 path_id,
1336 SentFrames {
1337 non_retransmits: true,
1338 ..SentFrames::default()
1339 },
1340 PadDatagram::ToMinMtu,
1341 qlog,
1342 );
1343 self.stats.udp_tx.on_sent(1, transmit.len());
1344 return Some(Transmit {
1345 destination: remote,
1346 size: transmit.len(),
1347 ecn: None,
1348 segment_size: None,
1349 src_ip: self.local_ip,
1350 });
1351 }
1352 }
1353
1354 let sent_frames = {
1355 let path_exclusive_only = have_available_path
1356 && self.path_data(path_id).local_status() == PathStatus::Backup;
1357 let pn = builder.exact_number;
1358 self.populate_packet(
1359 now,
1360 space_id,
1361 path_id,
1362 path_exclusive_only,
1363 &mut builder.frame_space_mut(),
1364 pn,
1365 &mut qlog,
1366 )
1367 };
1368
1369 debug_assert!(
1376 !(sent_frames.is_ack_only(&self.streams)
1377 && !can_send.acks
1378 && can_send.other
1379 && builder.buf.segment_size()
1380 == self.path_data(path_id).current_mtu() as usize
1381 && self.datagrams.outgoing.is_empty()),
1382 "SendableFrames was {can_send:?}, but only ACKs have been written"
1383 );
1384 if sent_frames.requires_padding {
1385 pad_datagram |= PadDatagram::ToMinMtu;
1386 }
1387
1388 for (path_id, _pn) in sent_frames.largest_acked.iter() {
1389 self.spaces[space_id]
1390 .for_path(*path_id)
1391 .pending_acks
1392 .acks_sent();
1393 self.timers.stop(
1394 Timer::PerPath(*path_id, PathTimer::MaxAckDelay),
1395 self.qlog.with_time(now),
1396 );
1397 }
1398
1399 if coalesce
1407 && builder
1408 .buf
1409 .datagram_remaining_mut()
1410 .saturating_sub(builder.predict_packet_end())
1411 > MIN_PACKET_SPACE
1412 && self
1413 .next_send_space(space_id, path_id, builder.buf, close)
1414 .is_some()
1415 {
1416 builder.finish_and_track(now, self, path_id, sent_frames, PadDatagram::No, qlog);
1419 } else {
1420 if builder.buf.num_datagrams() > 1 && matches!(pad_datagram, PadDatagram::No) {
1423 const MAX_PADDING: usize = 32;
1431 if builder.buf.datagram_remaining_mut()
1432 > builder.predict_packet_end() + MAX_PADDING
1433 {
1434 trace!(
1435 "GSO truncated by demand for {} padding bytes",
1436 builder.buf.datagram_remaining_mut() - builder.predict_packet_end()
1437 );
1438 builder.finish_and_track(
1439 now,
1440 self,
1441 path_id,
1442 sent_frames,
1443 PadDatagram::No,
1444 qlog,
1445 );
1446 break;
1447 }
1448
1449 builder.finish_and_track(
1452 now,
1453 self,
1454 path_id,
1455 sent_frames,
1456 PadDatagram::ToSegmentSize,
1457 qlog,
1458 );
1459 } else {
1460 builder.finish_and_track(now, self, path_id, sent_frames, pad_datagram, qlog);
1461 }
1462 if transmit.num_datagrams() == 1 {
1463 transmit.clip_datagram_size();
1464 }
1465 }
1466 }
1467
1468 if let Some(last_packet_number) = last_packet_number {
1469 self.path_data_mut(path_id).congestion.on_sent(
1472 now,
1473 transmit.len() as u64,
1474 last_packet_number,
1475 );
1476 }
1477
1478 self.qlog.emit_recovery_metrics(
1479 path_id,
1480 &mut self.paths.get_mut(&path_id).unwrap().data,
1481 now,
1482 );
1483
1484 self.app_limited = transmit.is_empty() && !congestion_blocked;
1485
1486 if transmit.is_empty() && self.state.is_established() {
1488 let space_id = SpaceId::Data;
1490 path_id = *self.paths.first_key_value().expect("one path must exist").0;
1491 let probe_data = loop {
1492 let active_cid = self.rem_cids.get(&path_id).map(CidQueue::active);
1498 let eligible = self.path_data(path_id).validated
1499 && !self.path_data(path_id).is_validating_path()
1500 && !self.abandoned_paths.contains(&path_id);
1501 let probe_size = eligible
1502 .then(|| {
1503 let next_pn = self.spaces[space_id].for_path(path_id).peek_tx_number();
1504 self.path_data_mut(path_id).mtud.poll_transmit(now, next_pn)
1505 })
1506 .flatten();
1507 match (active_cid, probe_size) {
1508 (Some(active_cid), Some(probe_size)) => {
1509 break Some((active_cid, probe_size));
1511 }
1512 _ => {
1513 match self.paths.keys().find(|&&next| next > path_id) {
1515 Some(next) => {
1516 path_id = *next;
1517 continue;
1518 }
1519 None => break None,
1520 }
1521 }
1522 }
1523 };
1524 if let Some((active_cid, probe_size)) = probe_data {
1525 debug_assert_eq!(transmit.num_datagrams(), 0);
1527 transmit.start_new_datagram_with_size(probe_size as usize);
1528
1529 let mut qlog = QlogSentPacket::default();
1530 let mut builder = PacketBuilder::new(
1531 now,
1532 space_id,
1533 path_id,
1534 active_cid,
1535 &mut transmit,
1536 true,
1537 self,
1538 &mut qlog,
1539 )?;
1540
1541 trace!(?probe_size, "writing MTUD probe");
1543 trace!("PING");
1544 builder.frame_space_mut().write(frame::FrameType::PING);
1545 qlog.frame(&Frame::Ping);
1546 self.stats.frame_tx.ping += 1;
1547
1548 if self.peer_supports_ack_frequency() {
1550 trace!("IMMEDIATE_ACK");
1551 builder
1552 .frame_space_mut()
1553 .write(frame::FrameType::IMMEDIATE_ACK);
1554 self.stats.frame_tx.immediate_ack += 1;
1555 qlog.frame(&Frame::ImmediateAck);
1556 }
1557
1558 let sent_frames = SentFrames {
1559 non_retransmits: true,
1560 ..Default::default()
1561 };
1562 builder.finish_and_track(
1563 now,
1564 self,
1565 path_id,
1566 sent_frames,
1567 PadDatagram::ToSize(probe_size),
1568 qlog,
1569 );
1570
1571 self.path_stats
1572 .entry(path_id)
1573 .or_default()
1574 .sent_plpmtud_probes += 1;
1575 }
1576 }
1577
1578 if transmit.is_empty() {
1579 return None;
1580 }
1581
1582 let destination = self.path_data(path_id).remote;
1583 trace!(
1584 segment_size = transmit.segment_size(),
1585 last_datagram_len = transmit.len() % transmit.segment_size(),
1586 ?destination,
1587 "sending {} bytes in {} datagrams",
1588 transmit.len(),
1589 transmit.num_datagrams()
1590 );
1591 self.path_data_mut(path_id)
1592 .inc_total_sent(transmit.len() as u64);
1593
1594 self.stats
1595 .udp_tx
1596 .on_sent(transmit.num_datagrams() as u64, transmit.len());
1597
1598 Some(Transmit {
1599 destination,
1600 size: transmit.len(),
1601 ecn: if self.path_data(path_id).sending_ecn {
1602 Some(EcnCodepoint::Ect0)
1603 } else {
1604 None
1605 },
1606 segment_size: match transmit.num_datagrams() {
1607 1 => None,
1608 _ => Some(transmit.segment_size()),
1609 },
1610 src_ip: self.local_ip,
1611 })
1612 }
1613
1614 fn next_send_space(
1619 &mut self,
1620 current_space_id: SpaceId,
1621 path_id: PathId,
1622 buf: &TransmitBuf<'_>,
1623 close: bool,
1624 ) -> Option<SpaceId> {
1625 let mut space_id = current_space_id;
1632 loop {
1633 let can_send = self.space_can_send(space_id, path_id, buf.segment_size(), close);
1634 if !can_send.is_empty() || (close && self.spaces[space_id].crypto.is_some()) {
1635 return Some(space_id);
1636 }
1637 space_id = match space_id {
1638 SpaceId::Initial => SpaceId::Handshake,
1639 SpaceId::Handshake => SpaceId::Data,
1640 SpaceId::Data => break,
1641 }
1642 }
1643 None
1644 }
1645
1646 fn path_congestion_check(
1648 &mut self,
1649 space_id: SpaceId,
1650 path_id: PathId,
1651 transmit: &TransmitBuf<'_>,
1652 can_send: &SendableFrames,
1653 now: Instant,
1654 ) -> PathBlocked {
1655 if self.side().is_server()
1661 && self
1662 .path_data(path_id)
1663 .anti_amplification_blocked(transmit.len() as u64 + 1)
1664 {
1665 trace!(?space_id, %path_id, "blocked by anti-amplification");
1666 return PathBlocked::AntiAmplification;
1667 }
1668
1669 let bytes_to_send = transmit.segment_size() as u64;
1672 let need_loss_probe = self.spaces[space_id].for_path(path_id).loss_probes > 0;
1673
1674 if can_send.other && !need_loss_probe && !can_send.close {
1675 let path = self.path_data(path_id);
1676 if path.in_flight.bytes + bytes_to_send >= path.congestion.window() {
1677 trace!(?space_id, %path_id, "blocked by congestion control");
1678 return PathBlocked::Congestion;
1679 }
1680 }
1681
1682 if let Some(delay) = self.path_data_mut(path_id).pacing_delay(bytes_to_send, now) {
1684 self.timers.set(
1685 Timer::PerPath(path_id, PathTimer::Pacing),
1686 delay,
1687 self.qlog.with_time(now),
1688 );
1689 trace!(?space_id, %path_id, "blocked by pacing");
1692 return PathBlocked::Pacing;
1693 }
1694
1695 PathBlocked::No
1696 }
1697
1698 fn send_prev_path_challenge(
1703 &mut self,
1704 now: Instant,
1705 buf: &mut TransmitBuf<'_>,
1706 path_id: PathId,
1707 ) -> Option<Transmit> {
1708 let (prev_cid, prev_path) = self.paths.get_mut(&path_id)?.prev.as_mut()?;
1709 if !prev_path.send_new_challenge {
1712 return None;
1713 };
1714 prev_path.send_new_challenge = false;
1715 let destination = prev_path.remote;
1716 let token = self.rng.random();
1717 let info = paths::SentChallengeInfo {
1718 sent_instant: now,
1719 remote: destination,
1720 };
1721 prev_path.challenges_sent.insert(token, info);
1722 debug_assert_eq!(
1723 self.highest_space,
1724 SpaceId::Data,
1725 "PATH_CHALLENGE queued without 1-RTT keys"
1726 );
1727 buf.start_new_datagram_with_size(MIN_INITIAL_SIZE as usize);
1728
1729 debug_assert_eq!(buf.datagram_start_offset(), 0);
1735 let mut qlog = QlogSentPacket::default();
1736 let mut builder = PacketBuilder::new(
1737 now,
1738 SpaceId::Data,
1739 path_id,
1740 *prev_cid,
1741 buf,
1742 false,
1743 self,
1744 &mut qlog,
1745 )?;
1746 let challenge = frame::PathChallenge(token);
1747 trace!(%challenge, "validating previous path");
1748 qlog.frame(&Frame::PathChallenge(challenge));
1749 builder.frame_space_mut().write(challenge);
1750 self.stats.frame_tx.path_challenge += 1;
1751
1752 builder.pad_to(MIN_INITIAL_SIZE);
1757
1758 builder.finish(self, now, qlog);
1759 self.stats.udp_tx.on_sent(1, buf.len());
1760
1761 Some(Transmit {
1762 destination,
1763 size: buf.len(),
1764 ecn: None,
1765 segment_size: None,
1766 src_ip: self.local_ip,
1767 })
1768 }
1769
1770 fn space_can_send(
1775 &mut self,
1776 space_id: SpaceId,
1777 path_id: PathId,
1778 packet_size: usize,
1779 close: bool,
1780 ) -> SendableFrames {
1781 let pn = self.spaces[SpaceId::Data]
1782 .for_path(path_id)
1783 .peek_tx_number();
1784 let frame_space_1rtt = packet_size.saturating_sub(self.predict_1rtt_overhead(pn, path_id));
1785 if self.spaces[space_id].crypto.is_none()
1786 && (space_id != SpaceId::Data
1787 || self.zero_rtt_crypto.is_none()
1788 || self.side.is_server())
1789 {
1790 return SendableFrames::empty();
1792 }
1793 let mut can_send = self.spaces[space_id].can_send(path_id, &self.streams);
1794 if space_id == SpaceId::Data {
1795 can_send |= self.can_send_1rtt(path_id, frame_space_1rtt);
1796 }
1797
1798 can_send.close = close && self.spaces[space_id].crypto.is_some();
1799
1800 can_send
1801 }
1802
1803 pub fn handle_event(&mut self, event: ConnectionEvent) {
1809 use ConnectionEventInner::*;
1810 match event.0 {
1811 Datagram(DatagramConnectionEvent {
1812 now,
1813 remote,
1814 path_id,
1815 ecn,
1816 first_decode,
1817 remaining,
1818 }) => {
1819 let span = trace_span!("pkt", %path_id);
1820 let _guard = span.enter();
1821 if let Some(known_remote) = self.path(path_id).map(|path| path.remote) {
1825 if remote != known_remote && !self.side.remote_may_migrate(&self.state) {
1826 trace!(
1827 %path_id,
1828 ?remote,
1829 path_remote = ?self.path(path_id).map(|p| p.remote),
1830 "discarding packet from unrecognized peer"
1831 );
1832 return;
1833 }
1834 }
1835
1836 let was_anti_amplification_blocked = self
1837 .path(path_id)
1838 .map(|path| path.anti_amplification_blocked(1))
1839 .unwrap_or(true); self.stats.udp_rx.datagrams += 1;
1843 self.stats.udp_rx.bytes += first_decode.len() as u64;
1844 let data_len = first_decode.len();
1845
1846 self.handle_decode(now, remote, path_id, ecn, first_decode);
1847 if let Some(path) = self.path_mut(path_id) {
1852 path.inc_total_recvd(data_len as u64);
1853 }
1854
1855 if let Some(data) = remaining {
1856 self.stats.udp_rx.bytes += data.len() as u64;
1857 self.handle_coalesced(now, remote, path_id, ecn, data);
1858 }
1859
1860 if let Some(path) = self.paths.get_mut(&path_id) {
1861 self.qlog
1862 .emit_recovery_metrics(path_id, &mut path.data, now);
1863 }
1864
1865 if was_anti_amplification_blocked {
1866 self.set_loss_detection_timer(now, path_id);
1870 }
1871 }
1872 NewIdentifiers(ids, now, cid_len, cid_lifetime) => {
1873 let path_id = ids.first().map(|issued| issued.path_id).unwrap_or_default();
1874 debug_assert!(ids.iter().all(|issued| issued.path_id == path_id));
1875 let cid_state = self
1876 .local_cid_state
1877 .entry(path_id)
1878 .or_insert_with(|| CidState::new(cid_len, cid_lifetime, now, 0));
1879 cid_state.new_cids(&ids, now);
1880
1881 ids.into_iter().rev().for_each(|frame| {
1882 self.spaces[SpaceId::Data].pending.new_cids.push(frame);
1883 });
1884 self.reset_cid_retirement(now);
1886 }
1887 }
1888 }
1889
1890 pub fn handle_timeout(&mut self, now: Instant) {
1900 while let Some((timer, _time)) = self.timers.expire_before(now, &self.qlog) {
1901 trace!(?timer, at=?now, "timeout");
1903 match timer {
1904 Timer::Conn(timer) => match timer {
1905 ConnTimer::Close => {
1906 self.state.move_to_drained(None);
1907 self.endpoint_events.push_back(EndpointEventInner::Drained);
1908 }
1909 ConnTimer::Idle => {
1910 self.kill(ConnectionError::TimedOut);
1911 }
1912 ConnTimer::KeepAlive => {
1913 trace!("sending keep-alive");
1914 self.ping();
1915 }
1916 ConnTimer::KeyDiscard => {
1917 self.zero_rtt_crypto = None;
1918 self.prev_crypto = None;
1919 }
1920 ConnTimer::PushNewCid => {
1921 while let Some((path_id, when)) = self.next_cid_retirement() {
1922 if when > now {
1923 break;
1924 }
1925 match self.local_cid_state.get_mut(&path_id) {
1926 None => error!(%path_id, "No local CID state for path"),
1927 Some(cid_state) => {
1928 let num_new_cid = cid_state.on_cid_timeout().into();
1930 if !self.state.is_closed() {
1931 trace!(
1932 "push a new CID to peer RETIRE_PRIOR_TO field {}",
1933 cid_state.retire_prior_to()
1934 );
1935 self.endpoint_events.push_back(
1936 EndpointEventInner::NeedIdentifiers(
1937 path_id,
1938 now,
1939 num_new_cid,
1940 ),
1941 );
1942 }
1943 }
1944 }
1945 }
1946 }
1947 },
1948 Timer::PerPath(path_id, timer) => {
1950 let span = trace_span!("per-path timer fired", %path_id, ?timer);
1951 let _guard = span.enter();
1952 match timer {
1953 PathTimer::PathIdle => {
1954 self.close_path(now, path_id, TransportErrorCode::NO_ERROR.into())
1955 .ok();
1956 }
1957
1958 PathTimer::PathKeepAlive => {
1959 trace!("sending keep-alive on path");
1960 self.ping_path(path_id).ok();
1961 }
1962 PathTimer::LossDetection => {
1963 self.on_loss_detection_timeout(now, path_id);
1964 self.qlog.emit_recovery_metrics(
1965 path_id,
1966 &mut self.paths.get_mut(&path_id).unwrap().data,
1967 now,
1968 );
1969 }
1970 PathTimer::PathValidation => {
1971 let Some(path) = self.paths.get_mut(&path_id) else {
1972 continue;
1973 };
1974 self.timers.stop(
1975 Timer::PerPath(path_id, PathTimer::PathChallengeLost),
1976 self.qlog.with_time(now),
1977 );
1978 debug!("path validation failed");
1979 if let Some((_, prev)) = path.prev.take() {
1980 path.data = prev;
1981 }
1982 path.data.challenges_sent.clear();
1983 path.data.send_new_challenge = false;
1984 }
1985 PathTimer::PathChallengeLost => {
1986 let Some(path) = self.paths.get_mut(&path_id) else {
1987 continue;
1988 };
1989 trace!("path challenge deemed lost");
1990 path.data.send_new_challenge = true;
1991 }
1992 PathTimer::PathOpen => {
1993 let Some(path) = self.path_mut(path_id) else {
1994 continue;
1995 };
1996 path.challenges_sent.clear();
1997 path.send_new_challenge = false;
1998 debug!("new path validation failed");
1999 if let Err(err) = self.close_path(
2000 now,
2001 path_id,
2002 TransportErrorCode::PATH_UNSTABLE_OR_POOR.into(),
2003 ) {
2004 warn!(?err, "failed closing path");
2005 }
2006
2007 self.events.push_back(Event::Path(PathEvent::LocallyClosed {
2008 id: path_id,
2009 error: PathError::ValidationFailed,
2010 }));
2011 }
2012 PathTimer::Pacing => trace!("pacing timer expired"),
2013 PathTimer::MaxAckDelay => {
2014 trace!("max ack delay reached");
2015 self.spaces[SpaceId::Data]
2017 .for_path(path_id)
2018 .pending_acks
2019 .on_max_ack_delay_timeout()
2020 }
2021 PathTimer::DiscardPath => {
2022 self.timers.stop_per_path(path_id, self.qlog.with_time(now));
2025 if let Some(loc_cid_state) = self.local_cid_state.remove(&path_id) {
2026 let (min_seq, max_seq) = loc_cid_state.active_seq();
2027 for seq in min_seq..=max_seq {
2028 self.endpoint_events.push_back(
2029 EndpointEventInner::RetireConnectionId(
2030 now, path_id, seq, false,
2031 ),
2032 );
2033 }
2034 }
2035 self.discard_path(path_id, now);
2036 }
2037 }
2038 }
2039 }
2040 }
2041 }
2042
2043 pub fn close(&mut self, now: Instant, error_code: VarInt, reason: Bytes) {
2055 self.close_inner(
2056 now,
2057 Close::Application(frame::ApplicationClose { error_code, reason }),
2058 )
2059 }
2060
2061 fn close_inner(&mut self, now: Instant, reason: Close) {
2062 let was_closed = self.state.is_closed();
2063 if !was_closed {
2064 self.close_common();
2065 self.set_close_timer(now);
2066 self.close = true;
2067 self.state.move_to_closed_local(reason);
2068 }
2069 }
2070
2071 pub fn datagrams(&mut self) -> Datagrams<'_> {
2073 Datagrams { conn: self }
2074 }
2075
2076 pub fn stats(&mut self) -> ConnectionStats {
2078 self.stats.clone()
2079 }
2080
2081 pub fn path_stats(&mut self, path_id: PathId) -> Option<PathStats> {
2083 let path = self.paths.get(&path_id)?;
2084 let stats = self.path_stats.entry(path_id).or_default();
2085 stats.rtt = path.data.rtt.get();
2086 stats.cwnd = path.data.congestion.window();
2087 stats.current_mtu = path.data.mtud.current_mtu();
2088 Some(*stats)
2089 }
2090
2091 pub fn ping(&mut self) {
2095 for path_data in self.spaces[self.highest_space].number_spaces.values_mut() {
2098 path_data.ping_pending = true;
2099 }
2100 }
2101
2102 pub fn ping_path(&mut self, path: PathId) -> Result<(), ClosedPath> {
2106 let path_data = self.spaces[self.highest_space]
2107 .number_spaces
2108 .get_mut(&path)
2109 .ok_or(ClosedPath { _private: () })?;
2110 path_data.ping_pending = true;
2111 Ok(())
2112 }
2113
2114 pub fn force_key_update(&mut self) {
2118 if !self.state.is_established() {
2119 debug!("ignoring forced key update in illegal state");
2120 return;
2121 }
2122 if self.prev_crypto.is_some() {
2123 debug!("ignoring redundant forced key update");
2126 return;
2127 }
2128 self.update_keys(None, false);
2129 }
2130
2131 #[doc(hidden)]
2133 #[deprecated]
2134 pub fn initiate_key_update(&mut self) {
2135 self.force_key_update();
2136 }
2137
2138 pub fn crypto_session(&self) -> &dyn crypto::Session {
2140 &*self.crypto
2141 }
2142
2143 pub fn is_handshaking(&self) -> bool {
2148 self.state.is_handshake()
2149 }
2150
2151 pub fn is_closed(&self) -> bool {
2159 self.state.is_closed()
2160 }
2161
2162 pub fn is_drained(&self) -> bool {
2167 self.state.is_drained()
2168 }
2169
2170 pub fn accepted_0rtt(&self) -> bool {
2174 self.accepted_0rtt
2175 }
2176
2177 pub fn has_0rtt(&self) -> bool {
2179 self.zero_rtt_enabled
2180 }
2181
2182 pub fn has_pending_retransmits(&self) -> bool {
2184 !self.spaces[SpaceId::Data].pending.is_empty(&self.streams)
2185 }
2186
2187 pub fn side(&self) -> Side {
2189 self.side.side()
2190 }
2191
2192 pub fn path_observed_address(&self, path_id: PathId) -> Result<Option<SocketAddr>, ClosedPath> {
2194 self.path(path_id)
2195 .map(|path_data| {
2196 path_data
2197 .last_observed_addr_report
2198 .as_ref()
2199 .map(|observed| observed.socket_addr())
2200 })
2201 .ok_or(ClosedPath { _private: () })
2202 }
2203
2204 pub fn local_ip(&self) -> Option<IpAddr> {
2214 self.local_ip
2215 }
2216
2217 pub fn rtt(&self, path_id: PathId) -> Option<Duration> {
2219 self.path(path_id).map(|d| d.rtt.get())
2220 }
2221
2222 pub fn congestion_state(&self, path_id: PathId) -> Option<&dyn Controller> {
2224 self.path(path_id).map(|d| d.congestion.as_ref())
2225 }
2226
2227 pub fn set_max_concurrent_streams(&mut self, dir: Dir, count: VarInt) {
2232 self.streams.set_max_concurrent(dir, count);
2233 let pending = &mut self.spaces[SpaceId::Data].pending;
2236 self.streams.queue_max_stream_id(pending);
2237 }
2238
2239 pub fn set_max_concurrent_paths(
2249 &mut self,
2250 now: Instant,
2251 count: NonZeroU32,
2252 ) -> Result<(), MultipathNotNegotiated> {
2253 if !self.is_multipath_negotiated() {
2254 return Err(MultipathNotNegotiated { _private: () });
2255 }
2256 self.max_concurrent_paths = count;
2257
2258 let in_use_count = self
2259 .local_max_path_id
2260 .next()
2261 .saturating_sub(self.abandoned_paths.len() as u32)
2262 .as_u32();
2263 let extra_needed = count.get().saturating_sub(in_use_count);
2264 let new_max_path_id = self.local_max_path_id.saturating_add(extra_needed);
2265
2266 self.set_max_path_id(now, new_max_path_id);
2267
2268 Ok(())
2269 }
2270
2271 fn set_max_path_id(&mut self, now: Instant, max_path_id: PathId) {
2273 if max_path_id <= self.local_max_path_id {
2274 return;
2275 }
2276
2277 self.local_max_path_id = max_path_id;
2278 self.spaces[SpaceId::Data].pending.max_path_id = true;
2279
2280 self.issue_first_path_cids(now);
2281 }
2282
2283 pub fn max_concurrent_streams(&self, dir: Dir) -> u64 {
2289 self.streams.max_concurrent(dir)
2290 }
2291
2292 pub fn set_send_window(&mut self, send_window: u64) {
2294 self.streams.set_send_window(send_window);
2295 }
2296
2297 pub fn set_receive_window(&mut self, receive_window: VarInt) {
2299 if self.streams.set_receive_window(receive_window) {
2300 self.spaces[SpaceId::Data].pending.max_data = true;
2301 }
2302 }
2303
2304 pub fn is_multipath_negotiated(&self) -> bool {
2309 !self.is_handshaking()
2310 && self.config.max_concurrent_multipath_paths.is_some()
2311 && self.peer_params.initial_max_path_id.is_some()
2312 }
2313
2314 fn on_ack_received(
2315 &mut self,
2316 now: Instant,
2317 space: SpaceId,
2318 ack: frame::Ack,
2319 ) -> Result<(), TransportError> {
2320 let path = PathId::ZERO;
2322 self.inner_on_ack_received(now, space, path, ack)
2323 }
2324
2325 fn on_path_ack_received(
2326 &mut self,
2327 now: Instant,
2328 space: SpaceId,
2329 path_ack: frame::PathAck,
2330 ) -> Result<(), TransportError> {
2331 let (ack, path) = path_ack.into_ack();
2332 self.inner_on_ack_received(now, space, path, ack)
2333 }
2334
2335 fn inner_on_ack_received(
2337 &mut self,
2338 now: Instant,
2339 space: SpaceId,
2340 path: PathId,
2341 ack: frame::Ack,
2342 ) -> Result<(), TransportError> {
2343 if self.abandoned_paths.contains(&path) {
2344 trace!("silently ignoring PATH_ACK on abandoned path");
2347 return Ok(());
2348 }
2349 if ack.largest >= self.spaces[space].for_path(path).next_packet_number {
2350 return Err(TransportError::PROTOCOL_VIOLATION("unsent packet acked"));
2351 }
2352 let new_largest = {
2353 let space = &mut self.spaces[space].for_path(path);
2354 if space.largest_acked_packet.is_none_or(|pn| ack.largest > pn) {
2355 space.largest_acked_packet = Some(ack.largest);
2356 if let Some(info) = space.sent_packets.get(ack.largest) {
2357 space.largest_acked_packet_sent = info.time_sent;
2361 }
2362 true
2363 } else {
2364 false
2365 }
2366 };
2367
2368 if self.detect_spurious_loss(&ack, space, path) {
2369 self.path_data_mut(path)
2370 .congestion
2371 .on_spurious_congestion_event();
2372 }
2373
2374 let mut newly_acked = ArrayRangeSet::new();
2376 for range in ack.iter() {
2377 self.spaces[space].for_path(path).check_ack(range.clone())?;
2378 for (pn, _) in self.spaces[space]
2379 .for_path(path)
2380 .sent_packets
2381 .iter_range(range)
2382 {
2383 newly_acked.insert_one(pn);
2384 }
2385 }
2386
2387 if newly_acked.is_empty() {
2388 return Ok(());
2389 }
2390
2391 let mut ack_eliciting_acked = false;
2392 for packet in newly_acked.elts() {
2393 if let Some(info) = self.spaces[space].for_path(path).take(packet) {
2394 for (acked_path_id, acked_pn) in info.largest_acked.iter() {
2395 if let Some(pns) = self.spaces[space].path_space_mut(*acked_path_id) {
2401 pns.pending_acks.subtract_below(*acked_pn);
2402 }
2403 }
2404 ack_eliciting_acked |= info.ack_eliciting;
2405
2406 let path_data = self.path_data_mut(path);
2408 let mtu_updated = path_data.mtud.on_acked(space, packet, info.size);
2409 if mtu_updated {
2410 path_data
2411 .congestion
2412 .on_mtu_update(path_data.mtud.current_mtu());
2413 }
2414
2415 self.ack_frequency.on_acked(path, packet);
2417
2418 self.on_packet_acked(now, path, info);
2419 }
2420 }
2421
2422 let largest_ackd = self.spaces[space].for_path(path).largest_acked_packet;
2423 let app_limited = self.app_limited;
2424 let path_data = self.path_data_mut(path);
2425 let in_flight = path_data.in_flight.bytes;
2426
2427 path_data
2428 .congestion
2429 .on_end_acks(now, in_flight, app_limited, largest_ackd);
2430
2431 if new_largest && ack_eliciting_acked {
2432 let ack_delay = if space != SpaceId::Data {
2433 Duration::from_micros(0)
2434 } else {
2435 cmp::min(
2436 self.ack_frequency.peer_max_ack_delay,
2437 Duration::from_micros(ack.delay << self.peer_params.ack_delay_exponent.0),
2438 )
2439 };
2440 let rtt = now.saturating_duration_since(
2441 self.spaces[space].for_path(path).largest_acked_packet_sent,
2442 );
2443
2444 let next_pn = self.spaces[space].for_path(path).next_packet_number;
2445 let path_data = self.path_data_mut(path);
2446 path_data.rtt.update(ack_delay, rtt);
2448 if path_data.first_packet_after_rtt_sample.is_none() {
2449 path_data.first_packet_after_rtt_sample = Some((space, next_pn));
2450 }
2451 }
2452
2453 self.detect_lost_packets(now, space, path, true);
2455
2456 if self.peer_completed_address_validation(path) {
2457 self.path_data_mut(path).pto_count = 0;
2458 }
2459
2460 if self.path_data(path).sending_ecn {
2465 if let Some(ecn) = ack.ecn {
2466 if new_largest {
2471 let sent = self.spaces[space].for_path(path).largest_acked_packet_sent;
2472 self.process_ecn(now, space, path, newly_acked.len() as u64, ecn, sent);
2473 }
2474 } else {
2475 debug!("ECN not acknowledged by peer");
2477 self.path_data_mut(path).sending_ecn = false;
2478 }
2479 }
2480
2481 self.set_loss_detection_timer(now, path);
2482 Ok(())
2483 }
2484
2485 fn detect_spurious_loss(&mut self, ack: &frame::Ack, space: SpaceId, path: PathId) -> bool {
2486 let lost_packets = &mut self.spaces[space].for_path(path).lost_packets;
2487
2488 if lost_packets.is_empty() {
2489 return false;
2490 }
2491
2492 for range in ack.iter() {
2493 let spurious_losses: Vec<u64> = lost_packets
2494 .iter_range(range.clone())
2495 .map(|(pn, _info)| pn)
2496 .collect();
2497
2498 for pn in spurious_losses {
2499 lost_packets.remove(pn);
2500 }
2501 }
2502
2503 lost_packets.is_empty()
2508 }
2509
2510 fn drain_lost_packets(&mut self, now: Instant, space: SpaceId, path: PathId) {
2515 let two_pto = 2 * self.path_data(path).rtt.pto_base();
2516
2517 let lost_packets = &mut self.spaces[space].for_path(path).lost_packets;
2518 lost_packets.retain(|_pn, info| now.saturating_duration_since(info.time_sent) <= two_pto);
2519 }
2520
2521 fn process_ecn(
2523 &mut self,
2524 now: Instant,
2525 space: SpaceId,
2526 path: PathId,
2527 newly_acked: u64,
2528 ecn: frame::EcnCounts,
2529 largest_sent_time: Instant,
2530 ) {
2531 match self.spaces[space]
2532 .for_path(path)
2533 .detect_ecn(newly_acked, ecn)
2534 {
2535 Err(e) => {
2536 debug!("halting ECN due to verification failure: {}", e);
2537
2538 self.path_data_mut(path).sending_ecn = false;
2539 self.spaces[space].for_path(path).ecn_feedback = frame::EcnCounts::ZERO;
2542 }
2543 Ok(false) => {}
2544 Ok(true) => {
2545 self.path_stats.entry(path).or_default().congestion_events += 1;
2546 self.path_data_mut(path).congestion.on_congestion_event(
2547 now,
2548 largest_sent_time,
2549 false,
2550 true,
2551 0,
2552 );
2553 }
2554 }
2555 }
2556
2557 fn on_packet_acked(&mut self, now: Instant, path_id: PathId, info: SentPacket) {
2560 self.paths
2561 .get_mut(&path_id)
2562 .expect("known path")
2563 .remove_in_flight(&info);
2564 let app_limited = self.app_limited;
2565 let path = self.path_data_mut(path_id);
2566 if info.ack_eliciting && !path.is_validating_path() {
2567 let rtt = path.rtt;
2570 path.congestion
2571 .on_ack(now, info.time_sent, info.size.into(), app_limited, &rtt);
2572 }
2573
2574 if let Some(retransmits) = info.retransmits.get() {
2576 for (id, _) in retransmits.reset_stream.iter() {
2577 self.streams.reset_acked(*id);
2578 }
2579 }
2580
2581 for frame in info.stream_frames {
2582 self.streams.received_ack_of(frame);
2583 }
2584 }
2585
2586 fn set_key_discard_timer(&mut self, now: Instant, space: SpaceId) {
2587 let start = if self.zero_rtt_crypto.is_some() {
2588 now
2589 } else {
2590 self.prev_crypto
2591 .as_ref()
2592 .expect("no previous keys")
2593 .end_packet
2594 .as_ref()
2595 .expect("update not acknowledged yet")
2596 .1
2597 };
2598
2599 self.timers.set(
2601 Timer::Conn(ConnTimer::KeyDiscard),
2602 start + self.pto_max_path(space) * 3,
2603 self.qlog.with_time(now),
2604 );
2605 }
2606
2607 fn on_loss_detection_timeout(&mut self, now: Instant, path_id: PathId) {
2620 if let Some((_, pn_space)) = self.loss_time_and_space(path_id) {
2621 self.detect_lost_packets(now, pn_space, path_id, false);
2623 self.set_loss_detection_timer(now, path_id);
2624 return;
2625 }
2626
2627 let (_, space) = match self.pto_time_and_space(now, path_id) {
2628 Some(x) => x,
2629 None => {
2630 error!(%path_id, "PTO expired while unset");
2631 return;
2632 }
2633 };
2634 trace!(
2635 in_flight = self.path_data(path_id).in_flight.bytes,
2636 count = self.path_data(path_id).pto_count,
2637 ?space,
2638 %path_id,
2639 "PTO fired"
2640 );
2641
2642 let count = match self.path_data(path_id).in_flight.ack_eliciting {
2643 0 => {
2646 debug_assert!(!self.peer_completed_address_validation(path_id));
2647 1
2648 }
2649 _ => 2,
2651 };
2652 let pns = self.spaces[space].for_path(path_id);
2653 pns.loss_probes = pns.loss_probes.saturating_add(count);
2654 let path_data = self.path_data_mut(path_id);
2655 path_data.pto_count = path_data.pto_count.saturating_add(1);
2656 self.set_loss_detection_timer(now, path_id);
2657 }
2658
2659 fn detect_lost_packets(
2676 &mut self,
2677 now: Instant,
2678 pn_space: SpaceId,
2679 path_id: PathId,
2680 due_to_ack: bool,
2681 ) {
2682 let mut lost_packets = Vec::<u64>::new();
2683 let mut lost_mtu_probe = None;
2684 let mut in_persistent_congestion = false;
2685 let mut size_of_lost_packets = 0u64;
2686 self.spaces[pn_space].for_path(path_id).loss_time = None;
2687
2688 let path = self.path_data(path_id);
2691 let in_flight_mtu_probe = path.mtud.in_flight_mtu_probe();
2692 let loss_delay = path
2693 .rtt
2694 .conservative()
2695 .mul_f32(self.config.time_threshold)
2696 .max(TIMER_GRANULARITY);
2697 let first_packet_after_rtt_sample = path.first_packet_after_rtt_sample;
2698
2699 let largest_acked_packet = self.spaces[pn_space]
2700 .for_path(path_id)
2701 .largest_acked_packet
2702 .expect("detect_lost_packets only to be called if path received at least one ACK");
2703 let packet_threshold = self.config.packet_threshold as u64;
2704
2705 let congestion_period = self
2709 .pto(SpaceId::Data, path_id)
2710 .saturating_mul(self.config.persistent_congestion_threshold);
2711 let mut persistent_congestion_start: Option<Instant> = None;
2712 let mut prev_packet = None;
2713 let space = self.spaces[pn_space].for_path(path_id);
2714
2715 for (packet, info) in space.sent_packets.iter_range(0..largest_acked_packet) {
2716 if prev_packet != Some(packet.wrapping_sub(1)) {
2717 persistent_congestion_start = None;
2719 }
2720
2721 let packet_too_old = now.saturating_duration_since(info.time_sent) >= loss_delay;
2725 if packet_too_old || largest_acked_packet >= packet + packet_threshold {
2726 if Some(packet) == in_flight_mtu_probe {
2728 lost_mtu_probe = in_flight_mtu_probe;
2731 } else {
2732 lost_packets.push(packet);
2733 size_of_lost_packets += info.size as u64;
2734 if info.ack_eliciting && due_to_ack {
2735 match persistent_congestion_start {
2736 Some(start) if info.time_sent - start > congestion_period => {
2739 in_persistent_congestion = true;
2740 }
2741 None if first_packet_after_rtt_sample
2743 .is_some_and(|x| x < (pn_space, packet)) =>
2744 {
2745 persistent_congestion_start = Some(info.time_sent);
2746 }
2747 _ => {}
2748 }
2749 }
2750 }
2751 } else {
2752 if space.loss_time.is_none() {
2754 space.loss_time = Some(info.time_sent + loss_delay);
2757 }
2758 persistent_congestion_start = None;
2759 }
2760
2761 prev_packet = Some(packet);
2762 }
2763
2764 self.handle_lost_packets(
2765 pn_space,
2766 path_id,
2767 now,
2768 lost_packets,
2769 lost_mtu_probe,
2770 loss_delay,
2771 in_persistent_congestion,
2772 size_of_lost_packets,
2773 );
2774 }
2775
2776 fn discard_path(&mut self, path_id: PathId, now: Instant) {
2778 trace!(%path_id, "dropping path state");
2779 let path = self.path_data(path_id);
2780 let in_flight_mtu_probe = path.mtud.in_flight_mtu_probe();
2781
2782 let mut size_of_lost_packets = 0u64; let lost_pns: Vec<_> = self.spaces[SpaceId::Data]
2784 .for_path(path_id)
2785 .sent_packets
2786 .iter()
2787 .filter(|(pn, _info)| Some(*pn) != in_flight_mtu_probe)
2788 .map(|(pn, info)| {
2789 size_of_lost_packets += info.size as u64;
2790 pn
2791 })
2792 .collect();
2793
2794 if !lost_pns.is_empty() {
2795 trace!(
2796 %path_id,
2797 count = lost_pns.len(),
2798 lost_bytes = size_of_lost_packets,
2799 "packets lost on path abandon"
2800 );
2801 self.handle_lost_packets(
2802 SpaceId::Data,
2803 path_id,
2804 now,
2805 lost_pns,
2806 in_flight_mtu_probe,
2807 Duration::ZERO,
2808 false,
2809 size_of_lost_packets,
2810 );
2811 }
2812 self.paths.remove(&path_id);
2813 self.spaces[SpaceId::Data].number_spaces.remove(&path_id);
2814
2815 let path_stats = self.path_stats.remove(&path_id).unwrap_or_default();
2816 self.events.push_back(
2817 PathEvent::Abandoned {
2818 id: path_id,
2819 path_stats,
2820 }
2821 .into(),
2822 );
2823 }
2824
2825 fn handle_lost_packets(
2826 &mut self,
2827 pn_space: SpaceId,
2828 path_id: PathId,
2829 now: Instant,
2830 lost_packets: Vec<u64>,
2831 lost_mtu_probe: Option<u64>,
2832 loss_delay: Duration,
2833 in_persistent_congestion: bool,
2834 size_of_lost_packets: u64,
2835 ) {
2836 debug_assert!(
2837 {
2838 let mut sorted = lost_packets.clone();
2839 sorted.sort();
2840 sorted == lost_packets
2841 },
2842 "lost_packets must be sorted"
2843 );
2844
2845 self.drain_lost_packets(now, pn_space, path_id);
2846
2847 if let Some(largest_lost) = lost_packets.last().cloned() {
2849 let old_bytes_in_flight = self.path_data_mut(path_id).in_flight.bytes;
2850 let largest_lost_sent = self.spaces[pn_space]
2851 .for_path(path_id)
2852 .sent_packets
2853 .get(largest_lost)
2854 .unwrap()
2855 .time_sent;
2856 let path_stats = self.path_stats.entry(path_id).or_default();
2857 path_stats.lost_packets += lost_packets.len() as u64;
2858 path_stats.lost_bytes += size_of_lost_packets;
2859 trace!(
2860 %path_id,
2861 count = lost_packets.len(),
2862 lost_bytes = size_of_lost_packets,
2863 "packets lost",
2864 );
2865
2866 for &packet in &lost_packets {
2867 let Some(info) = self.spaces[pn_space].for_path(path_id).take(packet) else {
2868 continue;
2869 };
2870 self.qlog
2871 .emit_packet_lost(packet, &info, loss_delay, pn_space, now);
2872 self.paths
2873 .get_mut(&path_id)
2874 .unwrap()
2875 .remove_in_flight(&info);
2876
2877 for frame in info.stream_frames {
2878 self.streams.retransmit(frame);
2879 }
2880 self.spaces[pn_space].pending |= info.retransmits;
2881 self.path_data_mut(path_id)
2882 .mtud
2883 .on_non_probe_lost(packet, info.size);
2884
2885 self.spaces[pn_space].for_path(path_id).lost_packets.insert(
2886 packet,
2887 LostPacket {
2888 time_sent: info.time_sent,
2889 },
2890 );
2891 }
2892
2893 let path = self.path_data_mut(path_id);
2894 if path.mtud.black_hole_detected(now) {
2895 path.congestion.on_mtu_update(path.mtud.current_mtu());
2896 if let Some(max_datagram_size) = self.datagrams().max_size() {
2897 self.datagrams.drop_oversized(max_datagram_size);
2898 }
2899 self.path_stats
2900 .entry(path_id)
2901 .or_default()
2902 .black_holes_detected += 1;
2903 }
2904
2905 let lost_ack_eliciting =
2907 old_bytes_in_flight != self.path_data_mut(path_id).in_flight.bytes;
2908
2909 if lost_ack_eliciting {
2910 self.path_stats
2911 .entry(path_id)
2912 .or_default()
2913 .congestion_events += 1;
2914 self.path_data_mut(path_id).congestion.on_congestion_event(
2915 now,
2916 largest_lost_sent,
2917 in_persistent_congestion,
2918 false,
2919 size_of_lost_packets,
2920 );
2921 }
2922 }
2923
2924 if let Some(packet) = lost_mtu_probe {
2926 let info = self.spaces[SpaceId::Data]
2927 .for_path(path_id)
2928 .take(packet)
2929 .unwrap(); self.paths
2932 .get_mut(&path_id)
2933 .unwrap()
2934 .remove_in_flight(&info);
2935 self.path_data_mut(path_id).mtud.on_probe_lost();
2936 self.path_stats
2937 .entry(path_id)
2938 .or_default()
2939 .lost_plpmtud_probes += 1;
2940 }
2941 }
2942
2943 fn loss_time_and_space(&self, path_id: PathId) -> Option<(Instant, SpaceId)> {
2949 SpaceId::iter()
2950 .filter_map(|id| {
2951 self.spaces[id]
2952 .number_spaces
2953 .get(&path_id)
2954 .and_then(|pns| pns.loss_time)
2955 .map(|time| (time, id))
2956 })
2957 .min_by_key(|&(time, _)| time)
2958 }
2959
2960 fn pto_time_and_space(&mut self, now: Instant, path_id: PathId) -> Option<(Instant, SpaceId)> {
2962 let path = self.path(path_id)?;
2963 let pto_count = path.pto_count;
2964 let backoff = 2u32.pow(pto_count.min(MAX_BACKOFF_EXPONENT));
2965 let mut duration = path.rtt.pto_base() * backoff;
2966
2967 if path_id == PathId::ZERO
2968 && path.in_flight.ack_eliciting == 0
2969 && !self.peer_completed_address_validation(PathId::ZERO)
2970 {
2971 let space = match self.highest_space {
2977 SpaceId::Handshake => SpaceId::Handshake,
2978 _ => SpaceId::Initial,
2979 };
2980
2981 return Some((now + duration, space));
2982 }
2983
2984 let mut result = None;
2985 for space in SpaceId::iter() {
2986 let Some(pns) = self.spaces[space].number_spaces.get(&path_id) else {
2987 continue;
2988 };
2989
2990 if !pns.has_in_flight() {
2991 continue;
2992 }
2993 if space == SpaceId::Data {
2994 if self.is_handshaking() {
2996 return result;
2997 }
2998 duration += self.ack_frequency.max_ack_delay_for_pto() * backoff;
3000 }
3001 let Some(last_ack_eliciting) = pns.time_of_last_ack_eliciting_packet else {
3002 continue;
3003 };
3004 let pto = last_ack_eliciting + duration;
3005 if result.is_none_or(|(earliest_pto, _)| pto < earliest_pto) {
3006 if path.anti_amplification_blocked(1) {
3007 continue;
3009 }
3010 if path.in_flight.ack_eliciting == 0 {
3011 continue;
3013 }
3014 result = Some((pto, space));
3015 }
3016 }
3017 result
3018 }
3019
3020 fn peer_completed_address_validation(&self, path: PathId) -> bool {
3021 if self.side.is_server() || self.state.is_closed() {
3023 return true;
3024 }
3025 self.spaces[SpaceId::Handshake]
3028 .path_space(PathId::ZERO)
3029 .and_then(|pns| pns.largest_acked_packet)
3030 .is_some()
3031 || self.spaces[SpaceId::Data]
3032 .path_space(path)
3033 .and_then(|pns| pns.largest_acked_packet)
3034 .is_some()
3035 || (self.spaces[SpaceId::Data].crypto.is_some()
3036 && self.spaces[SpaceId::Handshake].crypto.is_none())
3037 }
3038
3039 fn set_loss_detection_timer(&mut self, now: Instant, path_id: PathId) {
3047 if self.state.is_closed() {
3048 return;
3052 }
3053
3054 if let Some((loss_time, _)) = self.loss_time_and_space(path_id) {
3055 self.timers.set(
3057 Timer::PerPath(path_id, PathTimer::LossDetection),
3058 loss_time,
3059 self.qlog.with_time(now),
3060 );
3061 return;
3062 }
3063
3064 if let Some((timeout, _)) = self.pto_time_and_space(now, path_id) {
3067 self.timers.set(
3068 Timer::PerPath(path_id, PathTimer::LossDetection),
3069 timeout,
3070 self.qlog.with_time(now),
3071 );
3072 } else {
3073 self.timers.stop(
3074 Timer::PerPath(path_id, PathTimer::LossDetection),
3075 self.qlog.with_time(now),
3076 );
3077 }
3078 }
3079
3080 fn pto_max_path(&self, space: SpaceId) -> Duration {
3084 match space {
3085 SpaceId::Initial | SpaceId::Handshake => self.pto(space, PathId::ZERO),
3086 SpaceId::Data => self
3087 .paths
3088 .keys()
3089 .map(|path_id| self.pto(space, *path_id))
3090 .max()
3091 .expect("there should be one at least path"),
3092 }
3093 }
3094
3095 fn pto(&self, space: SpaceId, path_id: PathId) -> Duration {
3100 let max_ack_delay = match space {
3101 SpaceId::Initial | SpaceId::Handshake => Duration::ZERO,
3102 SpaceId::Data => self.ack_frequency.max_ack_delay_for_pto(),
3103 };
3104 self.path_data(path_id).rtt.pto_base() + max_ack_delay
3105 }
3106
3107 fn on_packet_authenticated(
3108 &mut self,
3109 now: Instant,
3110 space_id: SpaceId,
3111 path_id: PathId,
3112 ecn: Option<EcnCodepoint>,
3113 packet: Option<u64>,
3114 spin: bool,
3115 is_1rtt: bool,
3116 ) {
3117 self.total_authed_packets += 1;
3118 if let Some(last_allowed_receive) = self
3119 .paths
3120 .get(&path_id)
3121 .and_then(|path| path.data.last_allowed_receive)
3122 {
3123 if now > last_allowed_receive {
3124 warn!("received data on path which we abandoned more than 3 * PTO ago");
3125 if !self.state.is_closed() {
3127 self.state.move_to_closed(TransportError::NO_ERROR(
3129 "peer failed to respond with PATH_ABANDON in time",
3130 ));
3131 self.close_common();
3132 self.set_close_timer(now);
3133 self.close = true;
3134 }
3135 return;
3136 }
3137 }
3138
3139 self.reset_keep_alive(path_id, now);
3140 self.reset_idle_timeout(now, space_id, path_id);
3141 self.permit_idle_reset = true;
3142 self.receiving_ecn |= ecn.is_some();
3143 if let Some(x) = ecn {
3144 let space = &mut self.spaces[space_id];
3145 space.for_path(path_id).ecn_counters += x;
3146
3147 if x.is_ce() {
3148 space
3149 .for_path(path_id)
3150 .pending_acks
3151 .set_immediate_ack_required();
3152 }
3153 }
3154
3155 let packet = match packet {
3156 Some(x) => x,
3157 None => return,
3158 };
3159 match &self.side {
3160 ConnectionSide::Client { .. } => {
3161 if space_id == SpaceId::Handshake {
3165 if let Some(hs) = self.state.as_handshake_mut() {
3166 hs.allow_server_migration = false;
3167 }
3168 }
3169 }
3170 ConnectionSide::Server { .. } => {
3171 if self.spaces[SpaceId::Initial].crypto.is_some() && space_id == SpaceId::Handshake
3172 {
3173 self.discard_space(now, SpaceId::Initial);
3175 }
3176 if self.zero_rtt_crypto.is_some() && is_1rtt {
3177 self.set_key_discard_timer(now, space_id)
3179 }
3180 }
3181 }
3182 let space = self.spaces[space_id].for_path(path_id);
3183 space.pending_acks.insert_one(packet, now);
3184 if packet >= space.rx_packet.unwrap_or_default() {
3185 space.rx_packet = Some(packet);
3186 self.spin = self.side.is_client() ^ spin;
3188 }
3189 }
3190
3191 fn reset_idle_timeout(&mut self, now: Instant, space: SpaceId, path_id: PathId) {
3196 if let Some(timeout) = self.idle_timeout {
3198 if self.state.is_closed() {
3199 self.timers
3200 .stop(Timer::Conn(ConnTimer::Idle), self.qlog.with_time(now));
3201 } else {
3202 let dt = cmp::max(timeout, 3 * self.pto_max_path(space));
3203 self.timers.set(
3204 Timer::Conn(ConnTimer::Idle),
3205 now + dt,
3206 self.qlog.with_time(now),
3207 );
3208 }
3209 }
3210
3211 if let Some(timeout) = self.path_data(path_id).idle_timeout {
3213 if self.state.is_closed() {
3214 self.timers.stop(
3215 Timer::PerPath(path_id, PathTimer::PathIdle),
3216 self.qlog.with_time(now),
3217 );
3218 } else {
3219 let dt = cmp::max(timeout, 3 * self.pto(space, path_id));
3220 self.timers.set(
3221 Timer::PerPath(path_id, PathTimer::PathIdle),
3222 now + dt,
3223 self.qlog.with_time(now),
3224 );
3225 }
3226 }
3227 }
3228
3229 fn reset_keep_alive(&mut self, path_id: PathId, now: Instant) {
3231 if !self.state.is_established() {
3232 return;
3233 }
3234
3235 if let Some(interval) = self.config.keep_alive_interval {
3236 self.timers.set(
3237 Timer::Conn(ConnTimer::KeepAlive),
3238 now + interval,
3239 self.qlog.with_time(now),
3240 );
3241 }
3242
3243 if let Some(interval) = self.path_data(path_id).keep_alive {
3244 self.timers.set(
3245 Timer::PerPath(path_id, PathTimer::PathKeepAlive),
3246 now + interval,
3247 self.qlog.with_time(now),
3248 );
3249 }
3250 }
3251
3252 fn reset_cid_retirement(&mut self, now: Instant) {
3254 if let Some((_path, t)) = self.next_cid_retirement() {
3255 self.timers.set(
3256 Timer::Conn(ConnTimer::PushNewCid),
3257 t,
3258 self.qlog.with_time(now),
3259 );
3260 }
3261 }
3262
3263 fn next_cid_retirement(&self) -> Option<(PathId, Instant)> {
3265 self.local_cid_state
3266 .iter()
3267 .filter_map(|(path_id, cid_state)| cid_state.next_timeout().map(|t| (*path_id, t)))
3268 .min_by_key(|(_path_id, timeout)| *timeout)
3269 }
3270
3271 pub(crate) fn handle_first_packet(
3276 &mut self,
3277 now: Instant,
3278 remote: SocketAddr,
3279 ecn: Option<EcnCodepoint>,
3280 packet_number: u64,
3281 packet: InitialPacket,
3282 remaining: Option<BytesMut>,
3283 ) -> Result<(), ConnectionError> {
3284 let span = trace_span!("first recv");
3285 let _guard = span.enter();
3286 debug_assert!(self.side.is_server());
3287 let len = packet.header_data.len() + packet.payload.len();
3288 let path_id = PathId::ZERO;
3289 self.path_data_mut(path_id).total_recvd = len as u64;
3290
3291 if let Some(hs) = self.state.as_handshake_mut() {
3292 hs.expected_token = packet.header.token.clone();
3293 } else {
3294 unreachable!("first packet must be delivered in Handshake state");
3295 }
3296
3297 self.on_packet_authenticated(
3299 now,
3300 SpaceId::Initial,
3301 path_id,
3302 ecn,
3303 Some(packet_number),
3304 false,
3305 false,
3306 );
3307
3308 let packet: Packet = packet.into();
3309
3310 let mut qlog = QlogRecvPacket::new(len);
3311 qlog.header(&packet.header, Some(packet_number), path_id);
3312
3313 self.process_decrypted_packet(
3314 now,
3315 remote,
3316 path_id,
3317 Some(packet_number),
3318 packet,
3319 &mut qlog,
3320 )?;
3321 self.qlog.emit_packet_received(qlog, now);
3322 if let Some(data) = remaining {
3323 self.handle_coalesced(now, remote, path_id, ecn, data);
3324 }
3325
3326 self.qlog.emit_recovery_metrics(
3327 path_id,
3328 &mut self.paths.get_mut(&path_id).unwrap().data,
3329 now,
3330 );
3331
3332 Ok(())
3333 }
3334
3335 fn init_0rtt(&mut self, now: Instant) {
3336 let (header, packet) = match self.crypto.early_crypto() {
3337 Some(x) => x,
3338 None => return,
3339 };
3340 if self.side.is_client() {
3341 match self.crypto.transport_parameters() {
3342 Ok(params) => {
3343 let params = params
3344 .expect("crypto layer didn't supply transport parameters with ticket");
3345 let params = TransportParameters {
3347 initial_src_cid: None,
3348 original_dst_cid: None,
3349 preferred_address: None,
3350 retry_src_cid: None,
3351 stateless_reset_token: None,
3352 min_ack_delay: None,
3353 ack_delay_exponent: TransportParameters::default().ack_delay_exponent,
3354 max_ack_delay: TransportParameters::default().max_ack_delay,
3355 initial_max_path_id: None,
3356 ..params
3357 };
3358 self.set_peer_params(params);
3359 self.qlog.emit_peer_transport_params_restored(self, now);
3360 }
3361 Err(e) => {
3362 error!("session ticket has malformed transport parameters: {}", e);
3363 return;
3364 }
3365 }
3366 }
3367 trace!("0-RTT enabled");
3368 self.zero_rtt_enabled = true;
3369 self.zero_rtt_crypto = Some(ZeroRttCrypto { header, packet });
3370 }
3371
3372 fn read_crypto(
3373 &mut self,
3374 space: SpaceId,
3375 crypto: &frame::Crypto,
3376 payload_len: usize,
3377 ) -> Result<(), TransportError> {
3378 let expected = if !self.state.is_handshake() {
3379 SpaceId::Data
3380 } else if self.highest_space == SpaceId::Initial {
3381 SpaceId::Initial
3382 } else {
3383 SpaceId::Handshake
3386 };
3387 debug_assert!(space <= expected, "received out-of-order CRYPTO data");
3391
3392 let end = crypto.offset + crypto.data.len() as u64;
3393 if space < expected && end > self.spaces[space].crypto_stream.bytes_read() {
3394 warn!(
3395 "received new {:?} CRYPTO data when expecting {:?}",
3396 space, expected
3397 );
3398 return Err(TransportError::PROTOCOL_VIOLATION(
3399 "new data at unexpected encryption level",
3400 ));
3401 }
3402
3403 let space = &mut self.spaces[space];
3404 let max = end.saturating_sub(space.crypto_stream.bytes_read());
3405 if max > self.config.crypto_buffer_size as u64 {
3406 return Err(TransportError::CRYPTO_BUFFER_EXCEEDED(""));
3407 }
3408
3409 space
3410 .crypto_stream
3411 .insert(crypto.offset, crypto.data.clone(), payload_len);
3412 while let Some(chunk) = space.crypto_stream.read(usize::MAX, true) {
3413 trace!("consumed {} CRYPTO bytes", chunk.bytes.len());
3414 if self.crypto.read_handshake(&chunk.bytes)? {
3415 self.events.push_back(Event::HandshakeDataReady);
3416 }
3417 }
3418
3419 Ok(())
3420 }
3421
3422 fn write_crypto(&mut self) {
3423 loop {
3424 let space = self.highest_space;
3425 let mut outgoing = Vec::new();
3426 if let Some(crypto) = self.crypto.write_handshake(&mut outgoing) {
3427 match space {
3428 SpaceId::Initial => {
3429 self.upgrade_crypto(SpaceId::Handshake, crypto);
3430 }
3431 SpaceId::Handshake => {
3432 self.upgrade_crypto(SpaceId::Data, crypto);
3433 }
3434 _ => unreachable!("got updated secrets during 1-RTT"),
3435 }
3436 }
3437 if outgoing.is_empty() {
3438 if space == self.highest_space {
3439 break;
3440 } else {
3441 continue;
3443 }
3444 }
3445 let offset = self.spaces[space].crypto_offset;
3446 let outgoing = Bytes::from(outgoing);
3447 if let Some(hs) = self.state.as_handshake_mut() {
3448 if space == SpaceId::Initial && offset == 0 && self.side.is_client() {
3449 hs.client_hello = Some(outgoing.clone());
3450 }
3451 }
3452 self.spaces[space].crypto_offset += outgoing.len() as u64;
3453 trace!("wrote {} {:?} CRYPTO bytes", outgoing.len(), space);
3454 self.spaces[space].pending.crypto.push_back(frame::Crypto {
3455 offset,
3456 data: outgoing,
3457 });
3458 }
3459 }
3460
3461 fn upgrade_crypto(&mut self, space: SpaceId, crypto: Keys) {
3463 debug_assert!(
3464 self.spaces[space].crypto.is_none(),
3465 "already reached packet space {space:?}"
3466 );
3467 trace!("{:?} keys ready", space);
3468 if space == SpaceId::Data {
3469 self.next_crypto = Some(
3471 self.crypto
3472 .next_1rtt_keys()
3473 .expect("handshake should be complete"),
3474 );
3475 }
3476
3477 self.spaces[space].crypto = Some(crypto);
3478 debug_assert!(space as usize > self.highest_space as usize);
3479 self.highest_space = space;
3480 if space == SpaceId::Data && self.side.is_client() {
3481 self.zero_rtt_crypto = None;
3483 }
3484 }
3485
3486 fn discard_space(&mut self, now: Instant, space_id: SpaceId) {
3487 debug_assert!(space_id != SpaceId::Data);
3488 trace!("discarding {:?} keys", space_id);
3489 if space_id == SpaceId::Initial {
3490 if let ConnectionSide::Client { token, .. } = &mut self.side {
3492 *token = Bytes::new();
3493 }
3494 }
3495 let space = &mut self.spaces[space_id];
3496 space.crypto = None;
3497 let pns = space.for_path(PathId::ZERO);
3498 pns.time_of_last_ack_eliciting_packet = None;
3499 pns.loss_time = None;
3500 pns.loss_probes = 0;
3501 let sent_packets = mem::take(&mut pns.sent_packets);
3502 let path = self.paths.get_mut(&PathId::ZERO).unwrap();
3503 for (_, packet) in sent_packets.into_iter() {
3504 path.data.remove_in_flight(&packet);
3505 }
3506
3507 self.set_loss_detection_timer(now, PathId::ZERO)
3508 }
3509
3510 fn handle_coalesced(
3511 &mut self,
3512 now: Instant,
3513 remote: SocketAddr,
3514 path_id: PathId,
3515 ecn: Option<EcnCodepoint>,
3516 data: BytesMut,
3517 ) {
3518 self.path_data_mut(path_id)
3519 .inc_total_recvd(data.len() as u64);
3520 let mut remaining = Some(data);
3521 let cid_len = self
3522 .local_cid_state
3523 .values()
3524 .map(|cid_state| cid_state.cid_len())
3525 .next()
3526 .expect("one cid_state must exist");
3527 while let Some(data) = remaining {
3528 match PartialDecode::new(
3529 data,
3530 &FixedLengthConnectionIdParser::new(cid_len),
3531 &[self.version],
3532 self.endpoint_config.grease_quic_bit,
3533 ) {
3534 Ok((partial_decode, rest)) => {
3535 remaining = rest;
3536 self.handle_decode(now, remote, path_id, ecn, partial_decode);
3537 }
3538 Err(e) => {
3539 trace!("malformed header: {}", e);
3540 return;
3541 }
3542 }
3543 }
3544 }
3545
3546 fn handle_decode(
3547 &mut self,
3548 now: Instant,
3549 remote: SocketAddr,
3550 path_id: PathId,
3551 ecn: Option<EcnCodepoint>,
3552 partial_decode: PartialDecode,
3553 ) {
3554 let qlog = QlogRecvPacket::new(partial_decode.len());
3555 if let Some(decoded) = packet_crypto::unprotect_header(
3556 partial_decode,
3557 &self.spaces,
3558 self.zero_rtt_crypto.as_ref(),
3559 self.peer_params.stateless_reset_token,
3560 ) {
3561 self.handle_packet(
3562 now,
3563 remote,
3564 path_id,
3565 ecn,
3566 decoded.packet,
3567 decoded.stateless_reset,
3568 qlog,
3569 );
3570 }
3571 }
3572
3573 fn handle_packet(
3574 &mut self,
3575 now: Instant,
3576 remote: SocketAddr,
3577 path_id: PathId,
3578 ecn: Option<EcnCodepoint>,
3579 packet: Option<Packet>,
3580 stateless_reset: bool,
3581 mut qlog: QlogRecvPacket,
3582 ) {
3583 self.stats.udp_rx.ios += 1;
3584 if let Some(ref packet) = packet {
3585 trace!(
3586 "got {:?} packet ({} bytes) from {} using id {}",
3587 packet.header.space(),
3588 packet.payload.len() + packet.header_data.len(),
3589 remote,
3590 packet.header.dst_cid(),
3591 );
3592 }
3593
3594 if self.is_handshaking() {
3595 if path_id != PathId::ZERO {
3596 debug!(%remote, %path_id, "discarding multipath packet during handshake");
3597 return;
3598 }
3599 if remote != self.path_data_mut(path_id).remote {
3600 if let Some(hs) = self.state.as_handshake() {
3601 if hs.allow_server_migration {
3602 trace!(?remote, prev = ?self.path_data(path_id).remote, "server migrated to new remote");
3603 self.path_data_mut(path_id).remote = remote;
3604 self.qlog.emit_tuple_assigned(path_id, remote, now);
3605 } else {
3606 debug!("discarding packet with unexpected remote during handshake");
3607 return;
3608 }
3609 } else {
3610 debug!("discarding packet with unexpected remote during handshake");
3611 return;
3612 }
3613 }
3614 }
3615
3616 let was_closed = self.state.is_closed();
3617 let was_drained = self.state.is_drained();
3618
3619 let decrypted = match packet {
3620 None => Err(None),
3621 Some(mut packet) => self
3622 .decrypt_packet(now, path_id, &mut packet)
3623 .map(move |number| (packet, number)),
3624 };
3625 let result = match decrypted {
3626 _ if stateless_reset => {
3627 debug!("got stateless reset");
3628 Err(ConnectionError::Reset)
3629 }
3630 Err(Some(e)) => {
3631 warn!("illegal packet: {}", e);
3632 Err(e.into())
3633 }
3634 Err(None) => {
3635 debug!("failed to authenticate packet");
3636 self.authentication_failures += 1;
3637 let integrity_limit = self.spaces[self.highest_space]
3638 .crypto
3639 .as_ref()
3640 .unwrap()
3641 .packet
3642 .local
3643 .integrity_limit();
3644 if self.authentication_failures > integrity_limit {
3645 Err(TransportError::AEAD_LIMIT_REACHED("integrity limit violated").into())
3646 } else {
3647 return;
3648 }
3649 }
3650 Ok((packet, number)) => {
3651 qlog.header(&packet.header, number, path_id);
3652 let span = match number {
3653 Some(pn) => trace_span!("recv", space = ?packet.header.space(), pn),
3654 None => trace_span!("recv", space = ?packet.header.space()),
3655 };
3656 let _guard = span.enter();
3657
3658 let dedup = self.spaces[packet.header.space()]
3659 .path_space_mut(path_id)
3660 .map(|pns| &mut pns.dedup);
3661 if number.zip(dedup).is_some_and(|(n, d)| d.insert(n)) {
3662 debug!("discarding possible duplicate packet");
3663 self.qlog.emit_packet_received(qlog, now);
3664 return;
3665 } else if self.state.is_handshake() && packet.header.is_short() {
3666 trace!("dropping short packet during handshake");
3668 self.qlog.emit_packet_received(qlog, now);
3669 return;
3670 } else {
3671 if let Header::Initial(InitialHeader { ref token, .. }) = packet.header {
3672 if let Some(hs) = self.state.as_handshake() {
3673 if self.side.is_server() && token != &hs.expected_token {
3674 warn!("discarding Initial with invalid retry token");
3678 self.qlog.emit_packet_received(qlog, now);
3679 return;
3680 }
3681 }
3682 }
3683
3684 if !self.state.is_closed() {
3685 let spin = match packet.header {
3686 Header::Short { spin, .. } => spin,
3687 _ => false,
3688 };
3689
3690 if self.side().is_server() && !self.abandoned_paths.contains(&path_id) {
3691 self.ensure_path(path_id, remote, now, number);
3693 }
3694 if self.paths.contains_key(&path_id) {
3695 self.on_packet_authenticated(
3696 now,
3697 packet.header.space(),
3698 path_id,
3699 ecn,
3700 number,
3701 spin,
3702 packet.header.is_1rtt(),
3703 );
3704 }
3705 }
3706
3707 let res = self
3708 .process_decrypted_packet(now, remote, path_id, number, packet, &mut qlog);
3709
3710 self.qlog.emit_packet_received(qlog, now);
3711 res
3712 }
3713 }
3714 };
3715
3716 if let Err(conn_err) = result {
3718 match conn_err {
3719 ConnectionError::ApplicationClosed(reason) => self.state.move_to_closed(reason),
3720 ConnectionError::ConnectionClosed(reason) => self.state.move_to_closed(reason),
3721 ConnectionError::Reset
3722 | ConnectionError::TransportError(TransportError {
3723 code: TransportErrorCode::AEAD_LIMIT_REACHED,
3724 ..
3725 }) => {
3726 self.state.move_to_drained(Some(conn_err));
3727 }
3728 ConnectionError::TimedOut => {
3729 unreachable!("timeouts aren't generated by packet processing");
3730 }
3731 ConnectionError::TransportError(err) => {
3732 debug!("closing connection due to transport error: {}", err);
3733 self.state.move_to_closed(err);
3734 }
3735 ConnectionError::VersionMismatch => {
3736 self.state.move_to_draining(Some(conn_err));
3737 }
3738 ConnectionError::LocallyClosed => {
3739 unreachable!("LocallyClosed isn't generated by packet processing");
3740 }
3741 ConnectionError::CidsExhausted => {
3742 unreachable!("CidsExhausted isn't generated by packet processing");
3743 }
3744 };
3745 }
3746
3747 if !was_closed && self.state.is_closed() {
3748 self.close_common();
3749 if !self.state.is_drained() {
3750 self.set_close_timer(now);
3751 }
3752 }
3753 if !was_drained && self.state.is_drained() {
3754 self.endpoint_events.push_back(EndpointEventInner::Drained);
3755 self.timers
3758 .stop(Timer::Conn(ConnTimer::Close), self.qlog.with_time(now));
3759 }
3760
3761 if matches!(self.state.as_type(), StateType::Closed) {
3763 let path_remote = self
3767 .paths
3768 .get(&path_id)
3769 .map(|p| p.data.remote)
3770 .unwrap_or(remote);
3771 self.close = remote == path_remote;
3772 }
3773 }
3774
3775 fn process_decrypted_packet(
3776 &mut self,
3777 now: Instant,
3778 remote: SocketAddr,
3779 path_id: PathId,
3780 number: Option<u64>,
3781 packet: Packet,
3782 qlog: &mut QlogRecvPacket,
3783 ) -> Result<(), ConnectionError> {
3784 if !self.paths.contains_key(&path_id) {
3785 trace!(%path_id, ?number, "discarding packet for unknown path");
3789 return Ok(());
3790 }
3791 let state = match self.state.as_type() {
3792 StateType::Established => {
3793 match packet.header.space() {
3794 SpaceId::Data => {
3795 self.process_payload(now, remote, path_id, number.unwrap(), packet, qlog)?
3796 }
3797 _ if packet.header.has_frames() => {
3798 self.process_early_payload(now, path_id, packet, qlog)?
3799 }
3800 _ => {
3801 trace!("discarding unexpected pre-handshake packet");
3802 }
3803 }
3804 return Ok(());
3805 }
3806 StateType::Closed => {
3807 for result in frame::Iter::new(packet.payload.freeze())? {
3808 let frame = match result {
3809 Ok(frame) => frame,
3810 Err(err) => {
3811 debug!("frame decoding error: {err:?}");
3812 continue;
3813 }
3814 };
3815 qlog.frame(&frame);
3816
3817 if let Frame::Padding = frame {
3818 continue;
3819 };
3820
3821 self.stats.frame_rx.record(&frame);
3822
3823 if let Frame::Close(_error) = frame {
3824 trace!("draining");
3825 self.state.move_to_draining(None);
3826 break;
3827 }
3828 }
3829 return Ok(());
3830 }
3831 StateType::Draining | StateType::Drained => return Ok(()),
3832 StateType::Handshake => self.state.as_handshake_mut().expect("checked"),
3833 };
3834
3835 match packet.header {
3836 Header::Retry {
3837 src_cid: rem_cid, ..
3838 } => {
3839 debug_assert_eq!(path_id, PathId::ZERO);
3840 if self.side.is_server() {
3841 return Err(TransportError::PROTOCOL_VIOLATION("client sent Retry").into());
3842 }
3843
3844 let is_valid_retry = self
3845 .rem_cids
3846 .get(&path_id)
3847 .map(|cids| cids.active())
3848 .map(|orig_dst_cid| {
3849 self.crypto.is_valid_retry(
3850 orig_dst_cid,
3851 &packet.header_data,
3852 &packet.payload,
3853 )
3854 })
3855 .unwrap_or_default();
3856 if self.total_authed_packets > 1
3857 || packet.payload.len() <= 16 || !is_valid_retry
3859 {
3860 trace!("discarding invalid Retry");
3861 return Ok(());
3869 }
3870
3871 trace!("retrying with CID {}", rem_cid);
3872 let client_hello = state.client_hello.take().unwrap();
3873 self.retry_src_cid = Some(rem_cid);
3874 self.rem_cids
3875 .get_mut(&path_id)
3876 .expect("PathId::ZERO not yet abandoned, is_valid_retry would have been false")
3877 .update_initial_cid(rem_cid);
3878 self.rem_handshake_cid = rem_cid;
3879
3880 let space = &mut self.spaces[SpaceId::Initial];
3881 if let Some(info) = space.for_path(PathId::ZERO).take(0) {
3882 self.on_packet_acked(now, PathId::ZERO, info);
3883 };
3884
3885 self.discard_space(now, SpaceId::Initial); self.spaces[SpaceId::Initial] = {
3888 let mut space = PacketSpace::new(now, SpaceId::Initial, &mut self.rng);
3889 space.crypto = Some(self.crypto.initial_keys(rem_cid, self.side.side()));
3890 space.crypto_offset = client_hello.len() as u64;
3891 space.for_path(path_id).next_packet_number = self.spaces[SpaceId::Initial]
3892 .for_path(path_id)
3893 .next_packet_number;
3894 space.pending.crypto.push_back(frame::Crypto {
3895 offset: 0,
3896 data: client_hello,
3897 });
3898 space
3899 };
3900
3901 let zero_rtt = mem::take(
3903 &mut self.spaces[SpaceId::Data]
3904 .for_path(PathId::ZERO)
3905 .sent_packets,
3906 );
3907 for (_, info) in zero_rtt.into_iter() {
3908 self.paths
3909 .get_mut(&PathId::ZERO)
3910 .unwrap()
3911 .remove_in_flight(&info);
3912 self.spaces[SpaceId::Data].pending |= info.retransmits;
3913 }
3914 self.streams.retransmit_all_for_0rtt();
3915
3916 let token_len = packet.payload.len() - 16;
3917 let ConnectionSide::Client { ref mut token, .. } = self.side else {
3918 unreachable!("we already short-circuited if we're server");
3919 };
3920 *token = packet.payload.freeze().split_to(token_len);
3921
3922 self.state = State::handshake(state::Handshake {
3923 expected_token: Bytes::new(),
3924 rem_cid_set: false,
3925 client_hello: None,
3926 allow_server_migration: true,
3927 });
3928 Ok(())
3929 }
3930 Header::Long {
3931 ty: LongType::Handshake,
3932 src_cid: rem_cid,
3933 dst_cid: loc_cid,
3934 ..
3935 } => {
3936 debug_assert_eq!(path_id, PathId::ZERO);
3937 if rem_cid != self.rem_handshake_cid {
3938 debug!(
3939 "discarding packet with mismatched remote CID: {} != {}",
3940 self.rem_handshake_cid, rem_cid
3941 );
3942 return Ok(());
3943 }
3944 self.on_path_validated(path_id);
3945
3946 self.process_early_payload(now, path_id, packet, qlog)?;
3947 if self.state.is_closed() {
3948 return Ok(());
3949 }
3950
3951 if self.crypto.is_handshaking() {
3952 trace!("handshake ongoing");
3953 return Ok(());
3954 }
3955
3956 if self.side.is_client() {
3957 let params = self.crypto.transport_parameters()?.ok_or_else(|| {
3959 TransportError::new(
3960 TransportErrorCode::crypto(0x6d),
3961 "transport parameters missing".to_owned(),
3962 )
3963 })?;
3964
3965 if self.has_0rtt() {
3966 if !self.crypto.early_data_accepted().unwrap() {
3967 debug_assert!(self.side.is_client());
3968 debug!("0-RTT rejected");
3969 self.accepted_0rtt = false;
3970 self.streams.zero_rtt_rejected();
3971
3972 self.spaces[SpaceId::Data].pending = Retransmits::default();
3974
3975 let sent_packets = mem::take(
3977 &mut self.spaces[SpaceId::Data].for_path(path_id).sent_packets,
3978 );
3979 for (_, packet) in sent_packets.into_iter() {
3980 self.paths
3981 .get_mut(&path_id)
3982 .unwrap()
3983 .remove_in_flight(&packet);
3984 }
3985 } else {
3986 self.accepted_0rtt = true;
3987 params.validate_resumption_from(&self.peer_params)?;
3988 }
3989 }
3990 if let Some(token) = params.stateless_reset_token {
3991 let remote = self.path_data(path_id).remote;
3992 self.endpoint_events
3993 .push_back(EndpointEventInner::ResetToken(path_id, remote, token));
3994 }
3995 self.handle_peer_params(params, loc_cid, rem_cid, now)?;
3996 self.issue_first_cids(now);
3997 } else {
3998 self.spaces[SpaceId::Data].pending.handshake_done = true;
4000 self.discard_space(now, SpaceId::Handshake);
4001 self.events.push_back(Event::HandshakeConfirmed);
4002 trace!("handshake confirmed");
4003 }
4004
4005 self.events.push_back(Event::Connected);
4006 self.state.move_to_established();
4007 trace!("established");
4008
4009 self.issue_first_path_cids(now);
4012 Ok(())
4013 }
4014 Header::Initial(InitialHeader {
4015 src_cid: rem_cid,
4016 dst_cid: loc_cid,
4017 ..
4018 }) => {
4019 debug_assert_eq!(path_id, PathId::ZERO);
4020 if !state.rem_cid_set {
4021 trace!("switching remote CID to {}", rem_cid);
4022 let mut state = state.clone();
4023 self.rem_cids
4024 .get_mut(&path_id)
4025 .expect("PathId::ZERO not yet abandoned")
4026 .update_initial_cid(rem_cid);
4027 self.rem_handshake_cid = rem_cid;
4028 self.orig_rem_cid = rem_cid;
4029 state.rem_cid_set = true;
4030 self.state.move_to_handshake(state);
4031 } else if rem_cid != self.rem_handshake_cid {
4032 debug!(
4033 "discarding packet with mismatched remote CID: {} != {}",
4034 self.rem_handshake_cid, rem_cid
4035 );
4036 return Ok(());
4037 }
4038
4039 let starting_space = self.highest_space;
4040 self.process_early_payload(now, path_id, packet, qlog)?;
4041
4042 if self.side.is_server()
4043 && starting_space == SpaceId::Initial
4044 && self.highest_space != SpaceId::Initial
4045 {
4046 let params = self.crypto.transport_parameters()?.ok_or_else(|| {
4047 TransportError::new(
4048 TransportErrorCode::crypto(0x6d),
4049 "transport parameters missing".to_owned(),
4050 )
4051 })?;
4052 self.handle_peer_params(params, loc_cid, rem_cid, now)?;
4053 self.issue_first_cids(now);
4054 self.init_0rtt(now);
4055 }
4056 Ok(())
4057 }
4058 Header::Long {
4059 ty: LongType::ZeroRtt,
4060 ..
4061 } => {
4062 self.process_payload(now, remote, path_id, number.unwrap(), packet, qlog)?;
4063 Ok(())
4064 }
4065 Header::VersionNegotiate { .. } => {
4066 if self.total_authed_packets > 1 {
4067 return Ok(());
4068 }
4069 let supported = packet
4070 .payload
4071 .chunks(4)
4072 .any(|x| match <[u8; 4]>::try_from(x) {
4073 Ok(version) => self.version == u32::from_be_bytes(version),
4074 Err(_) => false,
4075 });
4076 if supported {
4077 return Ok(());
4078 }
4079 debug!("remote doesn't support our version");
4080 Err(ConnectionError::VersionMismatch)
4081 }
4082 Header::Short { .. } => unreachable!(
4083 "short packets received during handshake are discarded in handle_packet"
4084 ),
4085 }
4086 }
4087
4088 fn process_early_payload(
4090 &mut self,
4091 now: Instant,
4092 path_id: PathId,
4093 packet: Packet,
4094 #[allow(unused)] qlog: &mut QlogRecvPacket,
4095 ) -> Result<(), TransportError> {
4096 debug_assert_ne!(packet.header.space(), SpaceId::Data);
4097 debug_assert_eq!(path_id, PathId::ZERO);
4098 let payload_len = packet.payload.len();
4099 let mut ack_eliciting = false;
4100 for result in frame::Iter::new(packet.payload.freeze())? {
4101 let frame = result?;
4102 qlog.frame(&frame);
4103 let span = match frame {
4104 Frame::Padding => continue,
4105 _ => Some(trace_span!("frame", ty = %frame.ty(), path = tracing::field::Empty)),
4106 };
4107
4108 self.stats.frame_rx.record(&frame);
4109
4110 let _guard = span.as_ref().map(|x| x.enter());
4111 ack_eliciting |= frame.is_ack_eliciting();
4112
4113 if frame.is_1rtt() && packet.header.space() != SpaceId::Data {
4115 return Err(TransportError::PROTOCOL_VIOLATION(
4116 "illegal frame type in handshake",
4117 ));
4118 }
4119
4120 match frame {
4121 Frame::Padding | Frame::Ping => {}
4122 Frame::Crypto(frame) => {
4123 self.read_crypto(packet.header.space(), &frame, payload_len)?;
4124 }
4125 Frame::Ack(ack) => {
4126 self.on_ack_received(now, packet.header.space(), ack)?;
4127 }
4128 Frame::PathAck(ack) => {
4129 span.as_ref()
4130 .map(|span| span.record("path", tracing::field::debug(&ack.path_id)));
4131 self.on_path_ack_received(now, packet.header.space(), ack)?;
4132 }
4133 Frame::Close(reason) => {
4134 self.state.move_to_draining(Some(reason.into()));
4135 return Ok(());
4136 }
4137 _ => {
4138 let mut err =
4139 TransportError::PROTOCOL_VIOLATION("illegal frame type in handshake");
4140 err.frame = Some(frame.ty());
4141 return Err(err);
4142 }
4143 }
4144 }
4145
4146 if ack_eliciting {
4147 self.spaces[packet.header.space()]
4149 .for_path(path_id)
4150 .pending_acks
4151 .set_immediate_ack_required();
4152 }
4153
4154 self.write_crypto();
4155 Ok(())
4156 }
4157
4158 fn process_payload(
4160 &mut self,
4161 now: Instant,
4162 remote: SocketAddr,
4163 path_id: PathId,
4164 number: u64,
4165 packet: Packet,
4166 #[allow(unused)] qlog: &mut QlogRecvPacket,
4167 ) -> Result<(), TransportError> {
4168 let payload = packet.payload.freeze();
4169 let mut is_probing_packet = true;
4170 let mut close = None;
4171 let payload_len = payload.len();
4172 let mut ack_eliciting = false;
4173 let mut migration_observed_addr = None;
4176 for result in frame::Iter::new(payload)? {
4177 let frame = result?;
4178 qlog.frame(&frame);
4179 let span = match frame {
4180 Frame::Padding => continue,
4181 _ => trace_span!("frame", ty = %frame.ty(), path = tracing::field::Empty),
4182 };
4183
4184 self.stats.frame_rx.record(&frame);
4185 match &frame {
4188 Frame::Crypto(f) => {
4189 trace!(offset = f.offset, len = f.data.len(), "got crypto frame");
4190 }
4191 Frame::Stream(f) => {
4192 trace!(id = %f.id, offset = f.offset, len = f.data.len(), fin = f.fin, "got stream frame");
4193 }
4194 Frame::Datagram(f) => {
4195 trace!(len = f.data.len(), "got datagram frame");
4196 }
4197 f => {
4198 trace!("got frame {:?}", f);
4199 }
4200 }
4201
4202 let _guard = span.enter();
4203 if packet.header.is_0rtt() {
4204 match frame {
4205 Frame::Crypto(_) | Frame::Close(Close::Application(_)) => {
4206 return Err(TransportError::PROTOCOL_VIOLATION(
4207 "illegal frame type in 0-RTT",
4208 ));
4209 }
4210 _ => {
4211 if frame.is_1rtt() {
4212 return Err(TransportError::PROTOCOL_VIOLATION(
4213 "illegal frame type in 0-RTT",
4214 ));
4215 }
4216 }
4217 }
4218 }
4219 ack_eliciting |= frame.is_ack_eliciting();
4220
4221 match frame {
4223 Frame::Padding
4224 | Frame::PathChallenge(_)
4225 | Frame::PathResponse(_)
4226 | Frame::NewConnectionId(_)
4227 | Frame::ObservedAddr(_) => {}
4228 _ => {
4229 is_probing_packet = false;
4230 }
4231 }
4232
4233 match frame {
4234 Frame::Crypto(frame) => {
4235 self.read_crypto(SpaceId::Data, &frame, payload_len)?;
4236 }
4237 Frame::Stream(frame) => {
4238 if self.streams.received(frame, payload_len)?.should_transmit() {
4239 self.spaces[SpaceId::Data].pending.max_data = true;
4240 }
4241 }
4242 Frame::Ack(ack) => {
4243 self.on_ack_received(now, SpaceId::Data, ack)?;
4244 }
4245 Frame::PathAck(ack) => {
4246 span.record("path", tracing::field::debug(&ack.path_id));
4247 self.on_path_ack_received(now, SpaceId::Data, ack)?;
4248 }
4249 Frame::Padding | Frame::Ping => {}
4250 Frame::Close(reason) => {
4251 close = Some(reason);
4252 }
4253 Frame::PathChallenge(challenge) => {
4254 let path = &mut self
4255 .path_mut(path_id)
4256 .expect("payload is processed only after the path becomes known");
4257 path.path_responses.push(number, challenge.0, remote);
4258 if remote == path.remote {
4259 match self.peer_supports_ack_frequency() {
4269 true => self.immediate_ack(path_id),
4270 false => {
4271 self.ping_path(path_id).ok();
4272 }
4273 }
4274 }
4275 }
4276 Frame::PathResponse(response) => {
4277 let path = self
4278 .paths
4279 .get_mut(&path_id)
4280 .expect("payload is processed only after the path becomes known");
4281
4282 use paths::OnPathResponseReceived::*;
4283 match path.data.on_path_response_received(now, response.0, remote) {
4284 OnPath { was_open } => {
4285 use PathTimer::*;
4287 let qlog = self.qlog.with_time(now);
4288
4289 self.timers
4290 .stop(Timer::PerPath(path_id, PathValidation), qlog.clone());
4291 self.timers
4292 .stop(Timer::PerPath(path_id, PathChallengeLost), qlog.clone());
4293 self.timers.stop(Timer::PerPath(path_id, PathOpen), qlog);
4294 if !was_open {
4295 self.events
4296 .push_back(Event::Path(PathEvent::Opened { id: path_id }));
4297 if let Some(observed) = path.data.last_observed_addr_report.as_ref()
4298 {
4299 self.events.push_back(Event::Path(PathEvent::ObservedAddr {
4300 id: path_id,
4301 addr: observed.socket_addr(),
4302 }));
4303 }
4304 }
4305 if let Some((_, ref mut prev)) = path.prev {
4306 prev.challenges_sent.clear();
4307 prev.send_new_challenge = false;
4308 }
4309 }
4310 OffPath => {
4311 debug!("Response to off-path PathChallenge!");
4312 }
4313 Invalid { expected } => {
4314 debug!(%response, from=%remote, %expected, "ignoring invalid PATH_RESPONSE")
4315 }
4316 Unknown => debug!(%response, "ignoring invalid PATH_RESPONSE"),
4317 }
4318 }
4319 Frame::MaxData(bytes) => {
4320 self.streams.received_max_data(bytes);
4321 }
4322 Frame::MaxStreamData { id, offset } => {
4323 self.streams.received_max_stream_data(id, offset)?;
4324 }
4325 Frame::MaxStreams { dir, count } => {
4326 self.streams.received_max_streams(dir, count)?;
4327 }
4328 Frame::ResetStream(frame) => {
4329 if self.streams.received_reset(frame)?.should_transmit() {
4330 self.spaces[SpaceId::Data].pending.max_data = true;
4331 }
4332 }
4333 Frame::DataBlocked { offset } => {
4334 debug!(offset, "peer claims to be blocked at connection level");
4335 }
4336 Frame::StreamDataBlocked { id, offset } => {
4337 if id.initiator() == self.side.side() && id.dir() == Dir::Uni {
4338 debug!("got STREAM_DATA_BLOCKED on send-only {}", id);
4339 return Err(TransportError::STREAM_STATE_ERROR(
4340 "STREAM_DATA_BLOCKED on send-only stream",
4341 ));
4342 }
4343 debug!(
4344 stream = %id,
4345 offset, "peer claims to be blocked at stream level"
4346 );
4347 }
4348 Frame::StreamsBlocked { dir, limit } => {
4349 if limit > MAX_STREAM_COUNT {
4350 return Err(TransportError::FRAME_ENCODING_ERROR(
4351 "unrepresentable stream limit",
4352 ));
4353 }
4354 debug!(
4355 "peer claims to be blocked opening more than {} {} streams",
4356 limit, dir
4357 );
4358 }
4359 Frame::StopSending(frame::StopSending { id, error_code }) => {
4360 if id.initiator() != self.side.side() {
4361 if id.dir() == Dir::Uni {
4362 debug!("got STOP_SENDING on recv-only {}", id);
4363 return Err(TransportError::STREAM_STATE_ERROR(
4364 "STOP_SENDING on recv-only stream",
4365 ));
4366 }
4367 } else if self.streams.is_local_unopened(id) {
4368 return Err(TransportError::STREAM_STATE_ERROR(
4369 "STOP_SENDING on unopened stream",
4370 ));
4371 }
4372 self.streams.received_stop_sending(id, error_code);
4373 }
4374 Frame::RetireConnectionId(frame::RetireConnectionId { path_id, sequence }) => {
4375 if let Some(ref path_id) = path_id {
4376 span.record("path", tracing::field::debug(&path_id));
4377 }
4378 let path_id = path_id.unwrap_or_default();
4379 match self.local_cid_state.get_mut(&path_id) {
4380 None => error!(?path_id, "RETIRE_CONNECTION_ID for unknown path"),
4381 Some(cid_state) => {
4382 let allow_more_cids = cid_state
4383 .on_cid_retirement(sequence, self.peer_params.issue_cids_limit())?;
4384
4385 let has_path = !self.abandoned_paths.contains(&path_id);
4389 let allow_more_cids = allow_more_cids && has_path;
4390
4391 self.endpoint_events
4392 .push_back(EndpointEventInner::RetireConnectionId(
4393 now,
4394 path_id,
4395 sequence,
4396 allow_more_cids,
4397 ));
4398 }
4399 }
4400 }
4401 Frame::NewConnectionId(frame) => {
4402 let path_id = if let Some(path_id) = frame.path_id {
4403 if !self.is_multipath_negotiated() {
4404 return Err(TransportError::PROTOCOL_VIOLATION(
4405 "received PATH_NEW_CONNECTION_ID frame when multipath was not negotiated",
4406 ));
4407 }
4408 if path_id > self.local_max_path_id {
4409 return Err(TransportError::PROTOCOL_VIOLATION(
4410 "PATH_NEW_CONNECTION_ID contains path_id exceeding current max",
4411 ));
4412 }
4413 path_id
4414 } else {
4415 PathId::ZERO
4416 };
4417
4418 if self.abandoned_paths.contains(&path_id) {
4419 trace!("ignoring issued CID for abandoned path");
4420 continue;
4421 }
4422 if let Some(ref path_id) = frame.path_id {
4423 span.record("path", tracing::field::debug(&path_id));
4424 }
4425 let rem_cids = self
4426 .rem_cids
4427 .entry(path_id)
4428 .or_insert_with(|| CidQueue::new(frame.id));
4429 if rem_cids.active().is_empty() {
4430 return Err(TransportError::PROTOCOL_VIOLATION(
4432 "NEW_CONNECTION_ID when CIDs aren't in use",
4433 ));
4434 }
4435 if frame.retire_prior_to > frame.sequence {
4436 return Err(TransportError::PROTOCOL_VIOLATION(
4437 "NEW_CONNECTION_ID retiring unissued CIDs",
4438 ));
4439 }
4440
4441 use crate::cid_queue::InsertError;
4442 match rem_cids.insert(frame) {
4443 Ok(None) => {}
4444 Ok(Some((retired, reset_token))) => {
4445 let pending_retired =
4446 &mut self.spaces[SpaceId::Data].pending.retire_cids;
4447 const MAX_PENDING_RETIRED_CIDS: u64 = CidQueue::LEN as u64 * 10;
4450 if (pending_retired.len() as u64)
4453 .saturating_add(retired.end.saturating_sub(retired.start))
4454 > MAX_PENDING_RETIRED_CIDS
4455 {
4456 return Err(TransportError::CONNECTION_ID_LIMIT_ERROR(
4457 "queued too many retired CIDs",
4458 ));
4459 }
4460 pending_retired.extend(retired.map(|seq| (path_id, seq)));
4461 self.set_reset_token(path_id, remote, reset_token);
4462 }
4463 Err(InsertError::ExceedsLimit) => {
4464 return Err(TransportError::CONNECTION_ID_LIMIT_ERROR(""));
4465 }
4466 Err(InsertError::Retired) => {
4467 trace!("discarding already-retired");
4468 self.spaces[SpaceId::Data]
4472 .pending
4473 .retire_cids
4474 .push((path_id, frame.sequence));
4475 continue;
4476 }
4477 };
4478
4479 if self.side.is_server()
4480 && path_id == PathId::ZERO
4481 && self
4482 .rem_cids
4483 .get(&PathId::ZERO)
4484 .map(|cids| cids.active_seq() == 0)
4485 .unwrap_or_default()
4486 {
4487 self.update_rem_cid(PathId::ZERO);
4490 }
4491 }
4492 Frame::NewToken(NewToken { token }) => {
4493 let ConnectionSide::Client {
4494 token_store,
4495 server_name,
4496 ..
4497 } = &self.side
4498 else {
4499 return Err(TransportError::PROTOCOL_VIOLATION("client sent NEW_TOKEN"));
4500 };
4501 if token.is_empty() {
4502 return Err(TransportError::FRAME_ENCODING_ERROR("empty token"));
4503 }
4504 trace!("got new token");
4505 token_store.insert(server_name, token);
4506 }
4507 Frame::Datagram(datagram) => {
4508 if self
4509 .datagrams
4510 .received(datagram, &self.config.datagram_receive_buffer_size)?
4511 {
4512 self.events.push_back(Event::DatagramReceived);
4513 }
4514 }
4515 Frame::AckFrequency(ack_frequency) => {
4516 if !self.ack_frequency.ack_frequency_received(&ack_frequency)? {
4519 continue;
4522 }
4523
4524 for (path_id, space) in self.spaces[SpaceId::Data].number_spaces.iter_mut() {
4526 space.pending_acks.set_ack_frequency_params(&ack_frequency);
4527
4528 if let Some(timeout) = space
4531 .pending_acks
4532 .max_ack_delay_timeout(self.ack_frequency.max_ack_delay)
4533 {
4534 self.timers.set(
4535 Timer::PerPath(*path_id, PathTimer::MaxAckDelay),
4536 timeout,
4537 self.qlog.with_time(now),
4538 );
4539 }
4540 }
4541 }
4542 Frame::ImmediateAck => {
4543 for pns in self.spaces[SpaceId::Data].iter_paths_mut() {
4545 pns.pending_acks.set_immediate_ack_required();
4546 }
4547 }
4548 Frame::HandshakeDone => {
4549 if self.side.is_server() {
4550 return Err(TransportError::PROTOCOL_VIOLATION(
4551 "client sent HANDSHAKE_DONE",
4552 ));
4553 }
4554 if self.spaces[SpaceId::Handshake].crypto.is_some() {
4555 self.discard_space(now, SpaceId::Handshake);
4556 }
4557 self.events.push_back(Event::HandshakeConfirmed);
4558 trace!("handshake confirmed");
4559 }
4560 Frame::ObservedAddr(observed) => {
4561 trace!(seq_no = %observed.seq_no, ip = %observed.ip, port = observed.port);
4563 if !self
4564 .peer_params
4565 .address_discovery_role
4566 .should_report(&self.config.address_discovery_role)
4567 {
4568 return Err(TransportError::PROTOCOL_VIOLATION(
4569 "received OBSERVED_ADDRESS frame when not negotiated",
4570 ));
4571 }
4572 if packet.header.space() != SpaceId::Data {
4574 return Err(TransportError::PROTOCOL_VIOLATION(
4575 "OBSERVED_ADDRESS frame outside data space",
4576 ));
4577 }
4578
4579 let path = self.path_data_mut(path_id);
4580 if remote == path.remote {
4581 if let Some(updated) = path.update_observed_addr_report(observed) {
4582 if path.open {
4583 self.events.push_back(Event::Path(PathEvent::ObservedAddr {
4584 id: path_id,
4585 addr: updated,
4586 }));
4587 }
4588 }
4590 } else {
4591 migration_observed_addr = Some(observed)
4593 }
4594 }
4595 Frame::PathAbandon(frame::PathAbandon {
4596 path_id,
4597 error_code,
4598 }) => {
4599 span.record("path", tracing::field::debug(&path_id));
4600 let already_abandoned = match self.close_path(now, path_id, error_code.into()) {
4602 Ok(()) => {
4603 trace!("peer abandoned path");
4604 false
4605 }
4606 Err(ClosePathError::LastOpenPath) => {
4607 trace!("peer abandoned last path, closing connection");
4608 return Err(TransportError::NO_ERROR("last path abandoned by peer"));
4610 }
4611 Err(ClosePathError::ClosedPath) => {
4612 trace!("peer abandoned already closed path");
4613 true
4614 }
4615 };
4616 if self.path(path_id).is_some() && !already_abandoned {
4621 let delay = self.pto(SpaceId::Data, path_id) * 3;
4626 self.timers.set(
4627 Timer::PerPath(path_id, PathTimer::DiscardPath),
4628 now + delay,
4629 self.qlog.with_time(now),
4630 );
4631 }
4632 }
4633 Frame::PathStatusAvailable(info) => {
4634 span.record("path", tracing::field::debug(&info.path_id));
4635 if self.is_multipath_negotiated() {
4636 self.on_path_status(
4637 info.path_id,
4638 PathStatus::Available,
4639 info.status_seq_no,
4640 );
4641 } else {
4642 return Err(TransportError::PROTOCOL_VIOLATION(
4643 "received PATH_STATUS_AVAILABLE frame when multipath was not negotiated",
4644 ));
4645 }
4646 }
4647 Frame::PathStatusBackup(info) => {
4648 span.record("path", tracing::field::debug(&info.path_id));
4649 if self.is_multipath_negotiated() {
4650 self.on_path_status(info.path_id, PathStatus::Backup, info.status_seq_no);
4651 } else {
4652 return Err(TransportError::PROTOCOL_VIOLATION(
4653 "received PATH_STATUS_BACKUP frame when multipath was not negotiated",
4654 ));
4655 }
4656 }
4657 Frame::MaxPathId(frame::MaxPathId(path_id)) => {
4658 span.record("path", tracing::field::debug(&path_id));
4659 if !self.is_multipath_negotiated() {
4660 return Err(TransportError::PROTOCOL_VIOLATION(
4661 "received MAX_PATH_ID frame when multipath was not negotiated",
4662 ));
4663 }
4664 if path_id > self.remote_max_path_id {
4666 self.remote_max_path_id = path_id;
4667 self.issue_first_path_cids(now);
4668 }
4669 }
4670 Frame::PathsBlocked(frame::PathsBlocked(max_path_id)) => {
4671 if self.is_multipath_negotiated() {
4675 if self.local_max_path_id > max_path_id {
4676 return Err(TransportError::PROTOCOL_VIOLATION(
4677 "PATHS_BLOCKED maximum path identifier was larger than local maximum",
4678 ));
4679 }
4680 debug!("received PATHS_BLOCKED({:?})", max_path_id);
4681 } else {
4683 return Err(TransportError::PROTOCOL_VIOLATION(
4684 "received PATHS_BLOCKED frame when not multipath was not negotiated",
4685 ));
4686 }
4687 }
4688 Frame::PathCidsBlocked(frame::PathCidsBlocked { path_id, next_seq }) => {
4689 if self.is_multipath_negotiated() {
4697 if path_id > self.local_max_path_id {
4698 return Err(TransportError::PROTOCOL_VIOLATION(
4699 "PATH_CIDS_BLOCKED path identifier was larger than local maximum",
4700 ));
4701 }
4702 if next_seq.0
4703 > self
4704 .local_cid_state
4705 .get(&path_id)
4706 .map(|cid_state| cid_state.active_seq().1 + 1)
4707 .unwrap_or_default()
4708 {
4709 return Err(TransportError::PROTOCOL_VIOLATION(
4710 "PATH_CIDS_BLOCKED next sequence number larger than in local state",
4711 ));
4712 }
4713 debug!(%path_id, %next_seq, "received PATH_CIDS_BLOCKED");
4714 } else {
4715 return Err(TransportError::PROTOCOL_VIOLATION(
4716 "received PATH_CIDS_BLOCKED frame when not multipath was not negotiated",
4717 ));
4718 }
4719 }
4720 Frame::AddAddress(addr) => {
4721 let client_state = match self.iroh_hp.client_side_mut() {
4722 Ok(state) => state,
4723 Err(err) => {
4724 return Err(TransportError::PROTOCOL_VIOLATION(format!(
4725 "Nat traversal(ADD_ADDRESS): {err}"
4726 )));
4727 }
4728 };
4729
4730 if !client_state.check_remote_address(&addr) {
4731 warn!(?addr, "server sent illegal ADD_ADDRESS frame");
4733 }
4734
4735 match client_state.add_remote_address(addr) {
4736 Ok(maybe_added) => {
4737 if let Some(added) = maybe_added {
4738 self.events.push_back(Event::NatTraversal(
4739 iroh_hp::Event::AddressAdded(added),
4740 ));
4741 }
4742 }
4743 Err(e) => {
4744 warn!(%e, "failed to add remote address")
4745 }
4746 }
4747 }
4748 Frame::RemoveAddress(addr) => {
4749 let client_state = match self.iroh_hp.client_side_mut() {
4750 Ok(state) => state,
4751 Err(err) => {
4752 return Err(TransportError::PROTOCOL_VIOLATION(format!(
4753 "Nat traversal(REMOVE_ADDRESS): {err}"
4754 )));
4755 }
4756 };
4757 if let Some(removed_addr) = client_state.remove_remote_address(addr) {
4758 self.events
4759 .push_back(Event::NatTraversal(iroh_hp::Event::AddressRemoved(
4760 removed_addr,
4761 )));
4762 }
4763 }
4764 Frame::ReachOut(reach_out) => {
4765 let server_state = match self.iroh_hp.server_side_mut() {
4766 Ok(state) => state,
4767 Err(err) => {
4768 return Err(TransportError::PROTOCOL_VIOLATION(format!(
4769 "Nat traversal(REACH_OUT): {err}"
4770 )));
4771 }
4772 };
4773
4774 if let Err(err) = server_state.handle_reach_out(reach_out) {
4775 return Err(TransportError::PROTOCOL_VIOLATION(format!(
4776 "Nat traversal(REACH_OUT): {err}"
4777 )));
4778 }
4779 }
4780 }
4781 }
4782
4783 let space = self.spaces[SpaceId::Data].for_path(path_id);
4784 if space
4785 .pending_acks
4786 .packet_received(now, number, ack_eliciting, &space.dedup)
4787 {
4788 if self.abandoned_paths.contains(&path_id) {
4789 space.pending_acks.set_immediate_ack_required();
4792 } else {
4793 self.timers.set(
4794 Timer::PerPath(path_id, PathTimer::MaxAckDelay),
4795 now + self.ack_frequency.max_ack_delay,
4796 self.qlog.with_time(now),
4797 );
4798 }
4799 }
4800
4801 let pending = &mut self.spaces[SpaceId::Data].pending;
4806 self.streams.queue_max_stream_id(pending);
4807
4808 if let Some(reason) = close {
4809 self.state.move_to_draining(Some(reason.into()));
4810 self.close = true;
4811 }
4812
4813 if Some(number) == self.spaces[SpaceId::Data].for_path(path_id).rx_packet
4814 && !is_probing_packet
4815 && remote != self.path_data(path_id).remote
4816 {
4817 let ConnectionSide::Server { ref server_config } = self.side else {
4818 panic!("packets from unknown remote should be dropped by clients");
4819 };
4820 debug_assert!(
4821 server_config.migration,
4822 "migration-initiating packets should have been dropped immediately"
4823 );
4824 self.migrate(path_id, now, remote, migration_observed_addr);
4825 self.update_rem_cid(path_id);
4827 self.spin = false;
4828 }
4829
4830 Ok(())
4831 }
4832
4833 fn migrate(
4834 &mut self,
4835 path_id: PathId,
4836 now: Instant,
4837 remote: SocketAddr,
4838 observed_addr: Option<ObservedAddr>,
4839 ) {
4840 trace!(%remote, %path_id, "migration initiated");
4841 self.path_counter = self.path_counter.wrapping_add(1);
4842 let prev_pto = self.pto(SpaceId::Data, path_id);
4849 let known_path = self.paths.get_mut(&path_id).expect("known path");
4850 let path = &mut known_path.data;
4851 let mut new_path = if remote.is_ipv4() && remote.ip() == path.remote.ip() {
4852 PathData::from_previous(remote, path, self.path_counter, now)
4853 } else {
4854 let peer_max_udp_payload_size =
4855 u16::try_from(self.peer_params.max_udp_payload_size.into_inner())
4856 .unwrap_or(u16::MAX);
4857 PathData::new(
4858 remote,
4859 self.allow_mtud,
4860 Some(peer_max_udp_payload_size),
4861 self.path_counter,
4862 now,
4863 &self.config,
4864 )
4865 };
4866 new_path.last_observed_addr_report = path.last_observed_addr_report.clone();
4867 if let Some(report) = observed_addr {
4868 if let Some(updated) = new_path.update_observed_addr_report(report) {
4869 tracing::info!("adding observed addr event from migration");
4870 self.events.push_back(Event::Path(PathEvent::ObservedAddr {
4871 id: path_id,
4872 addr: updated,
4873 }));
4874 }
4875 }
4876 new_path.send_new_challenge = true;
4877
4878 let mut prev = mem::replace(path, new_path);
4879 if !prev.is_validating_path() {
4881 prev.send_new_challenge = true;
4882 known_path.prev = Some((self.rem_cids.get(&path_id).unwrap().active(), prev));
4886 }
4887
4888 self.qlog.emit_tuple_assigned(path_id, remote, now);
4890
4891 self.timers.set(
4892 Timer::PerPath(path_id, PathTimer::PathValidation),
4893 now + 3 * cmp::max(self.pto(SpaceId::Data, path_id), prev_pto),
4894 self.qlog.with_time(now),
4895 );
4896 }
4897
4898 pub fn local_address_changed(&mut self) {
4900 self.update_rem_cid(PathId::ZERO);
4902 self.ping();
4903 }
4904
4905 fn update_rem_cid(&mut self, path_id: PathId) {
4907 let Some((reset_token, retired)) =
4908 self.rem_cids.get_mut(&path_id).and_then(|cids| cids.next())
4909 else {
4910 return;
4911 };
4912
4913 self.spaces[SpaceId::Data]
4915 .pending
4916 .retire_cids
4917 .extend(retired.map(|seq| (path_id, seq)));
4918 let remote = self.path_data(path_id).remote;
4919 self.set_reset_token(path_id, remote, reset_token);
4920 }
4921
4922 fn set_reset_token(&mut self, path_id: PathId, remote: SocketAddr, reset_token: ResetToken) {
4931 self.endpoint_events
4932 .push_back(EndpointEventInner::ResetToken(path_id, remote, reset_token));
4933
4934 if path_id == PathId::ZERO {
4940 self.peer_params.stateless_reset_token = Some(reset_token);
4941 }
4942 }
4943
4944 fn issue_first_cids(&mut self, now: Instant) {
4946 if self
4947 .local_cid_state
4948 .get(&PathId::ZERO)
4949 .expect("PathId::ZERO exists when the connection is created")
4950 .cid_len()
4951 == 0
4952 {
4953 return;
4954 }
4955
4956 let mut n = self.peer_params.issue_cids_limit() - 1;
4958 if let ConnectionSide::Server { server_config } = &self.side {
4959 if server_config.has_preferred_address() {
4960 n -= 1;
4962 }
4963 }
4964 self.endpoint_events
4965 .push_back(EndpointEventInner::NeedIdentifiers(PathId::ZERO, now, n));
4966 }
4967
4968 fn issue_first_path_cids(&mut self, now: Instant) {
4972 if let Some(max_path_id) = self.max_path_id() {
4973 let mut path_id = self.max_path_id_with_cids.next();
4974 while path_id <= max_path_id {
4975 self.endpoint_events
4976 .push_back(EndpointEventInner::NeedIdentifiers(
4977 path_id,
4978 now,
4979 self.peer_params.issue_cids_limit(),
4980 ));
4981 path_id = path_id.next();
4982 }
4983 self.max_path_id_with_cids = max_path_id;
4984 }
4985 }
4986
4987 fn populate_packet(
4995 &mut self,
4996 now: Instant,
4997 space_id: SpaceId,
4998 path_id: PathId,
4999 path_exclusive_only: bool,
5000 buf: &mut impl BufMut,
5001 pn: u64,
5002 #[allow(unused)] qlog: &mut QlogSentPacket,
5003 ) -> SentFrames {
5004 let mut sent = SentFrames::default();
5005 let is_multipath_negotiated = self.is_multipath_negotiated();
5006 let space = &mut self.spaces[space_id];
5007 let path = &mut self.paths.get_mut(&path_id).expect("known path").data;
5008 let is_0rtt = space_id == SpaceId::Data && space.crypto.is_none();
5009 space
5010 .for_path(path_id)
5011 .pending_acks
5012 .maybe_ack_non_eliciting();
5013
5014 if !is_0rtt && mem::replace(&mut space.pending.handshake_done, false) {
5016 trace!("HANDSHAKE_DONE");
5017 buf.write(frame::FrameType::HANDSHAKE_DONE);
5018 qlog.frame(&Frame::HandshakeDone);
5019 sent.retransmits.get_or_create().handshake_done = true;
5020 self.stats.frame_tx.handshake_done =
5022 self.stats.frame_tx.handshake_done.saturating_add(1);
5023 }
5024
5025 if let Some((round, addresses)) = space.pending.reach_out.as_mut() {
5028 while let Some(local_addr) = addresses.pop() {
5029 let reach_out = frame::ReachOut::new(*round, local_addr);
5030 if buf.remaining_mut() > reach_out.size() {
5031 trace!(%round, ?local_addr, "REACH_OUT");
5032 reach_out.write(buf);
5033 let sent_reachouts = sent
5034 .retransmits
5035 .get_or_create()
5036 .reach_out
5037 .get_or_insert_with(|| (*round, Default::default()));
5038 sent_reachouts.1.push(local_addr);
5039 self.stats.frame_tx.reach_out = self.stats.frame_tx.reach_out.saturating_add(1);
5040 qlog.frame(&Frame::ReachOut(reach_out));
5041 } else {
5042 addresses.push(local_addr);
5043 break;
5044 }
5045 }
5046 if addresses.is_empty() {
5047 space.pending.reach_out = None;
5048 }
5049 }
5050
5051 if !path_exclusive_only
5053 && space_id == SpaceId::Data
5054 && self
5055 .config
5056 .address_discovery_role
5057 .should_report(&self.peer_params.address_discovery_role)
5058 && (!path.observed_addr_sent || space.pending.observed_addr)
5059 {
5060 let frame = frame::ObservedAddr::new(path.remote, self.next_observed_addr_seq_no);
5061 if buf.remaining_mut() > frame.size() {
5062 trace!(seq = %frame.seq_no, ip = %frame.ip, port = frame.port, "OBSERVED_ADDRESS");
5063 frame.write(buf);
5064
5065 self.next_observed_addr_seq_no = self.next_observed_addr_seq_no.saturating_add(1u8);
5066 path.observed_addr_sent = true;
5067
5068 self.stats.frame_tx.observed_addr += 1;
5069 sent.retransmits.get_or_create().observed_addr = true;
5070 space.pending.observed_addr = false;
5071 qlog.frame(&Frame::ObservedAddr(frame));
5072 }
5073 }
5074
5075 if mem::replace(&mut space.for_path(path_id).ping_pending, false) {
5077 trace!("PING");
5078 buf.write(frame::FrameType::PING);
5079 sent.non_retransmits = true;
5080 self.stats.frame_tx.ping += 1;
5081 qlog.frame(&Frame::Ping);
5082 }
5083
5084 if mem::replace(&mut space.for_path(path_id).immediate_ack_pending, false) {
5086 debug_assert_eq!(
5087 space_id,
5088 SpaceId::Data,
5089 "immediate acks must be sent in the data space"
5090 );
5091 trace!("IMMEDIATE_ACK");
5092 buf.write(frame::FrameType::IMMEDIATE_ACK);
5093 sent.non_retransmits = true;
5094 self.stats.frame_tx.immediate_ack += 1;
5095 qlog.frame(&Frame::ImmediateAck);
5096 }
5097
5098 if !path_exclusive_only {
5102 for path_id in space
5103 .number_spaces
5104 .iter_mut()
5105 .filter(|(_, pns)| pns.pending_acks.can_send())
5106 .map(|(&path_id, _)| path_id)
5107 .collect::<Vec<_>>()
5108 {
5109 Self::populate_acks(
5110 now,
5111 self.receiving_ecn,
5112 &mut sent,
5113 path_id,
5114 space_id,
5115 space,
5116 is_multipath_negotiated,
5117 buf,
5118 &mut self.stats,
5119 qlog,
5120 );
5121 }
5122 }
5123
5124 if !path_exclusive_only && mem::replace(&mut space.pending.ack_frequency, false) {
5126 let sequence_number = self.ack_frequency.next_sequence_number();
5127
5128 let config = self.config.ack_frequency_config.as_ref().unwrap();
5130
5131 let max_ack_delay = self.ack_frequency.candidate_max_ack_delay(
5133 path.rtt.get(),
5134 config,
5135 &self.peer_params,
5136 );
5137
5138 trace!(?max_ack_delay, "ACK_FREQUENCY");
5139
5140 let frame = frame::AckFrequency {
5141 sequence: sequence_number,
5142 ack_eliciting_threshold: config.ack_eliciting_threshold,
5143 request_max_ack_delay: max_ack_delay.as_micros().try_into().unwrap_or(VarInt::MAX),
5144 reordering_threshold: config.reordering_threshold,
5145 };
5146 frame.encode(buf);
5147 qlog.frame(&Frame::AckFrequency(frame));
5148
5149 sent.retransmits.get_or_create().ack_frequency = true;
5150
5151 self.ack_frequency
5152 .ack_frequency_sent(path_id, pn, max_ack_delay);
5153 self.stats.frame_tx.ack_frequency += 1;
5154 }
5155
5156 if buf.remaining_mut() > frame::PathChallenge::SIZE_BOUND
5158 && space_id == SpaceId::Data
5159 && path.send_new_challenge
5160 {
5161 path.send_new_challenge = false;
5162
5163 let token = self.rng.random();
5165 let info = paths::SentChallengeInfo {
5166 sent_instant: now,
5167 remote: path.remote,
5168 };
5169 path.challenges_sent.insert(token, info);
5170 sent.non_retransmits = true;
5171 sent.requires_padding = true;
5172 let challenge = frame::PathChallenge(token);
5173 trace!(%challenge, "sending new challenge");
5174 buf.write(challenge);
5175 qlog.frame(&Frame::PathChallenge(challenge));
5176 self.stats.frame_tx.path_challenge += 1;
5177 let pto = self.ack_frequency.max_ack_delay_for_pto() + path.rtt.pto_base();
5178 self.timers.set(
5179 Timer::PerPath(path_id, PathTimer::PathChallengeLost),
5180 now + pto,
5181 self.qlog.with_time(now),
5182 );
5183
5184 if is_multipath_negotiated && !path.validated && path.send_new_challenge {
5185 space.pending.path_status.insert(path_id);
5187 }
5188
5189 if space_id == SpaceId::Data
5192 && self
5193 .config
5194 .address_discovery_role
5195 .should_report(&self.peer_params.address_discovery_role)
5196 {
5197 let frame = frame::ObservedAddr::new(path.remote, self.next_observed_addr_seq_no);
5198 if buf.remaining_mut() > frame.size() {
5199 frame.write(buf);
5200 qlog.frame(&Frame::ObservedAddr(frame));
5201
5202 self.next_observed_addr_seq_no =
5203 self.next_observed_addr_seq_no.saturating_add(1u8);
5204 path.observed_addr_sent = true;
5205
5206 self.stats.frame_tx.observed_addr += 1;
5207 sent.retransmits.get_or_create().observed_addr = true;
5208 space.pending.observed_addr = false;
5209 }
5210 }
5211 }
5212
5213 if buf.remaining_mut() > frame::PathResponse::SIZE_BOUND && space_id == SpaceId::Data {
5215 if let Some(token) = path.path_responses.pop_on_path(path.remote) {
5216 sent.non_retransmits = true;
5217 sent.requires_padding = true;
5218 let response = frame::PathResponse(token);
5219 trace!(%response, "sending response");
5220 buf.write(response);
5221 qlog.frame(&Frame::PathResponse(response));
5222 self.stats.frame_tx.path_response += 1;
5223
5224 if space_id == SpaceId::Data
5228 && self
5229 .config
5230 .address_discovery_role
5231 .should_report(&self.peer_params.address_discovery_role)
5232 {
5233 let frame =
5234 frame::ObservedAddr::new(path.remote, self.next_observed_addr_seq_no);
5235 if buf.remaining_mut() > frame.size() {
5236 frame.write(buf);
5237 qlog.frame(&Frame::ObservedAddr(frame));
5238
5239 self.next_observed_addr_seq_no =
5240 self.next_observed_addr_seq_no.saturating_add(1u8);
5241 path.observed_addr_sent = true;
5242
5243 self.stats.frame_tx.observed_addr += 1;
5244 sent.retransmits.get_or_create().observed_addr = true;
5245 space.pending.observed_addr = false;
5246 }
5247 }
5248 }
5249 }
5250
5251 while !path_exclusive_only && buf.remaining_mut() > frame::Crypto::SIZE_BOUND && !is_0rtt {
5253 let mut frame = match space.pending.crypto.pop_front() {
5254 Some(x) => x,
5255 None => break,
5256 };
5257
5258 let max_crypto_data_size = buf.remaining_mut()
5263 - 1 - VarInt::size(unsafe { VarInt::from_u64_unchecked(frame.offset) })
5265 - 2; let len = frame
5268 .data
5269 .len()
5270 .min(2usize.pow(14) - 1)
5271 .min(max_crypto_data_size);
5272
5273 let data = frame.data.split_to(len);
5274 let truncated = frame::Crypto {
5275 offset: frame.offset,
5276 data,
5277 };
5278 trace!(
5279 "CRYPTO: off {} len {}",
5280 truncated.offset,
5281 truncated.data.len()
5282 );
5283 truncated.encode(buf);
5284 self.stats.frame_tx.crypto += 1;
5285
5286 #[cfg(feature = "qlog")]
5288 qlog.frame(&Frame::Crypto(truncated.clone()));
5289 sent.retransmits.get_or_create().crypto.push_back(truncated);
5290 if !frame.data.is_empty() {
5291 frame.offset += len as u64;
5292 space.pending.crypto.push_front(frame);
5293 }
5294 }
5295
5296 while !path_exclusive_only
5299 && space_id == SpaceId::Data
5300 && frame::PathAbandon::SIZE_BOUND <= buf.remaining_mut()
5301 {
5302 let Some((path_id, error_code)) = space.pending.path_abandon.pop_first() else {
5303 break;
5304 };
5305 let frame = frame::PathAbandon {
5306 path_id,
5307 error_code,
5308 };
5309 frame.encode(buf);
5310 qlog.frame(&Frame::PathAbandon(frame));
5311 self.stats.frame_tx.path_abandon += 1;
5312 trace!(%path_id, "PATH_ABANDON");
5313 sent.retransmits
5314 .get_or_create()
5315 .path_abandon
5316 .entry(path_id)
5317 .or_insert(error_code);
5318 }
5319
5320 while !path_exclusive_only
5322 && space_id == SpaceId::Data
5323 && frame::PathStatusAvailable::SIZE_BOUND <= buf.remaining_mut()
5324 {
5325 let Some(path_id) = space.pending.path_status.pop_first() else {
5326 break;
5327 };
5328 let Some(path) = self.paths.get(&path_id).map(|path_state| &path_state.data) else {
5329 trace!(%path_id, "discarding queued path status for unknown path");
5330 continue;
5331 };
5332
5333 let seq = path.status.seq();
5334 sent.retransmits.get_or_create().path_status.insert(path_id);
5335 match path.local_status() {
5336 PathStatus::Available => {
5337 let frame = frame::PathStatusAvailable {
5338 path_id,
5339 status_seq_no: seq,
5340 };
5341 frame.encode(buf);
5342 qlog.frame(&Frame::PathStatusAvailable(frame));
5343 self.stats.frame_tx.path_status_available += 1;
5344 trace!(%path_id, %seq, "PATH_STATUS_AVAILABLE")
5345 }
5346 PathStatus::Backup => {
5347 let frame = frame::PathStatusBackup {
5348 path_id,
5349 status_seq_no: seq,
5350 };
5351 frame.encode(buf);
5352 qlog.frame(&Frame::PathStatusBackup(frame));
5353 self.stats.frame_tx.path_status_backup += 1;
5354 trace!(%path_id, %seq, "PATH_STATUS_BACKUP")
5355 }
5356 }
5357 }
5358
5359 if space_id == SpaceId::Data
5361 && space.pending.max_path_id
5362 && frame::MaxPathId::SIZE_BOUND <= buf.remaining_mut()
5363 {
5364 let frame = frame::MaxPathId(self.local_max_path_id);
5365 frame.encode(buf);
5366 qlog.frame(&Frame::MaxPathId(frame));
5367 space.pending.max_path_id = false;
5368 sent.retransmits.get_or_create().max_path_id = true;
5369 trace!(val = %self.local_max_path_id, "MAX_PATH_ID");
5370 self.stats.frame_tx.max_path_id += 1;
5371 }
5372
5373 if space_id == SpaceId::Data
5375 && space.pending.paths_blocked
5376 && frame::PathsBlocked::SIZE_BOUND <= buf.remaining_mut()
5377 {
5378 let frame = frame::PathsBlocked(self.remote_max_path_id);
5379 frame.encode(buf);
5380 qlog.frame(&Frame::PathsBlocked(frame));
5381 space.pending.paths_blocked = false;
5382 sent.retransmits.get_or_create().paths_blocked = true;
5383 trace!(max_path_id = ?self.remote_max_path_id, "PATHS_BLOCKED");
5384 self.stats.frame_tx.paths_blocked += 1;
5385 }
5386
5387 while space_id == SpaceId::Data && frame::PathCidsBlocked::SIZE_BOUND <= buf.remaining_mut()
5389 {
5390 let Some(path_id) = space.pending.path_cids_blocked.pop() else {
5391 break;
5392 };
5393 let next_seq = match self.rem_cids.get(&path_id) {
5394 Some(cid_queue) => cid_queue.active_seq() + 1,
5395 None => 0,
5396 };
5397 let frame = frame::PathCidsBlocked {
5398 path_id,
5399 next_seq: VarInt(next_seq),
5400 };
5401 frame.encode(buf);
5402 qlog.frame(&Frame::PathCidsBlocked(frame));
5403 sent.retransmits
5404 .get_or_create()
5405 .path_cids_blocked
5406 .push(path_id);
5407 trace!(%path_id, next_seq, "PATH_CIDS_BLOCKED");
5408 self.stats.frame_tx.path_cids_blocked += 1;
5409 }
5410
5411 if space_id == SpaceId::Data {
5413 self.streams.write_control_frames(
5414 buf,
5415 &mut space.pending,
5416 &mut sent.retransmits,
5417 &mut self.stats.frame_tx,
5418 qlog,
5419 );
5420 }
5421
5422 let cid_len = self
5424 .local_cid_state
5425 .values()
5426 .map(|cid_state| cid_state.cid_len())
5427 .max()
5428 .expect("some local CID state must exist");
5429 let new_cid_size_bound =
5430 frame::NewConnectionId::size_bound(is_multipath_negotiated, cid_len);
5431 while !path_exclusive_only && buf.remaining_mut() > new_cid_size_bound {
5432 let issued = match space.pending.new_cids.pop() {
5433 Some(x) => x,
5434 None => break,
5435 };
5436 let retire_prior_to = self
5437 .local_cid_state
5438 .get(&issued.path_id)
5439 .map(|cid_state| cid_state.retire_prior_to())
5440 .unwrap_or_else(|| panic!("missing local CID state for path={}", issued.path_id));
5441
5442 let cid_path_id = match is_multipath_negotiated {
5443 true => {
5444 trace!(
5445 path_id = ?issued.path_id,
5446 sequence = issued.sequence,
5447 id = %issued.id,
5448 "PATH_NEW_CONNECTION_ID",
5449 );
5450 self.stats.frame_tx.path_new_connection_id += 1;
5451 Some(issued.path_id)
5452 }
5453 false => {
5454 trace!(
5455 sequence = issued.sequence,
5456 id = %issued.id,
5457 "NEW_CONNECTION_ID"
5458 );
5459 debug_assert_eq!(issued.path_id, PathId::ZERO);
5460 self.stats.frame_tx.new_connection_id += 1;
5461 None
5462 }
5463 };
5464 let frame = frame::NewConnectionId {
5465 path_id: cid_path_id,
5466 sequence: issued.sequence,
5467 retire_prior_to,
5468 id: issued.id,
5469 reset_token: issued.reset_token,
5470 };
5471 frame.encode(buf);
5472 sent.retransmits.get_or_create().new_cids.push(issued);
5473 qlog.frame(&Frame::NewConnectionId(frame));
5474 }
5475
5476 let retire_cid_bound = frame::RetireConnectionId::size_bound(is_multipath_negotiated);
5478 while !path_exclusive_only && buf.remaining_mut() > retire_cid_bound {
5479 let (path_id, sequence) = match space.pending.retire_cids.pop() {
5480 Some((PathId::ZERO, seq)) if !is_multipath_negotiated => {
5481 trace!(sequence = seq, "RETIRE_CONNECTION_ID");
5482 self.stats.frame_tx.retire_connection_id += 1;
5483 (None, seq)
5484 }
5485 Some((path_id, seq)) => {
5486 trace!(%path_id, sequence = seq, "PATH_RETIRE_CONNECTION_ID");
5487 self.stats.frame_tx.path_retire_connection_id += 1;
5488 (Some(path_id), seq)
5489 }
5490 None => break,
5491 };
5492 let frame = frame::RetireConnectionId { path_id, sequence };
5493 frame.encode(buf);
5494 qlog.frame(&Frame::RetireConnectionId(frame));
5495 sent.retransmits
5496 .get_or_create()
5497 .retire_cids
5498 .push((path_id.unwrap_or_default(), sequence));
5499 }
5500
5501 let mut sent_datagrams = false;
5503 while !path_exclusive_only
5504 && buf.remaining_mut() > Datagram::SIZE_BOUND
5505 && space_id == SpaceId::Data
5506 {
5507 let prev_remaining = buf.remaining_mut();
5508 match self.datagrams.write(buf) {
5509 true => {
5510 sent_datagrams = true;
5511 sent.non_retransmits = true;
5512 self.stats.frame_tx.datagram += 1;
5513 qlog.frame_datagram((prev_remaining - buf.remaining_mut()) as u64);
5514 }
5515 false => break,
5516 }
5517 }
5518 if self.datagrams.send_blocked && sent_datagrams {
5519 self.events.push_back(Event::DatagramsUnblocked);
5520 self.datagrams.send_blocked = false;
5521 }
5522
5523 let path = &mut self.paths.get_mut(&path_id).expect("known path").data;
5524
5525 while let Some(remote_addr) = space.pending.new_tokens.pop() {
5527 if path_exclusive_only {
5528 break;
5529 }
5530 debug_assert_eq!(space_id, SpaceId::Data);
5531 let ConnectionSide::Server { server_config } = &self.side else {
5532 panic!("NEW_TOKEN frames should not be enqueued by clients");
5533 };
5534
5535 if remote_addr != path.remote {
5536 continue;
5541 }
5542
5543 let token = Token::new(
5544 TokenPayload::Validation {
5545 ip: remote_addr.ip(),
5546 issued: server_config.time_source.now(),
5547 },
5548 &mut self.rng,
5549 );
5550 let new_token = NewToken {
5551 token: token.encode(&*server_config.token_key).into(),
5552 };
5553
5554 if buf.remaining_mut() < new_token.size() {
5555 space.pending.new_tokens.push(remote_addr);
5556 break;
5557 }
5558
5559 trace!("NEW_TOKEN");
5560 new_token.encode(buf);
5561 qlog.frame(&Frame::NewToken(new_token));
5562 sent.retransmits
5563 .get_or_create()
5564 .new_tokens
5565 .push(remote_addr);
5566 self.stats.frame_tx.new_token += 1;
5567 }
5568
5569 if !path_exclusive_only && space_id == SpaceId::Data {
5571 sent.stream_frames =
5572 self.streams
5573 .write_stream_frames(buf, self.config.send_fairness, qlog);
5574 self.stats.frame_tx.stream += sent.stream_frames.len() as u64;
5575 }
5576
5577 while space_id == SpaceId::Data && frame::AddAddress::SIZE_BOUND <= buf.remaining_mut() {
5580 if let Some(added_address) = space.pending.add_address.pop_last() {
5581 trace!(
5582 seq = %added_address.seq_no,
5583 ip = ?added_address.ip,
5584 port = added_address.port,
5585 "ADD_ADDRESS",
5586 );
5587 added_address.write(buf);
5588 sent.retransmits
5589 .get_or_create()
5590 .add_address
5591 .insert(added_address);
5592 self.stats.frame_tx.add_address = self.stats.frame_tx.add_address.saturating_add(1);
5593 qlog.frame(&Frame::AddAddress(added_address));
5594 } else {
5595 break;
5596 }
5597 }
5598
5599 while space_id == SpaceId::Data && frame::RemoveAddress::SIZE_BOUND <= buf.remaining_mut() {
5601 if let Some(removed_address) = space.pending.remove_address.pop_last() {
5602 trace!(seq = %removed_address.seq_no, "REMOVE_ADDRESS");
5603 removed_address.write(buf);
5604 sent.retransmits
5605 .get_or_create()
5606 .remove_address
5607 .insert(removed_address);
5608 self.stats.frame_tx.remove_address =
5609 self.stats.frame_tx.remove_address.saturating_add(1);
5610 qlog.frame(&Frame::RemoveAddress(removed_address));
5611 } else {
5612 break;
5613 }
5614 }
5615
5616 sent
5617 }
5618
5619 fn populate_acks(
5621 now: Instant,
5622 receiving_ecn: bool,
5623 sent: &mut SentFrames,
5624 path_id: PathId,
5625 space_id: SpaceId,
5626 space: &mut PacketSpace,
5627 is_multipath_negotiated: bool,
5628 buf: &mut impl BufMut,
5629 stats: &mut ConnectionStats,
5630 #[allow(unused)] qlog: &mut QlogSentPacket,
5631 ) {
5632 debug_assert!(space.crypto.is_some(), "tried to send ACK in 0-RTT");
5634
5635 debug_assert!(
5636 is_multipath_negotiated || path_id == PathId::ZERO,
5637 "Only PathId::ZERO allowed without multipath (have {path_id:?})"
5638 );
5639 if is_multipath_negotiated {
5640 debug_assert!(
5641 space_id == SpaceId::Data || path_id == PathId::ZERO,
5642 "path acks must be sent in 1RTT space (have {space_id:?})"
5643 );
5644 }
5645
5646 let pns = space.for_path(path_id);
5647 let ranges = pns.pending_acks.ranges();
5648 debug_assert!(!ranges.is_empty(), "can not send empty ACK range");
5649 let ecn = if receiving_ecn {
5650 Some(&pns.ecn_counters)
5651 } else {
5652 None
5653 };
5654 if let Some(max) = ranges.max() {
5655 sent.largest_acked.insert(path_id, max);
5656 }
5657
5658 let delay_micros = pns.pending_acks.ack_delay(now).as_micros() as u64;
5659 let ack_delay_exp = TransportParameters::default().ack_delay_exponent;
5661 let delay = delay_micros >> ack_delay_exp.into_inner();
5662
5663 if is_multipath_negotiated && space_id == SpaceId::Data {
5664 if !ranges.is_empty() {
5665 trace!("PATH_ACK {path_id:?} {ranges:?}, Delay = {delay_micros}us");
5666 frame::PathAck::encode(path_id, delay as _, ranges, ecn, buf);
5667 qlog.frame_path_ack(path_id, delay as _, ranges, ecn);
5668 stats.frame_tx.path_acks += 1;
5669 }
5670 } else {
5671 trace!("ACK {ranges:?}, Delay = {delay_micros}us");
5672 frame::Ack::encode(delay as _, ranges, ecn, buf);
5673 stats.frame_tx.acks += 1;
5674 qlog.frame_ack(delay, ranges, ecn);
5675 }
5676 }
5677
5678 fn close_common(&mut self) {
5679 trace!("connection closed");
5680 self.timers.reset();
5681 }
5682
5683 fn set_close_timer(&mut self, now: Instant) {
5684 self.timers.set(
5687 Timer::Conn(ConnTimer::Close),
5688 now + 3 * self.pto_max_path(self.highest_space),
5689 self.qlog.with_time(now),
5690 );
5691 }
5692
5693 fn handle_peer_params(
5698 &mut self,
5699 params: TransportParameters,
5700 loc_cid: ConnectionId,
5701 rem_cid: ConnectionId,
5702 now: Instant,
5703 ) -> Result<(), TransportError> {
5704 if Some(self.orig_rem_cid) != params.initial_src_cid
5705 || (self.side.is_client()
5706 && (Some(self.initial_dst_cid) != params.original_dst_cid
5707 || self.retry_src_cid != params.retry_src_cid))
5708 {
5709 return Err(TransportError::TRANSPORT_PARAMETER_ERROR(
5710 "CID authentication failure",
5711 ));
5712 }
5713 if params.initial_max_path_id.is_some() && (loc_cid.is_empty() || rem_cid.is_empty()) {
5714 return Err(TransportError::PROTOCOL_VIOLATION(
5715 "multipath must not use zero-length CIDs",
5716 ));
5717 }
5718
5719 self.set_peer_params(params);
5720 self.qlog.emit_peer_transport_params_received(self, now);
5721
5722 Ok(())
5723 }
5724
5725 fn set_peer_params(&mut self, params: TransportParameters) {
5726 self.streams.set_params(¶ms);
5727 self.idle_timeout =
5728 negotiate_max_idle_timeout(self.config.max_idle_timeout, Some(params.max_idle_timeout));
5729 trace!("negotiated max idle timeout {:?}", self.idle_timeout);
5730
5731 if let Some(ref info) = params.preferred_address {
5732 self.rem_cids.get_mut(&PathId::ZERO).expect("not yet abandoned").insert(frame::NewConnectionId {
5734 path_id: None,
5735 sequence: 1,
5736 id: info.connection_id,
5737 reset_token: info.stateless_reset_token,
5738 retire_prior_to: 0,
5739 })
5740 .expect(
5741 "preferred address CID is the first received, and hence is guaranteed to be legal",
5742 );
5743 let remote = self.path_data(PathId::ZERO).remote;
5744 self.set_reset_token(PathId::ZERO, remote, info.stateless_reset_token);
5745 }
5746 self.ack_frequency.peer_max_ack_delay = get_max_ack_delay(¶ms);
5747
5748 let mut multipath_enabled = None;
5749 if let (Some(local_max_path_id), Some(remote_max_path_id)) = (
5750 self.config.get_initial_max_path_id(),
5751 params.initial_max_path_id,
5752 ) {
5753 self.local_max_path_id = local_max_path_id;
5755 self.remote_max_path_id = remote_max_path_id;
5756 let initial_max_path_id = local_max_path_id.min(remote_max_path_id);
5757 debug!(%initial_max_path_id, "multipath negotiated");
5758 multipath_enabled = Some(initial_max_path_id);
5759 }
5760
5761 if let Some((max_locally_allowed_remote_addresses, max_remotely_allowed_remote_addresses)) =
5762 self.config
5763 .max_remote_nat_traversal_addresses
5764 .zip(params.max_remote_nat_traversal_addresses)
5765 {
5766 if let Some(max_initial_paths) =
5767 multipath_enabled.map(|path_id| path_id.saturating_add(1u8))
5768 {
5769 let max_local_addresses = max_remotely_allowed_remote_addresses.get();
5770 let max_remote_addresses = max_locally_allowed_remote_addresses.get();
5771 self.iroh_hp =
5772 iroh_hp::State::new(max_remote_addresses, max_local_addresses, self.side());
5773 debug!(
5774 %max_remote_addresses, %max_local_addresses,
5775 "iroh hole punching negotiated"
5776 );
5777
5778 match self.side() {
5779 Side::Client => {
5780 if max_initial_paths.as_u32() < max_remote_addresses as u32 + 1 {
5781 warn!(%max_initial_paths, %max_remote_addresses, "local client configuration might cause nat traversal issues")
5784 } else if max_local_addresses as u64
5785 > params.active_connection_id_limit.into_inner()
5786 {
5787 warn!(%max_local_addresses, remote_cid_limit=%params.active_connection_id_limit.into_inner(), "remote server configuration might cause nat traversal issues")
5791 }
5792 }
5793 Side::Server => {
5794 if (max_initial_paths.as_u32() as u64) < crate::LOC_CID_COUNT {
5795 warn!(%max_initial_paths, local_cid_limit=%crate::LOC_CID_COUNT, "local server configuration might cause nat traversal issues")
5796 }
5797 }
5798 }
5799 } else {
5800 debug!("iroh nat traversal enabled for both endpoints, but multipath is missing")
5801 }
5802 }
5803
5804 self.peer_params = params;
5805 let peer_max_udp_payload_size =
5806 u16::try_from(self.peer_params.max_udp_payload_size.into_inner()).unwrap_or(u16::MAX);
5807 self.path_data_mut(PathId::ZERO)
5808 .mtud
5809 .on_peer_max_udp_payload_size_received(peer_max_udp_payload_size);
5810 }
5811
5812 fn decrypt_packet(
5814 &mut self,
5815 now: Instant,
5816 path_id: PathId,
5817 packet: &mut Packet,
5818 ) -> Result<Option<u64>, Option<TransportError>> {
5819 let result = packet_crypto::decrypt_packet_body(
5820 packet,
5821 path_id,
5822 &self.spaces,
5823 self.zero_rtt_crypto.as_ref(),
5824 self.key_phase,
5825 self.prev_crypto.as_ref(),
5826 self.next_crypto.as_ref(),
5827 )?;
5828
5829 let result = match result {
5830 Some(r) => r,
5831 None => return Ok(None),
5832 };
5833
5834 if result.outgoing_key_update_acked {
5835 if let Some(prev) = self.prev_crypto.as_mut() {
5836 prev.end_packet = Some((result.number, now));
5837 self.set_key_discard_timer(now, packet.header.space());
5838 }
5839 }
5840
5841 if result.incoming_key_update {
5842 trace!("key update authenticated");
5843 self.update_keys(Some((result.number, now)), true);
5844 self.set_key_discard_timer(now, packet.header.space());
5845 }
5846
5847 Ok(Some(result.number))
5848 }
5849
5850 fn update_keys(&mut self, end_packet: Option<(u64, Instant)>, remote: bool) {
5851 trace!("executing key update");
5852 let new = self
5856 .crypto
5857 .next_1rtt_keys()
5858 .expect("only called for `Data` packets");
5859 self.key_phase_size = new
5860 .local
5861 .confidentiality_limit()
5862 .saturating_sub(KEY_UPDATE_MARGIN);
5863 let old = mem::replace(
5864 &mut self.spaces[SpaceId::Data]
5865 .crypto
5866 .as_mut()
5867 .unwrap() .packet,
5869 mem::replace(self.next_crypto.as_mut().unwrap(), new),
5870 );
5871 self.spaces[SpaceId::Data]
5872 .iter_paths_mut()
5873 .for_each(|s| s.sent_with_keys = 0);
5874 self.prev_crypto = Some(PrevCrypto {
5875 crypto: old,
5876 end_packet,
5877 update_unacked: remote,
5878 });
5879 self.key_phase = !self.key_phase;
5880 }
5881
5882 fn peer_supports_ack_frequency(&self) -> bool {
5883 self.peer_params.min_ack_delay.is_some()
5884 }
5885
5886 pub(crate) fn immediate_ack(&mut self, path_id: PathId) {
5891 debug_assert_eq!(
5892 self.highest_space,
5893 SpaceId::Data,
5894 "immediate ack must be written in the data space"
5895 );
5896 self.spaces[self.highest_space]
5897 .for_path(path_id)
5898 .immediate_ack_pending = true;
5899 }
5900
5901 #[cfg(test)]
5903 pub(crate) fn decode_packet(&self, event: &ConnectionEvent) -> Option<Vec<u8>> {
5904 let (path_id, first_decode, remaining) = match &event.0 {
5905 ConnectionEventInner::Datagram(DatagramConnectionEvent {
5906 path_id,
5907 first_decode,
5908 remaining,
5909 ..
5910 }) => (path_id, first_decode, remaining),
5911 _ => return None,
5912 };
5913
5914 if remaining.is_some() {
5915 panic!("Packets should never be coalesced in tests");
5916 }
5917
5918 let decrypted_header = packet_crypto::unprotect_header(
5919 first_decode.clone(),
5920 &self.spaces,
5921 self.zero_rtt_crypto.as_ref(),
5922 self.peer_params.stateless_reset_token,
5923 )?;
5924
5925 let mut packet = decrypted_header.packet?;
5926 packet_crypto::decrypt_packet_body(
5927 &mut packet,
5928 *path_id,
5929 &self.spaces,
5930 self.zero_rtt_crypto.as_ref(),
5931 self.key_phase,
5932 self.prev_crypto.as_ref(),
5933 self.next_crypto.as_ref(),
5934 )
5935 .ok()?;
5936
5937 Some(packet.payload.to_vec())
5938 }
5939
5940 #[cfg(test)]
5943 pub(crate) fn bytes_in_flight(&self) -> u64 {
5944 self.path_data(PathId::ZERO).in_flight.bytes
5946 }
5947
5948 #[cfg(test)]
5950 pub(crate) fn congestion_window(&self) -> u64 {
5951 let path = self.path_data(PathId::ZERO);
5952 path.congestion
5953 .window()
5954 .saturating_sub(path.in_flight.bytes)
5955 }
5956
5957 #[cfg(test)]
5959 pub(crate) fn is_idle(&self) -> bool {
5960 let current_timers = self.timers.values();
5961 current_timers
5962 .into_iter()
5963 .filter(|(timer, _)| {
5964 !matches!(
5965 timer,
5966 Timer::Conn(ConnTimer::KeepAlive)
5967 | Timer::PerPath(_, PathTimer::PathKeepAlive)
5968 | Timer::Conn(ConnTimer::PushNewCid)
5969 | Timer::Conn(ConnTimer::KeyDiscard)
5970 )
5971 })
5972 .min_by_key(|(_, time)| *time)
5973 .is_none_or(|(timer, _)| timer == Timer::Conn(ConnTimer::Idle))
5974 }
5975
5976 #[cfg(test)]
5978 pub(crate) fn using_ecn(&self) -> bool {
5979 self.path_data(PathId::ZERO).sending_ecn
5980 }
5981
5982 #[cfg(test)]
5984 pub(crate) fn total_recvd(&self) -> u64 {
5985 self.path_data(PathId::ZERO).total_recvd
5986 }
5987
5988 #[cfg(test)]
5989 pub(crate) fn active_local_cid_seq(&self) -> (u64, u64) {
5990 self.local_cid_state
5991 .get(&PathId::ZERO)
5992 .unwrap()
5993 .active_seq()
5994 }
5995
5996 #[cfg(test)]
5997 #[track_caller]
5998 pub(crate) fn active_local_path_cid_seq(&self, path_id: u32) -> (u64, u64) {
5999 self.local_cid_state
6000 .get(&PathId(path_id))
6001 .unwrap()
6002 .active_seq()
6003 }
6004
6005 #[cfg(test)]
6008 pub(crate) fn rotate_local_cid(&mut self, v: u64, now: Instant) {
6009 let n = self
6010 .local_cid_state
6011 .get_mut(&PathId::ZERO)
6012 .unwrap()
6013 .assign_retire_seq(v);
6014 self.endpoint_events
6015 .push_back(EndpointEventInner::NeedIdentifiers(PathId::ZERO, now, n));
6016 }
6017
6018 #[cfg(test)]
6020 pub(crate) fn active_rem_cid_seq(&self) -> u64 {
6021 self.rem_cids.get(&PathId::ZERO).unwrap().active_seq()
6022 }
6023
6024 #[cfg(test)]
6026 pub(crate) fn path_mtu(&self, path_id: PathId) -> u16 {
6027 self.path_data(path_id).current_mtu()
6028 }
6029
6030 #[cfg(test)]
6032 pub(crate) fn trigger_path_validation(&mut self) {
6033 for path in self.paths.values_mut() {
6034 path.data.send_new_challenge = true;
6035 }
6036 }
6037
6038 fn can_send_1rtt(&self, path_id: PathId, max_size: usize) -> SendableFrames {
6049 let path_exclusive = self.paths.get(&path_id).is_some_and(|path| {
6050 path.data.send_new_challenge
6051 || path
6052 .prev
6053 .as_ref()
6054 .is_some_and(|(_, path)| path.send_new_challenge)
6055 || !path.data.path_responses.is_empty()
6056 });
6057 let other = self.streams.can_send_stream_data()
6058 || self
6059 .datagrams
6060 .outgoing
6061 .front()
6062 .is_some_and(|x| x.size(true) <= max_size);
6063 SendableFrames {
6064 acks: false,
6065 other,
6066 close: false,
6067 path_exclusive,
6068 }
6069 }
6070
6071 fn kill(&mut self, reason: ConnectionError) {
6073 self.close_common();
6074 self.state.move_to_drained(Some(reason));
6075 self.endpoint_events.push_back(EndpointEventInner::Drained);
6076 }
6077
6078 pub fn current_mtu(&self) -> u16 {
6085 self.paths
6086 .iter()
6087 .filter(|&(path_id, _path_state)| !self.abandoned_paths.contains(path_id))
6088 .map(|(_path_id, path_state)| path_state.data.current_mtu())
6089 .min()
6090 .expect("There is always at least one available path")
6091 }
6092
6093 fn predict_1rtt_overhead(&mut self, pn: u64, path: PathId) -> usize {
6100 let pn_len = PacketNumber::new(
6101 pn,
6102 self.spaces[SpaceId::Data]
6103 .for_path(path)
6104 .largest_acked_packet
6105 .unwrap_or(0),
6106 )
6107 .len();
6108
6109 1 + self
6111 .rem_cids
6112 .get(&path)
6113 .map(|cids| cids.active().len())
6114 .unwrap_or(20) + pn_len
6116 + self.tag_len_1rtt()
6117 }
6118
6119 fn predict_1rtt_overhead_no_pn(&self) -> usize {
6120 let pn_len = 4;
6121
6122 let cid_len = self
6123 .rem_cids
6124 .values()
6125 .map(|cids| cids.active().len())
6126 .max()
6127 .unwrap_or(20); 1 + cid_len + pn_len + self.tag_len_1rtt()
6131 }
6132
6133 fn tag_len_1rtt(&self) -> usize {
6134 let key = match self.spaces[SpaceId::Data].crypto.as_ref() {
6135 Some(crypto) => Some(&*crypto.packet.local),
6136 None => self.zero_rtt_crypto.as_ref().map(|x| &*x.packet),
6137 };
6138 key.map_or(16, |x| x.tag_len())
6142 }
6143
6144 fn on_path_validated(&mut self, path_id: PathId) {
6146 self.path_data_mut(path_id).validated = true;
6147 let ConnectionSide::Server { server_config } = &self.side else {
6148 return;
6149 };
6150 let remote_addr = self.path_data(path_id).remote;
6151 let new_tokens = &mut self.spaces[SpaceId::Data as usize].pending.new_tokens;
6152 new_tokens.clear();
6153 for _ in 0..server_config.validation_token.sent {
6154 new_tokens.push(remote_addr);
6155 }
6156 }
6157
6158 fn on_path_status(&mut self, path_id: PathId, status: PathStatus, status_seq_no: VarInt) {
6160 if let Some(path) = self.paths.get_mut(&path_id) {
6161 path.data.status.remote_update(status, status_seq_no);
6162 } else {
6163 debug!("PATH_STATUS_AVAILABLE received unknown path {:?}", path_id);
6164 }
6165 self.events.push_back(
6166 PathEvent::RemoteStatus {
6167 id: path_id,
6168 status,
6169 }
6170 .into(),
6171 );
6172 }
6173
6174 fn max_path_id(&self) -> Option<PathId> {
6183 if self.is_multipath_negotiated() {
6184 Some(self.remote_max_path_id.min(self.local_max_path_id))
6185 } else {
6186 None
6187 }
6188 }
6189
6190 pub fn add_nat_traversal_address(&mut self, address: SocketAddr) -> Result<(), iroh_hp::Error> {
6192 if let Some(added) = self.iroh_hp.add_local_address(address)? {
6193 self.spaces[SpaceId::Data].pending.add_address.insert(added);
6194 };
6195 Ok(())
6196 }
6197
6198 pub fn remove_nat_traversal_address(
6202 &mut self,
6203 address: SocketAddr,
6204 ) -> Result<(), iroh_hp::Error> {
6205 if let Some(removed) = self.iroh_hp.remove_local_address(address)? {
6206 self.spaces[SpaceId::Data]
6207 .pending
6208 .remove_address
6209 .insert(removed);
6210 }
6211 Ok(())
6212 }
6213
6214 pub fn get_local_nat_traversal_addresses(&self) -> Result<Vec<SocketAddr>, iroh_hp::Error> {
6216 self.iroh_hp.get_local_nat_traversal_addresses()
6217 }
6218
6219 pub fn get_remote_nat_traversal_addresses(&self) -> Result<Vec<SocketAddr>, iroh_hp::Error> {
6221 Ok(self
6222 .iroh_hp
6223 .client_side()?
6224 .get_remote_nat_traversal_addresses())
6225 }
6226
6227 pub fn initiate_nat_traversal_round(
6235 &mut self,
6236 now: Instant,
6237 ) -> Result<Vec<SocketAddr>, iroh_hp::Error> {
6238 let client_state = self.iroh_hp.client_side_mut()?;
6239 let iroh_hp::NatTraversalRound {
6240 new_round,
6241 reach_out_at,
6242 addresses_to_probe,
6243 prev_round_path_ids,
6244 } = client_state.initiate_nat_traversal_round()?;
6245
6246 self.spaces[SpaceId::Data].pending.reach_out = Some((new_round, reach_out_at));
6247
6248 for path_id in prev_round_path_ids {
6249 let validated = self
6252 .path(path_id)
6253 .map(|path| path.validated)
6254 .unwrap_or(false);
6255
6256 if !validated {
6257 let _ = self.close_path(
6258 now,
6259 path_id,
6260 TransportErrorCode::APPLICATION_ABANDON_PATH.into(),
6261 );
6262 }
6263 }
6264
6265 let mut err = None;
6266
6267 let mut path_ids = Vec::with_capacity(addresses_to_probe.len());
6268 let mut probed_addresses = Vec::with_capacity(addresses_to_probe.len());
6269 let ipv6 = self.paths.values().any(|p| p.data.remote.is_ipv6());
6270
6271 for (ip, port) in addresses_to_probe {
6272 let remote = match ip {
6274 IpAddr::V4(addr) if ipv6 => SocketAddr::new(addr.to_ipv6_mapped().into(), port),
6275 IpAddr::V4(addr) => SocketAddr::new(addr.into(), port),
6276 IpAddr::V6(_) if ipv6 => SocketAddr::new(ip, port),
6277 IpAddr::V6(_) => {
6278 trace!("not using IPv6 nat candidate for IPv4 socket");
6279 continue;
6280 }
6281 };
6282 match self.open_path_ensure(remote, PathStatus::Backup, now) {
6283 Ok((path_id, path_was_known)) if !path_was_known => {
6284 path_ids.push(path_id);
6285 probed_addresses.push(remote);
6286 }
6287 Ok((path_id, _)) => {
6288 trace!(%path_id, %remote,"nat traversal: path existed for remote")
6289 }
6290 Err(e) => {
6291 debug!(%remote, %e,"nat traversal: failed to probe remote");
6292 err.get_or_insert(e);
6293 }
6294 }
6295 }
6296
6297 if let Some(err) = err {
6298 if probed_addresses.is_empty() {
6300 return Err(iroh_hp::Error::Multipath(err));
6301 }
6302 }
6303
6304 self.iroh_hp
6305 .client_side_mut()
6306 .expect("connection side validated")
6307 .set_round_path_ids(path_ids);
6308
6309 Ok(probed_addresses)
6310 }
6311}
6312
6313impl fmt::Debug for Connection {
6314 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
6315 f.debug_struct("Connection")
6316 .field("handshake_cid", &self.handshake_cid)
6317 .finish()
6318 }
6319}
6320
6321#[derive(Debug, Copy, Clone, PartialEq, Eq)]
6322enum PathBlocked {
6323 No,
6324 AntiAmplification,
6325 Congestion,
6326 Pacing,
6327}
6328
6329enum ConnectionSide {
6331 Client {
6332 token: Bytes,
6334 token_store: Arc<dyn TokenStore>,
6335 server_name: String,
6336 },
6337 Server {
6338 server_config: Arc<ServerConfig>,
6339 },
6340}
6341
6342impl ConnectionSide {
6343 fn remote_may_migrate(&self, state: &State) -> bool {
6344 match self {
6345 Self::Server { server_config } => server_config.migration,
6346 Self::Client { .. } => {
6347 if let Some(hs) = state.as_handshake() {
6348 hs.allow_server_migration
6349 } else {
6350 false
6351 }
6352 }
6353 }
6354 }
6355
6356 fn is_client(&self) -> bool {
6357 self.side().is_client()
6358 }
6359
6360 fn is_server(&self) -> bool {
6361 self.side().is_server()
6362 }
6363
6364 fn side(&self) -> Side {
6365 match *self {
6366 Self::Client { .. } => Side::Client,
6367 Self::Server { .. } => Side::Server,
6368 }
6369 }
6370}
6371
6372impl From<SideArgs> for ConnectionSide {
6373 fn from(side: SideArgs) -> Self {
6374 match side {
6375 SideArgs::Client {
6376 token_store,
6377 server_name,
6378 } => Self::Client {
6379 token: token_store.take(&server_name).unwrap_or_default(),
6380 token_store,
6381 server_name,
6382 },
6383 SideArgs::Server {
6384 server_config,
6385 pref_addr_cid: _,
6386 path_validated: _,
6387 } => Self::Server { server_config },
6388 }
6389 }
6390}
6391
6392pub(crate) enum SideArgs {
6394 Client {
6395 token_store: Arc<dyn TokenStore>,
6396 server_name: String,
6397 },
6398 Server {
6399 server_config: Arc<ServerConfig>,
6400 pref_addr_cid: Option<ConnectionId>,
6401 path_validated: bool,
6402 },
6403}
6404
6405impl SideArgs {
6406 pub(crate) fn pref_addr_cid(&self) -> Option<ConnectionId> {
6407 match *self {
6408 Self::Client { .. } => None,
6409 Self::Server { pref_addr_cid, .. } => pref_addr_cid,
6410 }
6411 }
6412
6413 pub(crate) fn path_validated(&self) -> bool {
6414 match *self {
6415 Self::Client { .. } => true,
6416 Self::Server { path_validated, .. } => path_validated,
6417 }
6418 }
6419
6420 pub(crate) fn side(&self) -> Side {
6421 match *self {
6422 Self::Client { .. } => Side::Client,
6423 Self::Server { .. } => Side::Server,
6424 }
6425 }
6426}
6427
6428#[derive(Debug, Error, Clone, PartialEq, Eq)]
6430pub enum ConnectionError {
6431 #[error("peer doesn't implement any supported version")]
6433 VersionMismatch,
6434 #[error(transparent)]
6436 TransportError(#[from] TransportError),
6437 #[error("aborted by peer: {0}")]
6439 ConnectionClosed(frame::ConnectionClose),
6440 #[error("closed by peer: {0}")]
6442 ApplicationClosed(frame::ApplicationClose),
6443 #[error("reset by peer")]
6445 Reset,
6446 #[error("timed out")]
6452 TimedOut,
6453 #[error("closed")]
6455 LocallyClosed,
6456 #[error("CIDs exhausted")]
6460 CidsExhausted,
6461}
6462
6463impl From<Close> for ConnectionError {
6464 fn from(x: Close) -> Self {
6465 match x {
6466 Close::Connection(reason) => Self::ConnectionClosed(reason),
6467 Close::Application(reason) => Self::ApplicationClosed(reason),
6468 }
6469 }
6470}
6471
6472impl From<ConnectionError> for io::Error {
6474 fn from(x: ConnectionError) -> Self {
6475 use ConnectionError::*;
6476 let kind = match x {
6477 TimedOut => io::ErrorKind::TimedOut,
6478 Reset => io::ErrorKind::ConnectionReset,
6479 ApplicationClosed(_) | ConnectionClosed(_) => io::ErrorKind::ConnectionAborted,
6480 TransportError(_) | VersionMismatch | LocallyClosed | CidsExhausted => {
6481 io::ErrorKind::Other
6482 }
6483 };
6484 Self::new(kind, x)
6485 }
6486}
6487
6488#[derive(Debug, Error, PartialEq, Eq, Clone, Copy)]
6491pub enum PathError {
6492 #[error("multipath extension not negotiated")]
6494 MultipathNotNegotiated,
6495 #[error("the server side may not open a path")]
6497 ServerSideNotAllowed,
6498 #[error("maximum number of concurrent paths reached")]
6500 MaxPathIdReached,
6501 #[error("remoted CIDs exhausted")]
6503 RemoteCidsExhausted,
6504 #[error("path validation failed")]
6506 ValidationFailed,
6507 #[error("invalid remote address")]
6509 InvalidRemoteAddress(SocketAddr),
6510}
6511
6512#[derive(Debug, Error, Clone, Eq, PartialEq)]
6514pub enum ClosePathError {
6515 #[error("closed path")]
6517 ClosedPath,
6518 #[error("last open path")]
6520 LastOpenPath,
6521}
6522
6523#[derive(Debug, Error, Clone, Copy)]
6524#[error("Multipath extension not negotiated")]
6525pub struct MultipathNotNegotiated {
6526 _private: (),
6527}
6528
6529#[derive(Debug)]
6531pub enum Event {
6532 HandshakeDataReady,
6534 Connected,
6536 HandshakeConfirmed,
6538 ConnectionLost {
6542 reason: ConnectionError,
6544 },
6545 Stream(StreamEvent),
6547 DatagramReceived,
6549 DatagramsUnblocked,
6551 Path(PathEvent),
6553 NatTraversal(iroh_hp::Event),
6555}
6556
6557impl From<PathEvent> for Event {
6558 fn from(source: PathEvent) -> Self {
6559 Self::Path(source)
6560 }
6561}
6562
6563fn get_max_ack_delay(params: &TransportParameters) -> Duration {
6564 Duration::from_micros(params.max_ack_delay.0 * 1000)
6565}
6566
6567const MAX_BACKOFF_EXPONENT: u32 = 16;
6569
6570const MIN_PACKET_SPACE: usize = MAX_HANDSHAKE_OR_0RTT_HEADER_SIZE + 32;
6578
6579const MAX_HANDSHAKE_OR_0RTT_HEADER_SIZE: usize =
6585 1 + 4 + 1 + MAX_CID_SIZE + 1 + MAX_CID_SIZE + VarInt::from_u32(u16::MAX as u32).size() + 4;
6586
6587const KEY_UPDATE_MARGIN: u64 = 10_000;
6591
6592#[derive(Default)]
6593struct SentFrames {
6594 retransmits: ThinRetransmits,
6595 largest_acked: FxHashMap<PathId, u64>,
6597 stream_frames: StreamMetaVec,
6598 non_retransmits: bool,
6600 requires_padding: bool,
6602}
6603
6604impl SentFrames {
6605 fn is_ack_only(&self, streams: &StreamsState) -> bool {
6607 !self.largest_acked.is_empty()
6608 && !self.non_retransmits
6609 && self.stream_frames.is_empty()
6610 && self.retransmits.is_empty(streams)
6611 }
6612}
6613
6614fn negotiate_max_idle_timeout(x: Option<VarInt>, y: Option<VarInt>) -> Option<Duration> {
6622 match (x, y) {
6623 (Some(VarInt(0)) | None, Some(VarInt(0)) | None) => None,
6624 (Some(VarInt(0)) | None, Some(y)) => Some(Duration::from_millis(y.0)),
6625 (Some(x), Some(VarInt(0)) | None) => Some(Duration::from_millis(x.0)),
6626 (Some(x), Some(y)) => Some(Duration::from_millis(cmp::min(x, y).0)),
6627 }
6628}
6629
6630#[cfg(test)]
6631mod tests {
6632 use super::*;
6633
6634 #[test]
6635 fn negotiate_max_idle_timeout_commutative() {
6636 let test_params = [
6637 (None, None, None),
6638 (None, Some(VarInt(0)), None),
6639 (None, Some(VarInt(2)), Some(Duration::from_millis(2))),
6640 (Some(VarInt(0)), Some(VarInt(0)), None),
6641 (
6642 Some(VarInt(2)),
6643 Some(VarInt(0)),
6644 Some(Duration::from_millis(2)),
6645 ),
6646 (
6647 Some(VarInt(1)),
6648 Some(VarInt(4)),
6649 Some(Duration::from_millis(1)),
6650 ),
6651 ];
6652
6653 for (left, right, result) in test_params {
6654 assert_eq!(negotiate_max_idle_timeout(left, right), result);
6655 assert_eq!(negotiate_max_idle_timeout(right, left), result);
6656 }
6657 }
6658}