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, false);
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, false) * 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, is_closing: bool) -> Duration {
3086 match space {
3087 SpaceId::Initial | SpaceId::Handshake => self.pto(space, PathId::ZERO),
3088 SpaceId::Data => self
3089 .paths
3090 .iter()
3091 .filter_map(|(path_id, state)| {
3092 if is_closing && state.data.total_sent == 0 && state.data.total_recvd == 0 {
3093 None
3095 } else {
3096 let pto = self.pto(space, *path_id);
3097 Some(pto)
3098 }
3099 })
3100 .max()
3101 .expect("there should be one at least path"),
3102 }
3103 }
3104
3105 fn pto(&self, space: SpaceId, path_id: PathId) -> Duration {
3110 let max_ack_delay = match space {
3111 SpaceId::Initial | SpaceId::Handshake => Duration::ZERO,
3112 SpaceId::Data => self.ack_frequency.max_ack_delay_for_pto(),
3113 };
3114 self.path_data(path_id).rtt.pto_base() + max_ack_delay
3115 }
3116
3117 fn on_packet_authenticated(
3118 &mut self,
3119 now: Instant,
3120 space_id: SpaceId,
3121 path_id: PathId,
3122 ecn: Option<EcnCodepoint>,
3123 packet: Option<u64>,
3124 spin: bool,
3125 is_1rtt: bool,
3126 ) {
3127 self.total_authed_packets += 1;
3128 if let Some(last_allowed_receive) = self
3129 .paths
3130 .get(&path_id)
3131 .and_then(|path| path.data.last_allowed_receive)
3132 {
3133 if now > last_allowed_receive {
3134 warn!("received data on path which we abandoned more than 3 * PTO ago");
3135 if !self.state.is_closed() {
3137 self.state.move_to_closed(TransportError::NO_ERROR(
3139 "peer failed to respond with PATH_ABANDON in time",
3140 ));
3141 self.close_common();
3142 self.set_close_timer(now);
3143 self.close = true;
3144 }
3145 return;
3146 }
3147 }
3148
3149 self.reset_keep_alive(path_id, now);
3150 self.reset_idle_timeout(now, space_id, path_id);
3151 self.permit_idle_reset = true;
3152 self.receiving_ecn |= ecn.is_some();
3153 if let Some(x) = ecn {
3154 let space = &mut self.spaces[space_id];
3155 space.for_path(path_id).ecn_counters += x;
3156
3157 if x.is_ce() {
3158 space
3159 .for_path(path_id)
3160 .pending_acks
3161 .set_immediate_ack_required();
3162 }
3163 }
3164
3165 let packet = match packet {
3166 Some(x) => x,
3167 None => return,
3168 };
3169 match &self.side {
3170 ConnectionSide::Client { .. } => {
3171 if space_id == SpaceId::Handshake {
3175 if let Some(hs) = self.state.as_handshake_mut() {
3176 hs.allow_server_migration = false;
3177 }
3178 }
3179 }
3180 ConnectionSide::Server { .. } => {
3181 if self.spaces[SpaceId::Initial].crypto.is_some() && space_id == SpaceId::Handshake
3182 {
3183 self.discard_space(now, SpaceId::Initial);
3185 }
3186 if self.zero_rtt_crypto.is_some() && is_1rtt {
3187 self.set_key_discard_timer(now, space_id)
3189 }
3190 }
3191 }
3192 let space = self.spaces[space_id].for_path(path_id);
3193 space.pending_acks.insert_one(packet, now);
3194 if packet >= space.rx_packet.unwrap_or_default() {
3195 space.rx_packet = Some(packet);
3196 self.spin = self.side.is_client() ^ spin;
3198 }
3199 }
3200
3201 fn reset_idle_timeout(&mut self, now: Instant, space: SpaceId, path_id: PathId) {
3206 if let Some(timeout) = self.idle_timeout {
3208 if self.state.is_closed() {
3209 self.timers
3210 .stop(Timer::Conn(ConnTimer::Idle), self.qlog.with_time(now));
3211 } else {
3212 let dt = cmp::max(timeout, 3 * self.pto_max_path(space, false));
3213 self.timers.set(
3214 Timer::Conn(ConnTimer::Idle),
3215 now + dt,
3216 self.qlog.with_time(now),
3217 );
3218 }
3219 }
3220
3221 if let Some(timeout) = self.path_data(path_id).idle_timeout {
3223 if self.state.is_closed() {
3224 self.timers.stop(
3225 Timer::PerPath(path_id, PathTimer::PathIdle),
3226 self.qlog.with_time(now),
3227 );
3228 } else {
3229 let dt = cmp::max(timeout, 3 * self.pto(space, path_id));
3230 self.timers.set(
3231 Timer::PerPath(path_id, PathTimer::PathIdle),
3232 now + dt,
3233 self.qlog.with_time(now),
3234 );
3235 }
3236 }
3237 }
3238
3239 fn reset_keep_alive(&mut self, path_id: PathId, now: Instant) {
3241 if !self.state.is_established() {
3242 return;
3243 }
3244
3245 if let Some(interval) = self.config.keep_alive_interval {
3246 self.timers.set(
3247 Timer::Conn(ConnTimer::KeepAlive),
3248 now + interval,
3249 self.qlog.with_time(now),
3250 );
3251 }
3252
3253 if let Some(interval) = self.path_data(path_id).keep_alive {
3254 self.timers.set(
3255 Timer::PerPath(path_id, PathTimer::PathKeepAlive),
3256 now + interval,
3257 self.qlog.with_time(now),
3258 );
3259 }
3260 }
3261
3262 fn reset_cid_retirement(&mut self, now: Instant) {
3264 if let Some((_path, t)) = self.next_cid_retirement() {
3265 self.timers.set(
3266 Timer::Conn(ConnTimer::PushNewCid),
3267 t,
3268 self.qlog.with_time(now),
3269 );
3270 }
3271 }
3272
3273 fn next_cid_retirement(&self) -> Option<(PathId, Instant)> {
3275 self.local_cid_state
3276 .iter()
3277 .filter_map(|(path_id, cid_state)| cid_state.next_timeout().map(|t| (*path_id, t)))
3278 .min_by_key(|(_path_id, timeout)| *timeout)
3279 }
3280
3281 pub(crate) fn handle_first_packet(
3286 &mut self,
3287 now: Instant,
3288 remote: SocketAddr,
3289 ecn: Option<EcnCodepoint>,
3290 packet_number: u64,
3291 packet: InitialPacket,
3292 remaining: Option<BytesMut>,
3293 ) -> Result<(), ConnectionError> {
3294 let span = trace_span!("first recv");
3295 let _guard = span.enter();
3296 debug_assert!(self.side.is_server());
3297 let len = packet.header_data.len() + packet.payload.len();
3298 let path_id = PathId::ZERO;
3299 self.path_data_mut(path_id).total_recvd = len as u64;
3300
3301 if let Some(hs) = self.state.as_handshake_mut() {
3302 hs.expected_token = packet.header.token.clone();
3303 } else {
3304 unreachable!("first packet must be delivered in Handshake state");
3305 }
3306
3307 self.on_packet_authenticated(
3309 now,
3310 SpaceId::Initial,
3311 path_id,
3312 ecn,
3313 Some(packet_number),
3314 false,
3315 false,
3316 );
3317
3318 let packet: Packet = packet.into();
3319
3320 let mut qlog = QlogRecvPacket::new(len);
3321 qlog.header(&packet.header, Some(packet_number), path_id);
3322
3323 self.process_decrypted_packet(
3324 now,
3325 remote,
3326 path_id,
3327 Some(packet_number),
3328 packet,
3329 &mut qlog,
3330 )?;
3331 self.qlog.emit_packet_received(qlog, now);
3332 if let Some(data) = remaining {
3333 self.handle_coalesced(now, remote, path_id, ecn, data);
3334 }
3335
3336 self.qlog.emit_recovery_metrics(
3337 path_id,
3338 &mut self.paths.get_mut(&path_id).unwrap().data,
3339 now,
3340 );
3341
3342 Ok(())
3343 }
3344
3345 fn init_0rtt(&mut self, now: Instant) {
3346 let (header, packet) = match self.crypto.early_crypto() {
3347 Some(x) => x,
3348 None => return,
3349 };
3350 if self.side.is_client() {
3351 match self.crypto.transport_parameters() {
3352 Ok(params) => {
3353 let params = params
3354 .expect("crypto layer didn't supply transport parameters with ticket");
3355 let params = TransportParameters {
3357 initial_src_cid: None,
3358 original_dst_cid: None,
3359 preferred_address: None,
3360 retry_src_cid: None,
3361 stateless_reset_token: None,
3362 min_ack_delay: None,
3363 ack_delay_exponent: TransportParameters::default().ack_delay_exponent,
3364 max_ack_delay: TransportParameters::default().max_ack_delay,
3365 initial_max_path_id: None,
3366 ..params
3367 };
3368 self.set_peer_params(params);
3369 self.qlog.emit_peer_transport_params_restored(self, now);
3370 }
3371 Err(e) => {
3372 error!("session ticket has malformed transport parameters: {}", e);
3373 return;
3374 }
3375 }
3376 }
3377 trace!("0-RTT enabled");
3378 self.zero_rtt_enabled = true;
3379 self.zero_rtt_crypto = Some(ZeroRttCrypto { header, packet });
3380 }
3381
3382 fn read_crypto(
3383 &mut self,
3384 space: SpaceId,
3385 crypto: &frame::Crypto,
3386 payload_len: usize,
3387 ) -> Result<(), TransportError> {
3388 let expected = if !self.state.is_handshake() {
3389 SpaceId::Data
3390 } else if self.highest_space == SpaceId::Initial {
3391 SpaceId::Initial
3392 } else {
3393 SpaceId::Handshake
3396 };
3397 debug_assert!(space <= expected, "received out-of-order CRYPTO data");
3401
3402 let end = crypto.offset + crypto.data.len() as u64;
3403 if space < expected && end > self.spaces[space].crypto_stream.bytes_read() {
3404 warn!(
3405 "received new {:?} CRYPTO data when expecting {:?}",
3406 space, expected
3407 );
3408 return Err(TransportError::PROTOCOL_VIOLATION(
3409 "new data at unexpected encryption level",
3410 ));
3411 }
3412
3413 let space = &mut self.spaces[space];
3414 let max = end.saturating_sub(space.crypto_stream.bytes_read());
3415 if max > self.config.crypto_buffer_size as u64 {
3416 return Err(TransportError::CRYPTO_BUFFER_EXCEEDED(""));
3417 }
3418
3419 space
3420 .crypto_stream
3421 .insert(crypto.offset, crypto.data.clone(), payload_len);
3422 while let Some(chunk) = space.crypto_stream.read(usize::MAX, true) {
3423 trace!("consumed {} CRYPTO bytes", chunk.bytes.len());
3424 if self.crypto.read_handshake(&chunk.bytes)? {
3425 self.events.push_back(Event::HandshakeDataReady);
3426 }
3427 }
3428
3429 Ok(())
3430 }
3431
3432 fn write_crypto(&mut self) {
3433 loop {
3434 let space = self.highest_space;
3435 let mut outgoing = Vec::new();
3436 if let Some(crypto) = self.crypto.write_handshake(&mut outgoing) {
3437 match space {
3438 SpaceId::Initial => {
3439 self.upgrade_crypto(SpaceId::Handshake, crypto);
3440 }
3441 SpaceId::Handshake => {
3442 self.upgrade_crypto(SpaceId::Data, crypto);
3443 }
3444 _ => unreachable!("got updated secrets during 1-RTT"),
3445 }
3446 }
3447 if outgoing.is_empty() {
3448 if space == self.highest_space {
3449 break;
3450 } else {
3451 continue;
3453 }
3454 }
3455 let offset = self.spaces[space].crypto_offset;
3456 let outgoing = Bytes::from(outgoing);
3457 if let Some(hs) = self.state.as_handshake_mut() {
3458 if space == SpaceId::Initial && offset == 0 && self.side.is_client() {
3459 hs.client_hello = Some(outgoing.clone());
3460 }
3461 }
3462 self.spaces[space].crypto_offset += outgoing.len() as u64;
3463 trace!("wrote {} {:?} CRYPTO bytes", outgoing.len(), space);
3464 self.spaces[space].pending.crypto.push_back(frame::Crypto {
3465 offset,
3466 data: outgoing,
3467 });
3468 }
3469 }
3470
3471 fn upgrade_crypto(&mut self, space: SpaceId, crypto: Keys) {
3473 debug_assert!(
3474 self.spaces[space].crypto.is_none(),
3475 "already reached packet space {space:?}"
3476 );
3477 trace!("{:?} keys ready", space);
3478 if space == SpaceId::Data {
3479 self.next_crypto = Some(
3481 self.crypto
3482 .next_1rtt_keys()
3483 .expect("handshake should be complete"),
3484 );
3485 }
3486
3487 self.spaces[space].crypto = Some(crypto);
3488 debug_assert!(space as usize > self.highest_space as usize);
3489 self.highest_space = space;
3490 if space == SpaceId::Data && self.side.is_client() {
3491 self.zero_rtt_crypto = None;
3493 }
3494 }
3495
3496 fn discard_space(&mut self, now: Instant, space_id: SpaceId) {
3497 debug_assert!(space_id != SpaceId::Data);
3498 trace!("discarding {:?} keys", space_id);
3499 if space_id == SpaceId::Initial {
3500 if let ConnectionSide::Client { token, .. } = &mut self.side {
3502 *token = Bytes::new();
3503 }
3504 }
3505 let space = &mut self.spaces[space_id];
3506 space.crypto = None;
3507 let pns = space.for_path(PathId::ZERO);
3508 pns.time_of_last_ack_eliciting_packet = None;
3509 pns.loss_time = None;
3510 pns.loss_probes = 0;
3511 let sent_packets = mem::take(&mut pns.sent_packets);
3512 let path = self.paths.get_mut(&PathId::ZERO).unwrap();
3513 for (_, packet) in sent_packets.into_iter() {
3514 path.data.remove_in_flight(&packet);
3515 }
3516
3517 self.set_loss_detection_timer(now, PathId::ZERO)
3518 }
3519
3520 fn handle_coalesced(
3521 &mut self,
3522 now: Instant,
3523 remote: SocketAddr,
3524 path_id: PathId,
3525 ecn: Option<EcnCodepoint>,
3526 data: BytesMut,
3527 ) {
3528 self.path_data_mut(path_id)
3529 .inc_total_recvd(data.len() as u64);
3530 let mut remaining = Some(data);
3531 let cid_len = self
3532 .local_cid_state
3533 .values()
3534 .map(|cid_state| cid_state.cid_len())
3535 .next()
3536 .expect("one cid_state must exist");
3537 while let Some(data) = remaining {
3538 match PartialDecode::new(
3539 data,
3540 &FixedLengthConnectionIdParser::new(cid_len),
3541 &[self.version],
3542 self.endpoint_config.grease_quic_bit,
3543 ) {
3544 Ok((partial_decode, rest)) => {
3545 remaining = rest;
3546 self.handle_decode(now, remote, path_id, ecn, partial_decode);
3547 }
3548 Err(e) => {
3549 trace!("malformed header: {}", e);
3550 return;
3551 }
3552 }
3553 }
3554 }
3555
3556 fn handle_decode(
3557 &mut self,
3558 now: Instant,
3559 remote: SocketAddr,
3560 path_id: PathId,
3561 ecn: Option<EcnCodepoint>,
3562 partial_decode: PartialDecode,
3563 ) {
3564 let qlog = QlogRecvPacket::new(partial_decode.len());
3565 if let Some(decoded) = packet_crypto::unprotect_header(
3566 partial_decode,
3567 &self.spaces,
3568 self.zero_rtt_crypto.as_ref(),
3569 self.peer_params.stateless_reset_token,
3570 ) {
3571 self.handle_packet(
3572 now,
3573 remote,
3574 path_id,
3575 ecn,
3576 decoded.packet,
3577 decoded.stateless_reset,
3578 qlog,
3579 );
3580 }
3581 }
3582
3583 fn handle_packet(
3584 &mut self,
3585 now: Instant,
3586 remote: SocketAddr,
3587 path_id: PathId,
3588 ecn: Option<EcnCodepoint>,
3589 packet: Option<Packet>,
3590 stateless_reset: bool,
3591 mut qlog: QlogRecvPacket,
3592 ) {
3593 self.stats.udp_rx.ios += 1;
3594 if let Some(ref packet) = packet {
3595 trace!(
3596 "got {:?} packet ({} bytes) from {} using id {}",
3597 packet.header.space(),
3598 packet.payload.len() + packet.header_data.len(),
3599 remote,
3600 packet.header.dst_cid(),
3601 );
3602 }
3603
3604 if self.is_handshaking() {
3605 if path_id != PathId::ZERO {
3606 debug!(%remote, %path_id, "discarding multipath packet during handshake");
3607 return;
3608 }
3609 if remote != self.path_data_mut(path_id).remote {
3610 if let Some(hs) = self.state.as_handshake() {
3611 if hs.allow_server_migration {
3612 trace!(?remote, prev = ?self.path_data(path_id).remote, "server migrated to new remote");
3613 self.path_data_mut(path_id).remote = remote;
3614 self.qlog.emit_tuple_assigned(path_id, remote, now);
3615 } else {
3616 debug!("discarding packet with unexpected remote during handshake");
3617 return;
3618 }
3619 } else {
3620 debug!("discarding packet with unexpected remote during handshake");
3621 return;
3622 }
3623 }
3624 }
3625
3626 let was_closed = self.state.is_closed();
3627 let was_drained = self.state.is_drained();
3628
3629 let decrypted = match packet {
3630 None => Err(None),
3631 Some(mut packet) => self
3632 .decrypt_packet(now, path_id, &mut packet)
3633 .map(move |number| (packet, number)),
3634 };
3635 let result = match decrypted {
3636 _ if stateless_reset => {
3637 debug!("got stateless reset");
3638 Err(ConnectionError::Reset)
3639 }
3640 Err(Some(e)) => {
3641 warn!("illegal packet: {}", e);
3642 Err(e.into())
3643 }
3644 Err(None) => {
3645 debug!("failed to authenticate packet");
3646 self.authentication_failures += 1;
3647 let integrity_limit = self.spaces[self.highest_space]
3648 .crypto
3649 .as_ref()
3650 .unwrap()
3651 .packet
3652 .local
3653 .integrity_limit();
3654 if self.authentication_failures > integrity_limit {
3655 Err(TransportError::AEAD_LIMIT_REACHED("integrity limit violated").into())
3656 } else {
3657 return;
3658 }
3659 }
3660 Ok((packet, number)) => {
3661 qlog.header(&packet.header, number, path_id);
3662 let span = match number {
3663 Some(pn) => trace_span!("recv", space = ?packet.header.space(), pn),
3664 None => trace_span!("recv", space = ?packet.header.space()),
3665 };
3666 let _guard = span.enter();
3667
3668 let dedup = self.spaces[packet.header.space()]
3669 .path_space_mut(path_id)
3670 .map(|pns| &mut pns.dedup);
3671 if number.zip(dedup).is_some_and(|(n, d)| d.insert(n)) {
3672 debug!("discarding possible duplicate packet");
3673 self.qlog.emit_packet_received(qlog, now);
3674 return;
3675 } else if self.state.is_handshake() && packet.header.is_short() {
3676 trace!("dropping short packet during handshake");
3678 self.qlog.emit_packet_received(qlog, now);
3679 return;
3680 } else {
3681 if let Header::Initial(InitialHeader { ref token, .. }) = packet.header {
3682 if let Some(hs) = self.state.as_handshake() {
3683 if self.side.is_server() && token != &hs.expected_token {
3684 warn!("discarding Initial with invalid retry token");
3688 self.qlog.emit_packet_received(qlog, now);
3689 return;
3690 }
3691 }
3692 }
3693
3694 if !self.state.is_closed() {
3695 let spin = match packet.header {
3696 Header::Short { spin, .. } => spin,
3697 _ => false,
3698 };
3699
3700 if self.side().is_server() && !self.abandoned_paths.contains(&path_id) {
3701 self.ensure_path(path_id, remote, now, number);
3703 }
3704 if self.paths.contains_key(&path_id) {
3705 self.on_packet_authenticated(
3706 now,
3707 packet.header.space(),
3708 path_id,
3709 ecn,
3710 number,
3711 spin,
3712 packet.header.is_1rtt(),
3713 );
3714 }
3715 }
3716
3717 let res = self
3718 .process_decrypted_packet(now, remote, path_id, number, packet, &mut qlog);
3719
3720 self.qlog.emit_packet_received(qlog, now);
3721 res
3722 }
3723 }
3724 };
3725
3726 if let Err(conn_err) = result {
3728 match conn_err {
3729 ConnectionError::ApplicationClosed(reason) => self.state.move_to_closed(reason),
3730 ConnectionError::ConnectionClosed(reason) => self.state.move_to_closed(reason),
3731 ConnectionError::Reset
3732 | ConnectionError::TransportError(TransportError {
3733 code: TransportErrorCode::AEAD_LIMIT_REACHED,
3734 ..
3735 }) => {
3736 self.state.move_to_drained(Some(conn_err));
3737 }
3738 ConnectionError::TimedOut => {
3739 unreachable!("timeouts aren't generated by packet processing");
3740 }
3741 ConnectionError::TransportError(err) => {
3742 debug!("closing connection due to transport error: {}", err);
3743 self.state.move_to_closed(err);
3744 }
3745 ConnectionError::VersionMismatch => {
3746 self.state.move_to_draining(Some(conn_err));
3747 }
3748 ConnectionError::LocallyClosed => {
3749 unreachable!("LocallyClosed isn't generated by packet processing");
3750 }
3751 ConnectionError::CidsExhausted => {
3752 unreachable!("CidsExhausted isn't generated by packet processing");
3753 }
3754 };
3755 }
3756
3757 if !was_closed && self.state.is_closed() {
3758 self.close_common();
3759 if !self.state.is_drained() {
3760 self.set_close_timer(now);
3761 }
3762 }
3763 if !was_drained && self.state.is_drained() {
3764 self.endpoint_events.push_back(EndpointEventInner::Drained);
3765 self.timers
3768 .stop(Timer::Conn(ConnTimer::Close), self.qlog.with_time(now));
3769 }
3770
3771 if matches!(self.state.as_type(), StateType::Closed) {
3773 let path_remote = self
3777 .paths
3778 .get(&path_id)
3779 .map(|p| p.data.remote)
3780 .unwrap_or(remote);
3781 self.close = remote == path_remote;
3782 }
3783 }
3784
3785 fn process_decrypted_packet(
3786 &mut self,
3787 now: Instant,
3788 remote: SocketAddr,
3789 path_id: PathId,
3790 number: Option<u64>,
3791 packet: Packet,
3792 qlog: &mut QlogRecvPacket,
3793 ) -> Result<(), ConnectionError> {
3794 if !self.paths.contains_key(&path_id) {
3795 trace!(%path_id, ?number, "discarding packet for unknown path");
3799 return Ok(());
3800 }
3801 let state = match self.state.as_type() {
3802 StateType::Established => {
3803 match packet.header.space() {
3804 SpaceId::Data => {
3805 self.process_payload(now, remote, path_id, number.unwrap(), packet, qlog)?
3806 }
3807 _ if packet.header.has_frames() => {
3808 self.process_early_payload(now, path_id, packet, qlog)?
3809 }
3810 _ => {
3811 trace!("discarding unexpected pre-handshake packet");
3812 }
3813 }
3814 return Ok(());
3815 }
3816 StateType::Closed => {
3817 for result in frame::Iter::new(packet.payload.freeze())? {
3818 let frame = match result {
3819 Ok(frame) => frame,
3820 Err(err) => {
3821 debug!("frame decoding error: {err:?}");
3822 continue;
3823 }
3824 };
3825 qlog.frame(&frame);
3826
3827 if let Frame::Padding = frame {
3828 continue;
3829 };
3830
3831 self.stats.frame_rx.record(&frame);
3832
3833 if let Frame::Close(_error) = frame {
3834 trace!("draining");
3835 self.state.move_to_draining(None);
3836 break;
3837 }
3838 }
3839 return Ok(());
3840 }
3841 StateType::Draining | StateType::Drained => return Ok(()),
3842 StateType::Handshake => self.state.as_handshake_mut().expect("checked"),
3843 };
3844
3845 match packet.header {
3846 Header::Retry {
3847 src_cid: rem_cid, ..
3848 } => {
3849 debug_assert_eq!(path_id, PathId::ZERO);
3850 if self.side.is_server() {
3851 return Err(TransportError::PROTOCOL_VIOLATION("client sent Retry").into());
3852 }
3853
3854 let is_valid_retry = self
3855 .rem_cids
3856 .get(&path_id)
3857 .map(|cids| cids.active())
3858 .map(|orig_dst_cid| {
3859 self.crypto.is_valid_retry(
3860 orig_dst_cid,
3861 &packet.header_data,
3862 &packet.payload,
3863 )
3864 })
3865 .unwrap_or_default();
3866 if self.total_authed_packets > 1
3867 || packet.payload.len() <= 16 || !is_valid_retry
3869 {
3870 trace!("discarding invalid Retry");
3871 return Ok(());
3879 }
3880
3881 trace!("retrying with CID {}", rem_cid);
3882 let client_hello = state.client_hello.take().unwrap();
3883 self.retry_src_cid = Some(rem_cid);
3884 self.rem_cids
3885 .get_mut(&path_id)
3886 .expect("PathId::ZERO not yet abandoned, is_valid_retry would have been false")
3887 .update_initial_cid(rem_cid);
3888 self.rem_handshake_cid = rem_cid;
3889
3890 let space = &mut self.spaces[SpaceId::Initial];
3891 if let Some(info) = space.for_path(PathId::ZERO).take(0) {
3892 self.on_packet_acked(now, PathId::ZERO, info);
3893 };
3894
3895 self.discard_space(now, SpaceId::Initial); self.spaces[SpaceId::Initial] = {
3898 let mut space = PacketSpace::new(now, SpaceId::Initial, &mut self.rng);
3899 space.crypto = Some(self.crypto.initial_keys(rem_cid, self.side.side()));
3900 space.crypto_offset = client_hello.len() as u64;
3901 space.for_path(path_id).next_packet_number = self.spaces[SpaceId::Initial]
3902 .for_path(path_id)
3903 .next_packet_number;
3904 space.pending.crypto.push_back(frame::Crypto {
3905 offset: 0,
3906 data: client_hello,
3907 });
3908 space
3909 };
3910
3911 let zero_rtt = mem::take(
3913 &mut self.spaces[SpaceId::Data]
3914 .for_path(PathId::ZERO)
3915 .sent_packets,
3916 );
3917 for (_, info) in zero_rtt.into_iter() {
3918 self.paths
3919 .get_mut(&PathId::ZERO)
3920 .unwrap()
3921 .remove_in_flight(&info);
3922 self.spaces[SpaceId::Data].pending |= info.retransmits;
3923 }
3924 self.streams.retransmit_all_for_0rtt();
3925
3926 let token_len = packet.payload.len() - 16;
3927 let ConnectionSide::Client { ref mut token, .. } = self.side else {
3928 unreachable!("we already short-circuited if we're server");
3929 };
3930 *token = packet.payload.freeze().split_to(token_len);
3931
3932 self.state = State::handshake(state::Handshake {
3933 expected_token: Bytes::new(),
3934 rem_cid_set: false,
3935 client_hello: None,
3936 allow_server_migration: true,
3937 });
3938 Ok(())
3939 }
3940 Header::Long {
3941 ty: LongType::Handshake,
3942 src_cid: rem_cid,
3943 dst_cid: loc_cid,
3944 ..
3945 } => {
3946 debug_assert_eq!(path_id, PathId::ZERO);
3947 if rem_cid != self.rem_handshake_cid {
3948 debug!(
3949 "discarding packet with mismatched remote CID: {} != {}",
3950 self.rem_handshake_cid, rem_cid
3951 );
3952 return Ok(());
3953 }
3954 self.on_path_validated(path_id);
3955
3956 self.process_early_payload(now, path_id, packet, qlog)?;
3957 if self.state.is_closed() {
3958 return Ok(());
3959 }
3960
3961 if self.crypto.is_handshaking() {
3962 trace!("handshake ongoing");
3963 return Ok(());
3964 }
3965
3966 if self.side.is_client() {
3967 let params = self.crypto.transport_parameters()?.ok_or_else(|| {
3969 TransportError::new(
3970 TransportErrorCode::crypto(0x6d),
3971 "transport parameters missing".to_owned(),
3972 )
3973 })?;
3974
3975 if self.has_0rtt() {
3976 if !self.crypto.early_data_accepted().unwrap() {
3977 debug_assert!(self.side.is_client());
3978 debug!("0-RTT rejected");
3979 self.accepted_0rtt = false;
3980 self.streams.zero_rtt_rejected();
3981
3982 self.spaces[SpaceId::Data].pending = Retransmits::default();
3984
3985 let sent_packets = mem::take(
3987 &mut self.spaces[SpaceId::Data].for_path(path_id).sent_packets,
3988 );
3989 for (_, packet) in sent_packets.into_iter() {
3990 self.paths
3991 .get_mut(&path_id)
3992 .unwrap()
3993 .remove_in_flight(&packet);
3994 }
3995 } else {
3996 self.accepted_0rtt = true;
3997 params.validate_resumption_from(&self.peer_params)?;
3998 }
3999 }
4000 if let Some(token) = params.stateless_reset_token {
4001 let remote = self.path_data(path_id).remote;
4002 self.endpoint_events
4003 .push_back(EndpointEventInner::ResetToken(path_id, remote, token));
4004 }
4005 self.handle_peer_params(params, loc_cid, rem_cid, now)?;
4006 self.issue_first_cids(now);
4007 } else {
4008 self.spaces[SpaceId::Data].pending.handshake_done = true;
4010 self.discard_space(now, SpaceId::Handshake);
4011 self.events.push_back(Event::HandshakeConfirmed);
4012 trace!("handshake confirmed");
4013 }
4014
4015 self.events.push_back(Event::Connected);
4016 self.state.move_to_established();
4017 trace!("established");
4018
4019 self.issue_first_path_cids(now);
4022 Ok(())
4023 }
4024 Header::Initial(InitialHeader {
4025 src_cid: rem_cid,
4026 dst_cid: loc_cid,
4027 ..
4028 }) => {
4029 debug_assert_eq!(path_id, PathId::ZERO);
4030 if !state.rem_cid_set {
4031 trace!("switching remote CID to {}", rem_cid);
4032 let mut state = state.clone();
4033 self.rem_cids
4034 .get_mut(&path_id)
4035 .expect("PathId::ZERO not yet abandoned")
4036 .update_initial_cid(rem_cid);
4037 self.rem_handshake_cid = rem_cid;
4038 self.orig_rem_cid = rem_cid;
4039 state.rem_cid_set = true;
4040 self.state.move_to_handshake(state);
4041 } else if rem_cid != self.rem_handshake_cid {
4042 debug!(
4043 "discarding packet with mismatched remote CID: {} != {}",
4044 self.rem_handshake_cid, rem_cid
4045 );
4046 return Ok(());
4047 }
4048
4049 let starting_space = self.highest_space;
4050 self.process_early_payload(now, path_id, packet, qlog)?;
4051
4052 if self.side.is_server()
4053 && starting_space == SpaceId::Initial
4054 && self.highest_space != SpaceId::Initial
4055 {
4056 let params = self.crypto.transport_parameters()?.ok_or_else(|| {
4057 TransportError::new(
4058 TransportErrorCode::crypto(0x6d),
4059 "transport parameters missing".to_owned(),
4060 )
4061 })?;
4062 self.handle_peer_params(params, loc_cid, rem_cid, now)?;
4063 self.issue_first_cids(now);
4064 self.init_0rtt(now);
4065 }
4066 Ok(())
4067 }
4068 Header::Long {
4069 ty: LongType::ZeroRtt,
4070 ..
4071 } => {
4072 self.process_payload(now, remote, path_id, number.unwrap(), packet, qlog)?;
4073 Ok(())
4074 }
4075 Header::VersionNegotiate { .. } => {
4076 if self.total_authed_packets > 1 {
4077 return Ok(());
4078 }
4079 let supported = packet
4080 .payload
4081 .chunks(4)
4082 .any(|x| match <[u8; 4]>::try_from(x) {
4083 Ok(version) => self.version == u32::from_be_bytes(version),
4084 Err(_) => false,
4085 });
4086 if supported {
4087 return Ok(());
4088 }
4089 debug!("remote doesn't support our version");
4090 Err(ConnectionError::VersionMismatch)
4091 }
4092 Header::Short { .. } => unreachable!(
4093 "short packets received during handshake are discarded in handle_packet"
4094 ),
4095 }
4096 }
4097
4098 fn process_early_payload(
4100 &mut self,
4101 now: Instant,
4102 path_id: PathId,
4103 packet: Packet,
4104 #[allow(unused)] qlog: &mut QlogRecvPacket,
4105 ) -> Result<(), TransportError> {
4106 debug_assert_ne!(packet.header.space(), SpaceId::Data);
4107 debug_assert_eq!(path_id, PathId::ZERO);
4108 let payload_len = packet.payload.len();
4109 let mut ack_eliciting = false;
4110 for result in frame::Iter::new(packet.payload.freeze())? {
4111 let frame = result?;
4112 qlog.frame(&frame);
4113 let span = match frame {
4114 Frame::Padding => continue,
4115 _ => Some(trace_span!("frame", ty = %frame.ty(), path = tracing::field::Empty)),
4116 };
4117
4118 self.stats.frame_rx.record(&frame);
4119
4120 let _guard = span.as_ref().map(|x| x.enter());
4121 ack_eliciting |= frame.is_ack_eliciting();
4122
4123 if frame.is_1rtt() && packet.header.space() != SpaceId::Data {
4125 return Err(TransportError::PROTOCOL_VIOLATION(
4126 "illegal frame type in handshake",
4127 ));
4128 }
4129
4130 match frame {
4131 Frame::Padding | Frame::Ping => {}
4132 Frame::Crypto(frame) => {
4133 self.read_crypto(packet.header.space(), &frame, payload_len)?;
4134 }
4135 Frame::Ack(ack) => {
4136 self.on_ack_received(now, packet.header.space(), ack)?;
4137 }
4138 Frame::PathAck(ack) => {
4139 span.as_ref()
4140 .map(|span| span.record("path", tracing::field::debug(&ack.path_id)));
4141 self.on_path_ack_received(now, packet.header.space(), ack)?;
4142 }
4143 Frame::Close(reason) => {
4144 self.state.move_to_draining(Some(reason.into()));
4145 return Ok(());
4146 }
4147 _ => {
4148 let mut err =
4149 TransportError::PROTOCOL_VIOLATION("illegal frame type in handshake");
4150 err.frame = Some(frame.ty());
4151 return Err(err);
4152 }
4153 }
4154 }
4155
4156 if ack_eliciting {
4157 self.spaces[packet.header.space()]
4159 .for_path(path_id)
4160 .pending_acks
4161 .set_immediate_ack_required();
4162 }
4163
4164 self.write_crypto();
4165 Ok(())
4166 }
4167
4168 fn process_payload(
4170 &mut self,
4171 now: Instant,
4172 remote: SocketAddr,
4173 path_id: PathId,
4174 number: u64,
4175 packet: Packet,
4176 #[allow(unused)] qlog: &mut QlogRecvPacket,
4177 ) -> Result<(), TransportError> {
4178 let payload = packet.payload.freeze();
4179 let mut is_probing_packet = true;
4180 let mut close = None;
4181 let payload_len = payload.len();
4182 let mut ack_eliciting = false;
4183 let mut migration_observed_addr = None;
4186 for result in frame::Iter::new(payload)? {
4187 let frame = result?;
4188 qlog.frame(&frame);
4189 let span = match frame {
4190 Frame::Padding => continue,
4191 _ => trace_span!("frame", ty = %frame.ty(), path = tracing::field::Empty),
4192 };
4193
4194 self.stats.frame_rx.record(&frame);
4195 match &frame {
4198 Frame::Crypto(f) => {
4199 trace!(offset = f.offset, len = f.data.len(), "got crypto frame");
4200 }
4201 Frame::Stream(f) => {
4202 trace!(id = %f.id, offset = f.offset, len = f.data.len(), fin = f.fin, "got stream frame");
4203 }
4204 Frame::Datagram(f) => {
4205 trace!(len = f.data.len(), "got datagram frame");
4206 }
4207 f => {
4208 trace!("got frame {:?}", f);
4209 }
4210 }
4211
4212 let _guard = span.enter();
4213 if packet.header.is_0rtt() {
4214 match frame {
4215 Frame::Crypto(_) | Frame::Close(Close::Application(_)) => {
4216 return Err(TransportError::PROTOCOL_VIOLATION(
4217 "illegal frame type in 0-RTT",
4218 ));
4219 }
4220 _ => {
4221 if frame.is_1rtt() {
4222 return Err(TransportError::PROTOCOL_VIOLATION(
4223 "illegal frame type in 0-RTT",
4224 ));
4225 }
4226 }
4227 }
4228 }
4229 ack_eliciting |= frame.is_ack_eliciting();
4230
4231 match frame {
4233 Frame::Padding
4234 | Frame::PathChallenge(_)
4235 | Frame::PathResponse(_)
4236 | Frame::NewConnectionId(_)
4237 | Frame::ObservedAddr(_) => {}
4238 _ => {
4239 is_probing_packet = false;
4240 }
4241 }
4242
4243 match frame {
4244 Frame::Crypto(frame) => {
4245 self.read_crypto(SpaceId::Data, &frame, payload_len)?;
4246 }
4247 Frame::Stream(frame) => {
4248 if self.streams.received(frame, payload_len)?.should_transmit() {
4249 self.spaces[SpaceId::Data].pending.max_data = true;
4250 }
4251 }
4252 Frame::Ack(ack) => {
4253 self.on_ack_received(now, SpaceId::Data, ack)?;
4254 }
4255 Frame::PathAck(ack) => {
4256 span.record("path", tracing::field::debug(&ack.path_id));
4257 self.on_path_ack_received(now, SpaceId::Data, ack)?;
4258 }
4259 Frame::Padding | Frame::Ping => {}
4260 Frame::Close(reason) => {
4261 close = Some(reason);
4262 }
4263 Frame::PathChallenge(challenge) => {
4264 let path = &mut self
4265 .path_mut(path_id)
4266 .expect("payload is processed only after the path becomes known");
4267 path.path_responses.push(number, challenge.0, remote);
4268 if remote == path.remote {
4269 match self.peer_supports_ack_frequency() {
4279 true => self.immediate_ack(path_id),
4280 false => {
4281 self.ping_path(path_id).ok();
4282 }
4283 }
4284 }
4285 }
4286 Frame::PathResponse(response) => {
4287 let path = self
4288 .paths
4289 .get_mut(&path_id)
4290 .expect("payload is processed only after the path becomes known");
4291
4292 use PathTimer::*;
4293 use paths::OnPathResponseReceived::*;
4294 match path.data.on_path_response_received(now, response.0, remote) {
4295 OnPath { was_open } => {
4296 let qlog = self.qlog.with_time(now);
4297
4298 self.timers
4299 .stop(Timer::PerPath(path_id, PathValidation), qlog.clone());
4300 self.timers
4301 .stop(Timer::PerPath(path_id, PathOpen), qlog.clone());
4302
4303 let next_challenge = path
4304 .data
4305 .earliest_expiring_challenge()
4306 .map(|time| time + self.ack_frequency.max_ack_delay_for_pto());
4307 self.timers.set_or_stop(
4308 Timer::PerPath(path_id, PathChallengeLost),
4309 next_challenge,
4310 qlog,
4311 );
4312
4313 if !was_open {
4314 self.events
4315 .push_back(Event::Path(PathEvent::Opened { id: path_id }));
4316 if let Some(observed) = path.data.last_observed_addr_report.as_ref()
4317 {
4318 self.events.push_back(Event::Path(PathEvent::ObservedAddr {
4319 id: path_id,
4320 addr: observed.socket_addr(),
4321 }));
4322 }
4323 }
4324 if let Some((_, ref mut prev)) = path.prev {
4325 prev.challenges_sent.clear();
4326 prev.send_new_challenge = false;
4327 }
4328 }
4329 OffPath => {
4330 debug!("Response to off-path PathChallenge!");
4331 let next_challenge = path
4332 .data
4333 .earliest_expiring_challenge()
4334 .map(|time| time + self.ack_frequency.max_ack_delay_for_pto());
4335 self.timers.set_or_stop(
4336 Timer::PerPath(path_id, PathChallengeLost),
4337 next_challenge,
4338 self.qlog.with_time(now),
4339 );
4340 }
4341 Invalid { expected } => {
4342 debug!(%response, from=%remote, %expected, "ignoring invalid PATH_RESPONSE")
4343 }
4344 Unknown => debug!(%response, "ignoring invalid PATH_RESPONSE"),
4345 }
4346 }
4347 Frame::MaxData(bytes) => {
4348 self.streams.received_max_data(bytes);
4349 }
4350 Frame::MaxStreamData { id, offset } => {
4351 self.streams.received_max_stream_data(id, offset)?;
4352 }
4353 Frame::MaxStreams { dir, count } => {
4354 self.streams.received_max_streams(dir, count)?;
4355 }
4356 Frame::ResetStream(frame) => {
4357 if self.streams.received_reset(frame)?.should_transmit() {
4358 self.spaces[SpaceId::Data].pending.max_data = true;
4359 }
4360 }
4361 Frame::DataBlocked { offset } => {
4362 debug!(offset, "peer claims to be blocked at connection level");
4363 }
4364 Frame::StreamDataBlocked { id, offset } => {
4365 if id.initiator() == self.side.side() && id.dir() == Dir::Uni {
4366 debug!("got STREAM_DATA_BLOCKED on send-only {}", id);
4367 return Err(TransportError::STREAM_STATE_ERROR(
4368 "STREAM_DATA_BLOCKED on send-only stream",
4369 ));
4370 }
4371 debug!(
4372 stream = %id,
4373 offset, "peer claims to be blocked at stream level"
4374 );
4375 }
4376 Frame::StreamsBlocked { dir, limit } => {
4377 if limit > MAX_STREAM_COUNT {
4378 return Err(TransportError::FRAME_ENCODING_ERROR(
4379 "unrepresentable stream limit",
4380 ));
4381 }
4382 debug!(
4383 "peer claims to be blocked opening more than {} {} streams",
4384 limit, dir
4385 );
4386 }
4387 Frame::StopSending(frame::StopSending { id, error_code }) => {
4388 if id.initiator() != self.side.side() {
4389 if id.dir() == Dir::Uni {
4390 debug!("got STOP_SENDING on recv-only {}", id);
4391 return Err(TransportError::STREAM_STATE_ERROR(
4392 "STOP_SENDING on recv-only stream",
4393 ));
4394 }
4395 } else if self.streams.is_local_unopened(id) {
4396 return Err(TransportError::STREAM_STATE_ERROR(
4397 "STOP_SENDING on unopened stream",
4398 ));
4399 }
4400 self.streams.received_stop_sending(id, error_code);
4401 }
4402 Frame::RetireConnectionId(frame::RetireConnectionId { path_id, sequence }) => {
4403 if let Some(ref path_id) = path_id {
4404 span.record("path", tracing::field::debug(&path_id));
4405 }
4406 let path_id = path_id.unwrap_or_default();
4407 match self.local_cid_state.get_mut(&path_id) {
4408 None => error!(?path_id, "RETIRE_CONNECTION_ID for unknown path"),
4409 Some(cid_state) => {
4410 let allow_more_cids = cid_state
4411 .on_cid_retirement(sequence, self.peer_params.issue_cids_limit())?;
4412
4413 let has_path = !self.abandoned_paths.contains(&path_id);
4417 let allow_more_cids = allow_more_cids && has_path;
4418
4419 self.endpoint_events
4420 .push_back(EndpointEventInner::RetireConnectionId(
4421 now,
4422 path_id,
4423 sequence,
4424 allow_more_cids,
4425 ));
4426 }
4427 }
4428 }
4429 Frame::NewConnectionId(frame) => {
4430 let path_id = if let Some(path_id) = frame.path_id {
4431 if !self.is_multipath_negotiated() {
4432 return Err(TransportError::PROTOCOL_VIOLATION(
4433 "received PATH_NEW_CONNECTION_ID frame when multipath was not negotiated",
4434 ));
4435 }
4436 if path_id > self.local_max_path_id {
4437 return Err(TransportError::PROTOCOL_VIOLATION(
4438 "PATH_NEW_CONNECTION_ID contains path_id exceeding current max",
4439 ));
4440 }
4441 path_id
4442 } else {
4443 PathId::ZERO
4444 };
4445
4446 if self.abandoned_paths.contains(&path_id) {
4447 trace!("ignoring issued CID for abandoned path");
4448 continue;
4449 }
4450 if let Some(ref path_id) = frame.path_id {
4451 span.record("path", tracing::field::debug(&path_id));
4452 }
4453 let rem_cids = self
4454 .rem_cids
4455 .entry(path_id)
4456 .or_insert_with(|| CidQueue::new(frame.id));
4457 if rem_cids.active().is_empty() {
4458 return Err(TransportError::PROTOCOL_VIOLATION(
4460 "NEW_CONNECTION_ID when CIDs aren't in use",
4461 ));
4462 }
4463 if frame.retire_prior_to > frame.sequence {
4464 return Err(TransportError::PROTOCOL_VIOLATION(
4465 "NEW_CONNECTION_ID retiring unissued CIDs",
4466 ));
4467 }
4468
4469 use crate::cid_queue::InsertError;
4470 match rem_cids.insert(frame) {
4471 Ok(None) => {}
4472 Ok(Some((retired, reset_token))) => {
4473 let pending_retired =
4474 &mut self.spaces[SpaceId::Data].pending.retire_cids;
4475 const MAX_PENDING_RETIRED_CIDS: u64 = CidQueue::LEN as u64 * 10;
4478 if (pending_retired.len() as u64)
4481 .saturating_add(retired.end.saturating_sub(retired.start))
4482 > MAX_PENDING_RETIRED_CIDS
4483 {
4484 return Err(TransportError::CONNECTION_ID_LIMIT_ERROR(
4485 "queued too many retired CIDs",
4486 ));
4487 }
4488 pending_retired.extend(retired.map(|seq| (path_id, seq)));
4489 self.set_reset_token(path_id, remote, reset_token);
4490 }
4491 Err(InsertError::ExceedsLimit) => {
4492 return Err(TransportError::CONNECTION_ID_LIMIT_ERROR(""));
4493 }
4494 Err(InsertError::Retired) => {
4495 trace!("discarding already-retired");
4496 self.spaces[SpaceId::Data]
4500 .pending
4501 .retire_cids
4502 .push((path_id, frame.sequence));
4503 continue;
4504 }
4505 };
4506
4507 if self.side.is_server()
4508 && path_id == PathId::ZERO
4509 && self
4510 .rem_cids
4511 .get(&PathId::ZERO)
4512 .map(|cids| cids.active_seq() == 0)
4513 .unwrap_or_default()
4514 {
4515 self.update_rem_cid(PathId::ZERO);
4518 }
4519 }
4520 Frame::NewToken(NewToken { token }) => {
4521 let ConnectionSide::Client {
4522 token_store,
4523 server_name,
4524 ..
4525 } = &self.side
4526 else {
4527 return Err(TransportError::PROTOCOL_VIOLATION("client sent NEW_TOKEN"));
4528 };
4529 if token.is_empty() {
4530 return Err(TransportError::FRAME_ENCODING_ERROR("empty token"));
4531 }
4532 trace!("got new token");
4533 token_store.insert(server_name, token);
4534 }
4535 Frame::Datagram(datagram) => {
4536 if self
4537 .datagrams
4538 .received(datagram, &self.config.datagram_receive_buffer_size)?
4539 {
4540 self.events.push_back(Event::DatagramReceived);
4541 }
4542 }
4543 Frame::AckFrequency(ack_frequency) => {
4544 if !self.ack_frequency.ack_frequency_received(&ack_frequency)? {
4547 continue;
4550 }
4551
4552 for (path_id, space) in self.spaces[SpaceId::Data].number_spaces.iter_mut() {
4554 space.pending_acks.set_ack_frequency_params(&ack_frequency);
4555
4556 if let Some(timeout) = space
4559 .pending_acks
4560 .max_ack_delay_timeout(self.ack_frequency.max_ack_delay)
4561 {
4562 self.timers.set(
4563 Timer::PerPath(*path_id, PathTimer::MaxAckDelay),
4564 timeout,
4565 self.qlog.with_time(now),
4566 );
4567 }
4568 }
4569 }
4570 Frame::ImmediateAck => {
4571 for pns in self.spaces[SpaceId::Data].iter_paths_mut() {
4573 pns.pending_acks.set_immediate_ack_required();
4574 }
4575 }
4576 Frame::HandshakeDone => {
4577 if self.side.is_server() {
4578 return Err(TransportError::PROTOCOL_VIOLATION(
4579 "client sent HANDSHAKE_DONE",
4580 ));
4581 }
4582 if self.spaces[SpaceId::Handshake].crypto.is_some() {
4583 self.discard_space(now, SpaceId::Handshake);
4584 }
4585 self.events.push_back(Event::HandshakeConfirmed);
4586 trace!("handshake confirmed");
4587 }
4588 Frame::ObservedAddr(observed) => {
4589 trace!(seq_no = %observed.seq_no, ip = %observed.ip, port = observed.port);
4591 if !self
4592 .peer_params
4593 .address_discovery_role
4594 .should_report(&self.config.address_discovery_role)
4595 {
4596 return Err(TransportError::PROTOCOL_VIOLATION(
4597 "received OBSERVED_ADDRESS frame when not negotiated",
4598 ));
4599 }
4600 if packet.header.space() != SpaceId::Data {
4602 return Err(TransportError::PROTOCOL_VIOLATION(
4603 "OBSERVED_ADDRESS frame outside data space",
4604 ));
4605 }
4606
4607 let path = self.path_data_mut(path_id);
4608 if remote == path.remote {
4609 if let Some(updated) = path.update_observed_addr_report(observed) {
4610 if path.open {
4611 self.events.push_back(Event::Path(PathEvent::ObservedAddr {
4612 id: path_id,
4613 addr: updated,
4614 }));
4615 }
4616 }
4618 } else {
4619 migration_observed_addr = Some(observed)
4621 }
4622 }
4623 Frame::PathAbandon(frame::PathAbandon {
4624 path_id,
4625 error_code,
4626 }) => {
4627 span.record("path", tracing::field::debug(&path_id));
4628 let already_abandoned = match self.close_path(now, path_id, error_code.into()) {
4630 Ok(()) => {
4631 trace!("peer abandoned path");
4632 false
4633 }
4634 Err(ClosePathError::LastOpenPath) => {
4635 trace!("peer abandoned last path, closing connection");
4636 return Err(TransportError::NO_ERROR("last path abandoned by peer"));
4638 }
4639 Err(ClosePathError::ClosedPath) => {
4640 trace!("peer abandoned already closed path");
4641 true
4642 }
4643 };
4644 if self.path(path_id).is_some() && !already_abandoned {
4649 let delay = self.pto(SpaceId::Data, path_id) * 3;
4654 self.timers.set(
4655 Timer::PerPath(path_id, PathTimer::DiscardPath),
4656 now + delay,
4657 self.qlog.with_time(now),
4658 );
4659 }
4660 }
4661 Frame::PathStatusAvailable(info) => {
4662 span.record("path", tracing::field::debug(&info.path_id));
4663 if self.is_multipath_negotiated() {
4664 self.on_path_status(
4665 info.path_id,
4666 PathStatus::Available,
4667 info.status_seq_no,
4668 );
4669 } else {
4670 return Err(TransportError::PROTOCOL_VIOLATION(
4671 "received PATH_STATUS_AVAILABLE frame when multipath was not negotiated",
4672 ));
4673 }
4674 }
4675 Frame::PathStatusBackup(info) => {
4676 span.record("path", tracing::field::debug(&info.path_id));
4677 if self.is_multipath_negotiated() {
4678 self.on_path_status(info.path_id, PathStatus::Backup, info.status_seq_no);
4679 } else {
4680 return Err(TransportError::PROTOCOL_VIOLATION(
4681 "received PATH_STATUS_BACKUP frame when multipath was not negotiated",
4682 ));
4683 }
4684 }
4685 Frame::MaxPathId(frame::MaxPathId(path_id)) => {
4686 span.record("path", tracing::field::debug(&path_id));
4687 if !self.is_multipath_negotiated() {
4688 return Err(TransportError::PROTOCOL_VIOLATION(
4689 "received MAX_PATH_ID frame when multipath was not negotiated",
4690 ));
4691 }
4692 if path_id > self.remote_max_path_id {
4694 self.remote_max_path_id = path_id;
4695 self.issue_first_path_cids(now);
4696 }
4697 }
4698 Frame::PathsBlocked(frame::PathsBlocked(max_path_id)) => {
4699 if self.is_multipath_negotiated() {
4703 if self.local_max_path_id > max_path_id {
4704 return Err(TransportError::PROTOCOL_VIOLATION(
4705 "PATHS_BLOCKED maximum path identifier was larger than local maximum",
4706 ));
4707 }
4708 debug!("received PATHS_BLOCKED({:?})", max_path_id);
4709 } else {
4711 return Err(TransportError::PROTOCOL_VIOLATION(
4712 "received PATHS_BLOCKED frame when not multipath was not negotiated",
4713 ));
4714 }
4715 }
4716 Frame::PathCidsBlocked(frame::PathCidsBlocked { path_id, next_seq }) => {
4717 if self.is_multipath_negotiated() {
4725 if path_id > self.local_max_path_id {
4726 return Err(TransportError::PROTOCOL_VIOLATION(
4727 "PATH_CIDS_BLOCKED path identifier was larger than local maximum",
4728 ));
4729 }
4730 if next_seq.0
4731 > self
4732 .local_cid_state
4733 .get(&path_id)
4734 .map(|cid_state| cid_state.active_seq().1 + 1)
4735 .unwrap_or_default()
4736 {
4737 return Err(TransportError::PROTOCOL_VIOLATION(
4738 "PATH_CIDS_BLOCKED next sequence number larger than in local state",
4739 ));
4740 }
4741 debug!(%path_id, %next_seq, "received PATH_CIDS_BLOCKED");
4742 } else {
4743 return Err(TransportError::PROTOCOL_VIOLATION(
4744 "received PATH_CIDS_BLOCKED frame when not multipath was not negotiated",
4745 ));
4746 }
4747 }
4748 Frame::AddAddress(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(ADD_ADDRESS): {err}"
4754 )));
4755 }
4756 };
4757
4758 if !client_state.check_remote_address(&addr) {
4759 warn!(?addr, "server sent illegal ADD_ADDRESS frame");
4761 }
4762
4763 match client_state.add_remote_address(addr) {
4764 Ok(maybe_added) => {
4765 if let Some(added) = maybe_added {
4766 self.events.push_back(Event::NatTraversal(
4767 iroh_hp::Event::AddressAdded(added),
4768 ));
4769 }
4770 }
4771 Err(e) => {
4772 warn!(%e, "failed to add remote address")
4773 }
4774 }
4775 }
4776 Frame::RemoveAddress(addr) => {
4777 let client_state = match self.iroh_hp.client_side_mut() {
4778 Ok(state) => state,
4779 Err(err) => {
4780 return Err(TransportError::PROTOCOL_VIOLATION(format!(
4781 "Nat traversal(REMOVE_ADDRESS): {err}"
4782 )));
4783 }
4784 };
4785 if let Some(removed_addr) = client_state.remove_remote_address(addr) {
4786 self.events
4787 .push_back(Event::NatTraversal(iroh_hp::Event::AddressRemoved(
4788 removed_addr,
4789 )));
4790 }
4791 }
4792 Frame::ReachOut(reach_out) => {
4793 let server_state = match self.iroh_hp.server_side_mut() {
4794 Ok(state) => state,
4795 Err(err) => {
4796 return Err(TransportError::PROTOCOL_VIOLATION(format!(
4797 "Nat traversal(REACH_OUT): {err}"
4798 )));
4799 }
4800 };
4801
4802 if let Err(err) = server_state.handle_reach_out(reach_out) {
4803 return Err(TransportError::PROTOCOL_VIOLATION(format!(
4804 "Nat traversal(REACH_OUT): {err}"
4805 )));
4806 }
4807 }
4808 }
4809 }
4810
4811 let space = self.spaces[SpaceId::Data].for_path(path_id);
4812 if space
4813 .pending_acks
4814 .packet_received(now, number, ack_eliciting, &space.dedup)
4815 {
4816 if self.abandoned_paths.contains(&path_id) {
4817 space.pending_acks.set_immediate_ack_required();
4820 } else {
4821 self.timers.set(
4822 Timer::PerPath(path_id, PathTimer::MaxAckDelay),
4823 now + self.ack_frequency.max_ack_delay,
4824 self.qlog.with_time(now),
4825 );
4826 }
4827 }
4828
4829 let pending = &mut self.spaces[SpaceId::Data].pending;
4834 self.streams.queue_max_stream_id(pending);
4835
4836 if let Some(reason) = close {
4837 self.state.move_to_draining(Some(reason.into()));
4838 self.close = true;
4839 }
4840
4841 if Some(number) == self.spaces[SpaceId::Data].for_path(path_id).rx_packet
4842 && !is_probing_packet
4843 && remote != self.path_data(path_id).remote
4844 {
4845 let ConnectionSide::Server { ref server_config } = self.side else {
4846 panic!("packets from unknown remote should be dropped by clients");
4847 };
4848 debug_assert!(
4849 server_config.migration,
4850 "migration-initiating packets should have been dropped immediately"
4851 );
4852 self.migrate(path_id, now, remote, migration_observed_addr);
4853 self.update_rem_cid(path_id);
4855 self.spin = false;
4856 }
4857
4858 Ok(())
4859 }
4860
4861 fn migrate(
4862 &mut self,
4863 path_id: PathId,
4864 now: Instant,
4865 remote: SocketAddr,
4866 observed_addr: Option<ObservedAddr>,
4867 ) {
4868 trace!(%remote, %path_id, "migration initiated");
4869 self.path_counter = self.path_counter.wrapping_add(1);
4870 let prev_pto = self.pto(SpaceId::Data, path_id);
4877 let known_path = self.paths.get_mut(&path_id).expect("known path");
4878 let path = &mut known_path.data;
4879 let mut new_path = if remote.is_ipv4() && remote.ip() == path.remote.ip() {
4880 PathData::from_previous(remote, path, self.path_counter, now)
4881 } else {
4882 let peer_max_udp_payload_size =
4883 u16::try_from(self.peer_params.max_udp_payload_size.into_inner())
4884 .unwrap_or(u16::MAX);
4885 PathData::new(
4886 remote,
4887 self.allow_mtud,
4888 Some(peer_max_udp_payload_size),
4889 self.path_counter,
4890 now,
4891 &self.config,
4892 )
4893 };
4894 new_path.last_observed_addr_report = path.last_observed_addr_report.clone();
4895 if let Some(report) = observed_addr {
4896 if let Some(updated) = new_path.update_observed_addr_report(report) {
4897 tracing::info!("adding observed addr event from migration");
4898 self.events.push_back(Event::Path(PathEvent::ObservedAddr {
4899 id: path_id,
4900 addr: updated,
4901 }));
4902 }
4903 }
4904 new_path.send_new_challenge = true;
4905
4906 let mut prev = mem::replace(path, new_path);
4907 if !prev.is_validating_path() {
4909 prev.send_new_challenge = true;
4910 known_path.prev = Some((self.rem_cids.get(&path_id).unwrap().active(), prev));
4914 }
4915
4916 self.qlog.emit_tuple_assigned(path_id, remote, now);
4918
4919 self.timers.set(
4920 Timer::PerPath(path_id, PathTimer::PathValidation),
4921 now + 3 * cmp::max(self.pto(SpaceId::Data, path_id), prev_pto),
4922 self.qlog.with_time(now),
4923 );
4924 }
4925
4926 pub fn local_address_changed(&mut self) {
4928 self.update_rem_cid(PathId::ZERO);
4930 self.ping();
4931 }
4932
4933 fn update_rem_cid(&mut self, path_id: PathId) {
4935 let Some((reset_token, retired)) =
4936 self.rem_cids.get_mut(&path_id).and_then(|cids| cids.next())
4937 else {
4938 return;
4939 };
4940
4941 self.spaces[SpaceId::Data]
4943 .pending
4944 .retire_cids
4945 .extend(retired.map(|seq| (path_id, seq)));
4946 let remote = self.path_data(path_id).remote;
4947 self.set_reset_token(path_id, remote, reset_token);
4948 }
4949
4950 fn set_reset_token(&mut self, path_id: PathId, remote: SocketAddr, reset_token: ResetToken) {
4959 self.endpoint_events
4960 .push_back(EndpointEventInner::ResetToken(path_id, remote, reset_token));
4961
4962 if path_id == PathId::ZERO {
4968 self.peer_params.stateless_reset_token = Some(reset_token);
4969 }
4970 }
4971
4972 fn issue_first_cids(&mut self, now: Instant) {
4974 if self
4975 .local_cid_state
4976 .get(&PathId::ZERO)
4977 .expect("PathId::ZERO exists when the connection is created")
4978 .cid_len()
4979 == 0
4980 {
4981 return;
4982 }
4983
4984 let mut n = self.peer_params.issue_cids_limit() - 1;
4986 if let ConnectionSide::Server { server_config } = &self.side {
4987 if server_config.has_preferred_address() {
4988 n -= 1;
4990 }
4991 }
4992 self.endpoint_events
4993 .push_back(EndpointEventInner::NeedIdentifiers(PathId::ZERO, now, n));
4994 }
4995
4996 fn issue_first_path_cids(&mut self, now: Instant) {
5000 if let Some(max_path_id) = self.max_path_id() {
5001 let mut path_id = self.max_path_id_with_cids.next();
5002 while path_id <= max_path_id {
5003 self.endpoint_events
5004 .push_back(EndpointEventInner::NeedIdentifiers(
5005 path_id,
5006 now,
5007 self.peer_params.issue_cids_limit(),
5008 ));
5009 path_id = path_id.next();
5010 }
5011 self.max_path_id_with_cids = max_path_id;
5012 }
5013 }
5014
5015 fn populate_packet(
5023 &mut self,
5024 now: Instant,
5025 space_id: SpaceId,
5026 path_id: PathId,
5027 path_exclusive_only: bool,
5028 buf: &mut impl BufMut,
5029 pn: u64,
5030 #[allow(unused)] qlog: &mut QlogSentPacket,
5031 ) -> SentFrames {
5032 let mut sent = SentFrames::default();
5033 let is_multipath_negotiated = self.is_multipath_negotiated();
5034 let space = &mut self.spaces[space_id];
5035 let path = &mut self.paths.get_mut(&path_id).expect("known path").data;
5036 let is_0rtt = space_id == SpaceId::Data && space.crypto.is_none();
5037 space
5038 .for_path(path_id)
5039 .pending_acks
5040 .maybe_ack_non_eliciting();
5041
5042 if !is_0rtt && mem::replace(&mut space.pending.handshake_done, false) {
5044 trace!("HANDSHAKE_DONE");
5045 buf.write(frame::FrameType::HANDSHAKE_DONE);
5046 qlog.frame(&Frame::HandshakeDone);
5047 sent.retransmits.get_or_create().handshake_done = true;
5048 self.stats.frame_tx.handshake_done =
5050 self.stats.frame_tx.handshake_done.saturating_add(1);
5051 }
5052
5053 if let Some((round, addresses)) = space.pending.reach_out.as_mut() {
5056 while let Some(local_addr) = addresses.pop() {
5057 let reach_out = frame::ReachOut::new(*round, local_addr);
5058 if buf.remaining_mut() > reach_out.size() {
5059 trace!(%round, ?local_addr, "REACH_OUT");
5060 reach_out.write(buf);
5061 let sent_reachouts = sent
5062 .retransmits
5063 .get_or_create()
5064 .reach_out
5065 .get_or_insert_with(|| (*round, Default::default()));
5066 sent_reachouts.1.push(local_addr);
5067 self.stats.frame_tx.reach_out = self.stats.frame_tx.reach_out.saturating_add(1);
5068 qlog.frame(&Frame::ReachOut(reach_out));
5069 } else {
5070 addresses.push(local_addr);
5071 break;
5072 }
5073 }
5074 if addresses.is_empty() {
5075 space.pending.reach_out = None;
5076 }
5077 }
5078
5079 if !path_exclusive_only
5081 && space_id == SpaceId::Data
5082 && self
5083 .config
5084 .address_discovery_role
5085 .should_report(&self.peer_params.address_discovery_role)
5086 && (!path.observed_addr_sent || space.pending.observed_addr)
5087 {
5088 let frame = frame::ObservedAddr::new(path.remote, self.next_observed_addr_seq_no);
5089 if buf.remaining_mut() > frame.size() {
5090 trace!(seq = %frame.seq_no, ip = %frame.ip, port = frame.port, "OBSERVED_ADDRESS");
5091 frame.write(buf);
5092
5093 self.next_observed_addr_seq_no = self.next_observed_addr_seq_no.saturating_add(1u8);
5094 path.observed_addr_sent = true;
5095
5096 self.stats.frame_tx.observed_addr += 1;
5097 sent.retransmits.get_or_create().observed_addr = true;
5098 space.pending.observed_addr = false;
5099 qlog.frame(&Frame::ObservedAddr(frame));
5100 }
5101 }
5102
5103 if mem::replace(&mut space.for_path(path_id).ping_pending, false) {
5105 trace!("PING");
5106 buf.write(frame::FrameType::PING);
5107 sent.non_retransmits = true;
5108 self.stats.frame_tx.ping += 1;
5109 qlog.frame(&Frame::Ping);
5110 }
5111
5112 if mem::replace(&mut space.for_path(path_id).immediate_ack_pending, false) {
5114 debug_assert_eq!(
5115 space_id,
5116 SpaceId::Data,
5117 "immediate acks must be sent in the data space"
5118 );
5119 trace!("IMMEDIATE_ACK");
5120 buf.write(frame::FrameType::IMMEDIATE_ACK);
5121 sent.non_retransmits = true;
5122 self.stats.frame_tx.immediate_ack += 1;
5123 qlog.frame(&Frame::ImmediateAck);
5124 }
5125
5126 if !path_exclusive_only {
5130 for path_id in space
5131 .number_spaces
5132 .iter_mut()
5133 .filter(|(_, pns)| pns.pending_acks.can_send())
5134 .map(|(&path_id, _)| path_id)
5135 .collect::<Vec<_>>()
5136 {
5137 Self::populate_acks(
5138 now,
5139 self.receiving_ecn,
5140 &mut sent,
5141 path_id,
5142 space_id,
5143 space,
5144 is_multipath_negotiated,
5145 buf,
5146 &mut self.stats,
5147 qlog,
5148 );
5149 }
5150 }
5151
5152 if !path_exclusive_only && mem::replace(&mut space.pending.ack_frequency, false) {
5154 let sequence_number = self.ack_frequency.next_sequence_number();
5155
5156 let config = self.config.ack_frequency_config.as_ref().unwrap();
5158
5159 let max_ack_delay = self.ack_frequency.candidate_max_ack_delay(
5161 path.rtt.get(),
5162 config,
5163 &self.peer_params,
5164 );
5165
5166 trace!(?max_ack_delay, "ACK_FREQUENCY");
5167
5168 let frame = frame::AckFrequency {
5169 sequence: sequence_number,
5170 ack_eliciting_threshold: config.ack_eliciting_threshold,
5171 request_max_ack_delay: max_ack_delay.as_micros().try_into().unwrap_or(VarInt::MAX),
5172 reordering_threshold: config.reordering_threshold,
5173 };
5174 frame.encode(buf);
5175 qlog.frame(&Frame::AckFrequency(frame));
5176
5177 sent.retransmits.get_or_create().ack_frequency = true;
5178
5179 self.ack_frequency
5180 .ack_frequency_sent(path_id, pn, max_ack_delay);
5181 self.stats.frame_tx.ack_frequency += 1;
5182 }
5183
5184 if buf.remaining_mut() > frame::PathChallenge::SIZE_BOUND
5186 && space_id == SpaceId::Data
5187 && path.send_new_challenge
5188 && !self.state.is_closed()
5189 {
5191 path.send_new_challenge = false;
5192
5193 let token = self.rng.random();
5195 let info = paths::SentChallengeInfo {
5196 sent_instant: now,
5197 remote: path.remote,
5198 };
5199 path.challenges_sent.insert(token, info);
5200 sent.non_retransmits = true;
5201 sent.requires_padding = true;
5202 let challenge = frame::PathChallenge(token);
5203 trace!(%challenge, "sending new challenge");
5204 buf.write(challenge);
5205 qlog.frame(&Frame::PathChallenge(challenge));
5206 self.stats.frame_tx.path_challenge += 1;
5207 let pto = self.ack_frequency.max_ack_delay_for_pto() + path.rtt.pto_base();
5208 self.timers.set(
5209 Timer::PerPath(path_id, PathTimer::PathChallengeLost),
5210 now + pto,
5211 self.qlog.with_time(now),
5212 );
5213
5214 if is_multipath_negotiated && !path.validated && path.send_new_challenge {
5215 space.pending.path_status.insert(path_id);
5217 }
5218
5219 if space_id == SpaceId::Data
5222 && self
5223 .config
5224 .address_discovery_role
5225 .should_report(&self.peer_params.address_discovery_role)
5226 {
5227 let frame = frame::ObservedAddr::new(path.remote, self.next_observed_addr_seq_no);
5228 if buf.remaining_mut() > frame.size() {
5229 frame.write(buf);
5230 qlog.frame(&Frame::ObservedAddr(frame));
5231
5232 self.next_observed_addr_seq_no =
5233 self.next_observed_addr_seq_no.saturating_add(1u8);
5234 path.observed_addr_sent = true;
5235
5236 self.stats.frame_tx.observed_addr += 1;
5237 sent.retransmits.get_or_create().observed_addr = true;
5238 space.pending.observed_addr = false;
5239 }
5240 }
5241 }
5242
5243 if buf.remaining_mut() > frame::PathResponse::SIZE_BOUND && space_id == SpaceId::Data {
5245 if let Some(token) = path.path_responses.pop_on_path(path.remote) {
5246 sent.non_retransmits = true;
5247 sent.requires_padding = true;
5248 let response = frame::PathResponse(token);
5249 trace!(%response, "sending response");
5250 buf.write(response);
5251 qlog.frame(&Frame::PathResponse(response));
5252 self.stats.frame_tx.path_response += 1;
5253
5254 if space_id == SpaceId::Data
5258 && self
5259 .config
5260 .address_discovery_role
5261 .should_report(&self.peer_params.address_discovery_role)
5262 {
5263 let frame =
5264 frame::ObservedAddr::new(path.remote, self.next_observed_addr_seq_no);
5265 if buf.remaining_mut() > frame.size() {
5266 frame.write(buf);
5267 qlog.frame(&Frame::ObservedAddr(frame));
5268
5269 self.next_observed_addr_seq_no =
5270 self.next_observed_addr_seq_no.saturating_add(1u8);
5271 path.observed_addr_sent = true;
5272
5273 self.stats.frame_tx.observed_addr += 1;
5274 sent.retransmits.get_or_create().observed_addr = true;
5275 space.pending.observed_addr = false;
5276 }
5277 }
5278 }
5279 }
5280
5281 while !path_exclusive_only && buf.remaining_mut() > frame::Crypto::SIZE_BOUND && !is_0rtt {
5283 let mut frame = match space.pending.crypto.pop_front() {
5284 Some(x) => x,
5285 None => break,
5286 };
5287
5288 let max_crypto_data_size = buf.remaining_mut()
5293 - 1 - VarInt::size(unsafe { VarInt::from_u64_unchecked(frame.offset) })
5295 - 2; let len = frame
5298 .data
5299 .len()
5300 .min(2usize.pow(14) - 1)
5301 .min(max_crypto_data_size);
5302
5303 let data = frame.data.split_to(len);
5304 let truncated = frame::Crypto {
5305 offset: frame.offset,
5306 data,
5307 };
5308 trace!(
5309 "CRYPTO: off {} len {}",
5310 truncated.offset,
5311 truncated.data.len()
5312 );
5313 truncated.encode(buf);
5314 self.stats.frame_tx.crypto += 1;
5315
5316 #[cfg(feature = "qlog")]
5318 qlog.frame(&Frame::Crypto(truncated.clone()));
5319 sent.retransmits.get_or_create().crypto.push_back(truncated);
5320 if !frame.data.is_empty() {
5321 frame.offset += len as u64;
5322 space.pending.crypto.push_front(frame);
5323 }
5324 }
5325
5326 while !path_exclusive_only
5329 && space_id == SpaceId::Data
5330 && frame::PathAbandon::SIZE_BOUND <= buf.remaining_mut()
5331 {
5332 let Some((path_id, error_code)) = space.pending.path_abandon.pop_first() else {
5333 break;
5334 };
5335 let frame = frame::PathAbandon {
5336 path_id,
5337 error_code,
5338 };
5339 frame.encode(buf);
5340 qlog.frame(&Frame::PathAbandon(frame));
5341 self.stats.frame_tx.path_abandon += 1;
5342 trace!(%path_id, "PATH_ABANDON");
5343 sent.retransmits
5344 .get_or_create()
5345 .path_abandon
5346 .entry(path_id)
5347 .or_insert(error_code);
5348 }
5349
5350 while !path_exclusive_only
5352 && space_id == SpaceId::Data
5353 && frame::PathStatusAvailable::SIZE_BOUND <= buf.remaining_mut()
5354 {
5355 let Some(path_id) = space.pending.path_status.pop_first() else {
5356 break;
5357 };
5358 let Some(path) = self.paths.get(&path_id).map(|path_state| &path_state.data) else {
5359 trace!(%path_id, "discarding queued path status for unknown path");
5360 continue;
5361 };
5362
5363 let seq = path.status.seq();
5364 sent.retransmits.get_or_create().path_status.insert(path_id);
5365 match path.local_status() {
5366 PathStatus::Available => {
5367 let frame = frame::PathStatusAvailable {
5368 path_id,
5369 status_seq_no: seq,
5370 };
5371 frame.encode(buf);
5372 qlog.frame(&Frame::PathStatusAvailable(frame));
5373 self.stats.frame_tx.path_status_available += 1;
5374 trace!(%path_id, %seq, "PATH_STATUS_AVAILABLE")
5375 }
5376 PathStatus::Backup => {
5377 let frame = frame::PathStatusBackup {
5378 path_id,
5379 status_seq_no: seq,
5380 };
5381 frame.encode(buf);
5382 qlog.frame(&Frame::PathStatusBackup(frame));
5383 self.stats.frame_tx.path_status_backup += 1;
5384 trace!(%path_id, %seq, "PATH_STATUS_BACKUP")
5385 }
5386 }
5387 }
5388
5389 if space_id == SpaceId::Data
5391 && space.pending.max_path_id
5392 && frame::MaxPathId::SIZE_BOUND <= buf.remaining_mut()
5393 {
5394 let frame = frame::MaxPathId(self.local_max_path_id);
5395 frame.encode(buf);
5396 qlog.frame(&Frame::MaxPathId(frame));
5397 space.pending.max_path_id = false;
5398 sent.retransmits.get_or_create().max_path_id = true;
5399 trace!(val = %self.local_max_path_id, "MAX_PATH_ID");
5400 self.stats.frame_tx.max_path_id += 1;
5401 }
5402
5403 if space_id == SpaceId::Data
5405 && space.pending.paths_blocked
5406 && frame::PathsBlocked::SIZE_BOUND <= buf.remaining_mut()
5407 {
5408 let frame = frame::PathsBlocked(self.remote_max_path_id);
5409 frame.encode(buf);
5410 qlog.frame(&Frame::PathsBlocked(frame));
5411 space.pending.paths_blocked = false;
5412 sent.retransmits.get_or_create().paths_blocked = true;
5413 trace!(max_path_id = ?self.remote_max_path_id, "PATHS_BLOCKED");
5414 self.stats.frame_tx.paths_blocked += 1;
5415 }
5416
5417 while space_id == SpaceId::Data && frame::PathCidsBlocked::SIZE_BOUND <= buf.remaining_mut()
5419 {
5420 let Some(path_id) = space.pending.path_cids_blocked.pop() else {
5421 break;
5422 };
5423 let next_seq = match self.rem_cids.get(&path_id) {
5424 Some(cid_queue) => cid_queue.active_seq() + 1,
5425 None => 0,
5426 };
5427 let frame = frame::PathCidsBlocked {
5428 path_id,
5429 next_seq: VarInt(next_seq),
5430 };
5431 frame.encode(buf);
5432 qlog.frame(&Frame::PathCidsBlocked(frame));
5433 sent.retransmits
5434 .get_or_create()
5435 .path_cids_blocked
5436 .push(path_id);
5437 trace!(%path_id, next_seq, "PATH_CIDS_BLOCKED");
5438 self.stats.frame_tx.path_cids_blocked += 1;
5439 }
5440
5441 if space_id == SpaceId::Data {
5443 self.streams.write_control_frames(
5444 buf,
5445 &mut space.pending,
5446 &mut sent.retransmits,
5447 &mut self.stats.frame_tx,
5448 qlog,
5449 );
5450 }
5451
5452 let cid_len = self
5454 .local_cid_state
5455 .values()
5456 .map(|cid_state| cid_state.cid_len())
5457 .max()
5458 .expect("some local CID state must exist");
5459 let new_cid_size_bound =
5460 frame::NewConnectionId::size_bound(is_multipath_negotiated, cid_len);
5461 while !path_exclusive_only && buf.remaining_mut() > new_cid_size_bound {
5462 let issued = match space.pending.new_cids.pop() {
5463 Some(x) => x,
5464 None => break,
5465 };
5466 let retire_prior_to = self
5467 .local_cid_state
5468 .get(&issued.path_id)
5469 .map(|cid_state| cid_state.retire_prior_to())
5470 .unwrap_or_else(|| panic!("missing local CID state for path={}", issued.path_id));
5471
5472 let cid_path_id = match is_multipath_negotiated {
5473 true => {
5474 trace!(
5475 path_id = ?issued.path_id,
5476 sequence = issued.sequence,
5477 id = %issued.id,
5478 "PATH_NEW_CONNECTION_ID",
5479 );
5480 self.stats.frame_tx.path_new_connection_id += 1;
5481 Some(issued.path_id)
5482 }
5483 false => {
5484 trace!(
5485 sequence = issued.sequence,
5486 id = %issued.id,
5487 "NEW_CONNECTION_ID"
5488 );
5489 debug_assert_eq!(issued.path_id, PathId::ZERO);
5490 self.stats.frame_tx.new_connection_id += 1;
5491 None
5492 }
5493 };
5494 let frame = frame::NewConnectionId {
5495 path_id: cid_path_id,
5496 sequence: issued.sequence,
5497 retire_prior_to,
5498 id: issued.id,
5499 reset_token: issued.reset_token,
5500 };
5501 frame.encode(buf);
5502 sent.retransmits.get_or_create().new_cids.push(issued);
5503 qlog.frame(&Frame::NewConnectionId(frame));
5504 }
5505
5506 let retire_cid_bound = frame::RetireConnectionId::size_bound(is_multipath_negotiated);
5508 while !path_exclusive_only && buf.remaining_mut() > retire_cid_bound {
5509 let (path_id, sequence) = match space.pending.retire_cids.pop() {
5510 Some((PathId::ZERO, seq)) if !is_multipath_negotiated => {
5511 trace!(sequence = seq, "RETIRE_CONNECTION_ID");
5512 self.stats.frame_tx.retire_connection_id += 1;
5513 (None, seq)
5514 }
5515 Some((path_id, seq)) => {
5516 trace!(%path_id, sequence = seq, "PATH_RETIRE_CONNECTION_ID");
5517 self.stats.frame_tx.path_retire_connection_id += 1;
5518 (Some(path_id), seq)
5519 }
5520 None => break,
5521 };
5522 let frame = frame::RetireConnectionId { path_id, sequence };
5523 frame.encode(buf);
5524 qlog.frame(&Frame::RetireConnectionId(frame));
5525 sent.retransmits
5526 .get_or_create()
5527 .retire_cids
5528 .push((path_id.unwrap_or_default(), sequence));
5529 }
5530
5531 let mut sent_datagrams = false;
5533 while !path_exclusive_only
5534 && buf.remaining_mut() > Datagram::SIZE_BOUND
5535 && space_id == SpaceId::Data
5536 {
5537 let prev_remaining = buf.remaining_mut();
5538 match self.datagrams.write(buf) {
5539 true => {
5540 sent_datagrams = true;
5541 sent.non_retransmits = true;
5542 self.stats.frame_tx.datagram += 1;
5543 qlog.frame_datagram((prev_remaining - buf.remaining_mut()) as u64);
5544 }
5545 false => break,
5546 }
5547 }
5548 if self.datagrams.send_blocked && sent_datagrams {
5549 self.events.push_back(Event::DatagramsUnblocked);
5550 self.datagrams.send_blocked = false;
5551 }
5552
5553 let path = &mut self.paths.get_mut(&path_id).expect("known path").data;
5554
5555 while let Some(remote_addr) = space.pending.new_tokens.pop() {
5557 if path_exclusive_only {
5558 break;
5559 }
5560 debug_assert_eq!(space_id, SpaceId::Data);
5561 let ConnectionSide::Server { server_config } = &self.side else {
5562 panic!("NEW_TOKEN frames should not be enqueued by clients");
5563 };
5564
5565 if remote_addr != path.remote {
5566 continue;
5571 }
5572
5573 let token = Token::new(
5574 TokenPayload::Validation {
5575 ip: remote_addr.ip(),
5576 issued: server_config.time_source.now(),
5577 },
5578 &mut self.rng,
5579 );
5580 let new_token = NewToken {
5581 token: token.encode(&*server_config.token_key).into(),
5582 };
5583
5584 if buf.remaining_mut() < new_token.size() {
5585 space.pending.new_tokens.push(remote_addr);
5586 break;
5587 }
5588
5589 trace!("NEW_TOKEN");
5590 new_token.encode(buf);
5591 qlog.frame(&Frame::NewToken(new_token));
5592 sent.retransmits
5593 .get_or_create()
5594 .new_tokens
5595 .push(remote_addr);
5596 self.stats.frame_tx.new_token += 1;
5597 }
5598
5599 if !path_exclusive_only && space_id == SpaceId::Data {
5601 sent.stream_frames =
5602 self.streams
5603 .write_stream_frames(buf, self.config.send_fairness, qlog);
5604 self.stats.frame_tx.stream += sent.stream_frames.len() as u64;
5605 }
5606
5607 while space_id == SpaceId::Data && frame::AddAddress::SIZE_BOUND <= buf.remaining_mut() {
5610 if let Some(added_address) = space.pending.add_address.pop_last() {
5611 trace!(
5612 seq = %added_address.seq_no,
5613 ip = ?added_address.ip,
5614 port = added_address.port,
5615 "ADD_ADDRESS",
5616 );
5617 added_address.write(buf);
5618 sent.retransmits
5619 .get_or_create()
5620 .add_address
5621 .insert(added_address);
5622 self.stats.frame_tx.add_address = self.stats.frame_tx.add_address.saturating_add(1);
5623 qlog.frame(&Frame::AddAddress(added_address));
5624 } else {
5625 break;
5626 }
5627 }
5628
5629 while space_id == SpaceId::Data && frame::RemoveAddress::SIZE_BOUND <= buf.remaining_mut() {
5631 if let Some(removed_address) = space.pending.remove_address.pop_last() {
5632 trace!(seq = %removed_address.seq_no, "REMOVE_ADDRESS");
5633 removed_address.write(buf);
5634 sent.retransmits
5635 .get_or_create()
5636 .remove_address
5637 .insert(removed_address);
5638 self.stats.frame_tx.remove_address =
5639 self.stats.frame_tx.remove_address.saturating_add(1);
5640 qlog.frame(&Frame::RemoveAddress(removed_address));
5641 } else {
5642 break;
5643 }
5644 }
5645
5646 sent
5647 }
5648
5649 fn populate_acks(
5651 now: Instant,
5652 receiving_ecn: bool,
5653 sent: &mut SentFrames,
5654 path_id: PathId,
5655 space_id: SpaceId,
5656 space: &mut PacketSpace,
5657 is_multipath_negotiated: bool,
5658 buf: &mut impl BufMut,
5659 stats: &mut ConnectionStats,
5660 #[allow(unused)] qlog: &mut QlogSentPacket,
5661 ) {
5662 debug_assert!(space.crypto.is_some(), "tried to send ACK in 0-RTT");
5664
5665 debug_assert!(
5666 is_multipath_negotiated || path_id == PathId::ZERO,
5667 "Only PathId::ZERO allowed without multipath (have {path_id:?})"
5668 );
5669 if is_multipath_negotiated {
5670 debug_assert!(
5671 space_id == SpaceId::Data || path_id == PathId::ZERO,
5672 "path acks must be sent in 1RTT space (have {space_id:?})"
5673 );
5674 }
5675
5676 let pns = space.for_path(path_id);
5677 let ranges = pns.pending_acks.ranges();
5678 debug_assert!(!ranges.is_empty(), "can not send empty ACK range");
5679 let ecn = if receiving_ecn {
5680 Some(&pns.ecn_counters)
5681 } else {
5682 None
5683 };
5684 if let Some(max) = ranges.max() {
5685 sent.largest_acked.insert(path_id, max);
5686 }
5687
5688 let delay_micros = pns.pending_acks.ack_delay(now).as_micros() as u64;
5689 let ack_delay_exp = TransportParameters::default().ack_delay_exponent;
5691 let delay = delay_micros >> ack_delay_exp.into_inner();
5692
5693 if is_multipath_negotiated && space_id == SpaceId::Data {
5694 if !ranges.is_empty() {
5695 trace!("PATH_ACK {path_id:?} {ranges:?}, Delay = {delay_micros}us");
5696 frame::PathAck::encode(path_id, delay as _, ranges, ecn, buf);
5697 qlog.frame_path_ack(path_id, delay as _, ranges, ecn);
5698 stats.frame_tx.path_acks += 1;
5699 }
5700 } else {
5701 trace!("ACK {ranges:?}, Delay = {delay_micros}us");
5702 frame::Ack::encode(delay as _, ranges, ecn, buf);
5703 stats.frame_tx.acks += 1;
5704 qlog.frame_ack(delay, ranges, ecn);
5705 }
5706 }
5707
5708 fn close_common(&mut self) {
5709 trace!("connection closed");
5710 self.timers.reset();
5711 }
5712
5713 fn set_close_timer(&mut self, now: Instant) {
5714 let pto_max = self.pto_max_path(self.highest_space, true);
5717 self.timers.set(
5718 Timer::Conn(ConnTimer::Close),
5719 now + 3 * pto_max,
5720 self.qlog.with_time(now),
5721 );
5722 }
5723
5724 fn handle_peer_params(
5729 &mut self,
5730 params: TransportParameters,
5731 loc_cid: ConnectionId,
5732 rem_cid: ConnectionId,
5733 now: Instant,
5734 ) -> Result<(), TransportError> {
5735 if Some(self.orig_rem_cid) != params.initial_src_cid
5736 || (self.side.is_client()
5737 && (Some(self.initial_dst_cid) != params.original_dst_cid
5738 || self.retry_src_cid != params.retry_src_cid))
5739 {
5740 return Err(TransportError::TRANSPORT_PARAMETER_ERROR(
5741 "CID authentication failure",
5742 ));
5743 }
5744 if params.initial_max_path_id.is_some() && (loc_cid.is_empty() || rem_cid.is_empty()) {
5745 return Err(TransportError::PROTOCOL_VIOLATION(
5746 "multipath must not use zero-length CIDs",
5747 ));
5748 }
5749
5750 self.set_peer_params(params);
5751 self.qlog.emit_peer_transport_params_received(self, now);
5752
5753 Ok(())
5754 }
5755
5756 fn set_peer_params(&mut self, params: TransportParameters) {
5757 self.streams.set_params(¶ms);
5758 self.idle_timeout =
5759 negotiate_max_idle_timeout(self.config.max_idle_timeout, Some(params.max_idle_timeout));
5760 trace!("negotiated max idle timeout {:?}", self.idle_timeout);
5761
5762 if let Some(ref info) = params.preferred_address {
5763 self.rem_cids.get_mut(&PathId::ZERO).expect("not yet abandoned").insert(frame::NewConnectionId {
5765 path_id: None,
5766 sequence: 1,
5767 id: info.connection_id,
5768 reset_token: info.stateless_reset_token,
5769 retire_prior_to: 0,
5770 })
5771 .expect(
5772 "preferred address CID is the first received, and hence is guaranteed to be legal",
5773 );
5774 let remote = self.path_data(PathId::ZERO).remote;
5775 self.set_reset_token(PathId::ZERO, remote, info.stateless_reset_token);
5776 }
5777 self.ack_frequency.peer_max_ack_delay = get_max_ack_delay(¶ms);
5778
5779 let mut multipath_enabled = None;
5780 if let (Some(local_max_path_id), Some(remote_max_path_id)) = (
5781 self.config.get_initial_max_path_id(),
5782 params.initial_max_path_id,
5783 ) {
5784 self.local_max_path_id = local_max_path_id;
5786 self.remote_max_path_id = remote_max_path_id;
5787 let initial_max_path_id = local_max_path_id.min(remote_max_path_id);
5788 debug!(%initial_max_path_id, "multipath negotiated");
5789 multipath_enabled = Some(initial_max_path_id);
5790 }
5791
5792 if let Some((max_locally_allowed_remote_addresses, max_remotely_allowed_remote_addresses)) =
5793 self.config
5794 .max_remote_nat_traversal_addresses
5795 .zip(params.max_remote_nat_traversal_addresses)
5796 {
5797 if let Some(max_initial_paths) =
5798 multipath_enabled.map(|path_id| path_id.saturating_add(1u8))
5799 {
5800 let max_local_addresses = max_remotely_allowed_remote_addresses.get();
5801 let max_remote_addresses = max_locally_allowed_remote_addresses.get();
5802 self.iroh_hp =
5803 iroh_hp::State::new(max_remote_addresses, max_local_addresses, self.side());
5804 debug!(
5805 %max_remote_addresses, %max_local_addresses,
5806 "iroh hole punching negotiated"
5807 );
5808
5809 match self.side() {
5810 Side::Client => {
5811 if max_initial_paths.as_u32() < max_remote_addresses as u32 + 1 {
5812 warn!(%max_initial_paths, %max_remote_addresses, "local client configuration might cause nat traversal issues")
5815 } else if max_local_addresses as u64
5816 > params.active_connection_id_limit.into_inner()
5817 {
5818 warn!(%max_local_addresses, remote_cid_limit=%params.active_connection_id_limit.into_inner(), "remote server configuration might cause nat traversal issues")
5822 }
5823 }
5824 Side::Server => {
5825 if (max_initial_paths.as_u32() as u64) < crate::LOC_CID_COUNT {
5826 warn!(%max_initial_paths, local_cid_limit=%crate::LOC_CID_COUNT, "local server configuration might cause nat traversal issues")
5827 }
5828 }
5829 }
5830 } else {
5831 debug!("iroh nat traversal enabled for both endpoints, but multipath is missing")
5832 }
5833 }
5834
5835 self.peer_params = params;
5836 let peer_max_udp_payload_size =
5837 u16::try_from(self.peer_params.max_udp_payload_size.into_inner()).unwrap_or(u16::MAX);
5838 self.path_data_mut(PathId::ZERO)
5839 .mtud
5840 .on_peer_max_udp_payload_size_received(peer_max_udp_payload_size);
5841 }
5842
5843 fn decrypt_packet(
5845 &mut self,
5846 now: Instant,
5847 path_id: PathId,
5848 packet: &mut Packet,
5849 ) -> Result<Option<u64>, Option<TransportError>> {
5850 let result = packet_crypto::decrypt_packet_body(
5851 packet,
5852 path_id,
5853 &self.spaces,
5854 self.zero_rtt_crypto.as_ref(),
5855 self.key_phase,
5856 self.prev_crypto.as_ref(),
5857 self.next_crypto.as_ref(),
5858 )?;
5859
5860 let result = match result {
5861 Some(r) => r,
5862 None => return Ok(None),
5863 };
5864
5865 if result.outgoing_key_update_acked {
5866 if let Some(prev) = self.prev_crypto.as_mut() {
5867 prev.end_packet = Some((result.number, now));
5868 self.set_key_discard_timer(now, packet.header.space());
5869 }
5870 }
5871
5872 if result.incoming_key_update {
5873 trace!("key update authenticated");
5874 self.update_keys(Some((result.number, now)), true);
5875 self.set_key_discard_timer(now, packet.header.space());
5876 }
5877
5878 Ok(Some(result.number))
5879 }
5880
5881 fn update_keys(&mut self, end_packet: Option<(u64, Instant)>, remote: bool) {
5882 trace!("executing key update");
5883 let new = self
5887 .crypto
5888 .next_1rtt_keys()
5889 .expect("only called for `Data` packets");
5890 self.key_phase_size = new
5891 .local
5892 .confidentiality_limit()
5893 .saturating_sub(KEY_UPDATE_MARGIN);
5894 let old = mem::replace(
5895 &mut self.spaces[SpaceId::Data]
5896 .crypto
5897 .as_mut()
5898 .unwrap() .packet,
5900 mem::replace(self.next_crypto.as_mut().unwrap(), new),
5901 );
5902 self.spaces[SpaceId::Data]
5903 .iter_paths_mut()
5904 .for_each(|s| s.sent_with_keys = 0);
5905 self.prev_crypto = Some(PrevCrypto {
5906 crypto: old,
5907 end_packet,
5908 update_unacked: remote,
5909 });
5910 self.key_phase = !self.key_phase;
5911 }
5912
5913 fn peer_supports_ack_frequency(&self) -> bool {
5914 self.peer_params.min_ack_delay.is_some()
5915 }
5916
5917 pub(crate) fn immediate_ack(&mut self, path_id: PathId) {
5922 debug_assert_eq!(
5923 self.highest_space,
5924 SpaceId::Data,
5925 "immediate ack must be written in the data space"
5926 );
5927 self.spaces[self.highest_space]
5928 .for_path(path_id)
5929 .immediate_ack_pending = true;
5930 }
5931
5932 #[cfg(test)]
5934 pub(crate) fn decode_packet(&self, event: &ConnectionEvent) -> Option<Vec<u8>> {
5935 let (path_id, first_decode, remaining) = match &event.0 {
5936 ConnectionEventInner::Datagram(DatagramConnectionEvent {
5937 path_id,
5938 first_decode,
5939 remaining,
5940 ..
5941 }) => (path_id, first_decode, remaining),
5942 _ => return None,
5943 };
5944
5945 if remaining.is_some() {
5946 panic!("Packets should never be coalesced in tests");
5947 }
5948
5949 let decrypted_header = packet_crypto::unprotect_header(
5950 first_decode.clone(),
5951 &self.spaces,
5952 self.zero_rtt_crypto.as_ref(),
5953 self.peer_params.stateless_reset_token,
5954 )?;
5955
5956 let mut packet = decrypted_header.packet?;
5957 packet_crypto::decrypt_packet_body(
5958 &mut packet,
5959 *path_id,
5960 &self.spaces,
5961 self.zero_rtt_crypto.as_ref(),
5962 self.key_phase,
5963 self.prev_crypto.as_ref(),
5964 self.next_crypto.as_ref(),
5965 )
5966 .ok()?;
5967
5968 Some(packet.payload.to_vec())
5969 }
5970
5971 #[cfg(test)]
5974 pub(crate) fn bytes_in_flight(&self) -> u64 {
5975 self.path_data(PathId::ZERO).in_flight.bytes
5977 }
5978
5979 #[cfg(test)]
5981 pub(crate) fn congestion_window(&self) -> u64 {
5982 let path = self.path_data(PathId::ZERO);
5983 path.congestion
5984 .window()
5985 .saturating_sub(path.in_flight.bytes)
5986 }
5987
5988 #[cfg(test)]
5990 pub(crate) fn is_idle(&self) -> bool {
5991 let current_timers = self.timers.values();
5992 current_timers
5993 .into_iter()
5994 .filter(|(timer, _)| {
5995 !matches!(
5996 timer,
5997 Timer::Conn(ConnTimer::KeepAlive)
5998 | Timer::PerPath(_, PathTimer::PathKeepAlive)
5999 | Timer::Conn(ConnTimer::PushNewCid)
6000 | Timer::Conn(ConnTimer::KeyDiscard)
6001 )
6002 })
6003 .min_by_key(|(_, time)| *time)
6004 .is_none_or(|(timer, _)| timer == Timer::Conn(ConnTimer::Idle))
6005 }
6006
6007 #[cfg(test)]
6009 pub(crate) fn using_ecn(&self) -> bool {
6010 self.path_data(PathId::ZERO).sending_ecn
6011 }
6012
6013 #[cfg(test)]
6015 pub(crate) fn total_recvd(&self) -> u64 {
6016 self.path_data(PathId::ZERO).total_recvd
6017 }
6018
6019 #[cfg(test)]
6020 pub(crate) fn active_local_cid_seq(&self) -> (u64, u64) {
6021 self.local_cid_state
6022 .get(&PathId::ZERO)
6023 .unwrap()
6024 .active_seq()
6025 }
6026
6027 #[cfg(test)]
6028 #[track_caller]
6029 pub(crate) fn active_local_path_cid_seq(&self, path_id: u32) -> (u64, u64) {
6030 self.local_cid_state
6031 .get(&PathId(path_id))
6032 .unwrap()
6033 .active_seq()
6034 }
6035
6036 #[cfg(test)]
6039 pub(crate) fn rotate_local_cid(&mut self, v: u64, now: Instant) {
6040 let n = self
6041 .local_cid_state
6042 .get_mut(&PathId::ZERO)
6043 .unwrap()
6044 .assign_retire_seq(v);
6045 self.endpoint_events
6046 .push_back(EndpointEventInner::NeedIdentifiers(PathId::ZERO, now, n));
6047 }
6048
6049 #[cfg(test)]
6051 pub(crate) fn active_rem_cid_seq(&self) -> u64 {
6052 self.rem_cids.get(&PathId::ZERO).unwrap().active_seq()
6053 }
6054
6055 #[cfg(test)]
6057 pub(crate) fn path_mtu(&self, path_id: PathId) -> u16 {
6058 self.path_data(path_id).current_mtu()
6059 }
6060
6061 #[cfg(test)]
6063 pub(crate) fn trigger_path_validation(&mut self) {
6064 for path in self.paths.values_mut() {
6065 path.data.send_new_challenge = true;
6066 }
6067 }
6068
6069 fn can_send_1rtt(&self, path_id: PathId, max_size: usize) -> SendableFrames {
6080 let path_exclusive = self.paths.get(&path_id).is_some_and(|path| {
6081 path.data.send_new_challenge
6082 || path
6083 .prev
6084 .as_ref()
6085 .is_some_and(|(_, path)| path.send_new_challenge)
6086 || !path.data.path_responses.is_empty()
6087 });
6088 let other = self.streams.can_send_stream_data()
6089 || self
6090 .datagrams
6091 .outgoing
6092 .front()
6093 .is_some_and(|x| x.size(true) <= max_size);
6094 SendableFrames {
6095 acks: false,
6096 other,
6097 close: false,
6098 path_exclusive,
6099 }
6100 }
6101
6102 fn kill(&mut self, reason: ConnectionError) {
6104 self.close_common();
6105 self.state.move_to_drained(Some(reason));
6106 self.endpoint_events.push_back(EndpointEventInner::Drained);
6107 }
6108
6109 pub fn current_mtu(&self) -> u16 {
6116 self.paths
6117 .iter()
6118 .filter(|&(path_id, _path_state)| !self.abandoned_paths.contains(path_id))
6119 .map(|(_path_id, path_state)| path_state.data.current_mtu())
6120 .min()
6121 .expect("There is always at least one available path")
6122 }
6123
6124 fn predict_1rtt_overhead(&mut self, pn: u64, path: PathId) -> usize {
6131 let pn_len = PacketNumber::new(
6132 pn,
6133 self.spaces[SpaceId::Data]
6134 .for_path(path)
6135 .largest_acked_packet
6136 .unwrap_or(0),
6137 )
6138 .len();
6139
6140 1 + self
6142 .rem_cids
6143 .get(&path)
6144 .map(|cids| cids.active().len())
6145 .unwrap_or(20) + pn_len
6147 + self.tag_len_1rtt()
6148 }
6149
6150 fn predict_1rtt_overhead_no_pn(&self) -> usize {
6151 let pn_len = 4;
6152
6153 let cid_len = self
6154 .rem_cids
6155 .values()
6156 .map(|cids| cids.active().len())
6157 .max()
6158 .unwrap_or(20); 1 + cid_len + pn_len + self.tag_len_1rtt()
6162 }
6163
6164 fn tag_len_1rtt(&self) -> usize {
6165 let key = match self.spaces[SpaceId::Data].crypto.as_ref() {
6166 Some(crypto) => Some(&*crypto.packet.local),
6167 None => self.zero_rtt_crypto.as_ref().map(|x| &*x.packet),
6168 };
6169 key.map_or(16, |x| x.tag_len())
6173 }
6174
6175 fn on_path_validated(&mut self, path_id: PathId) {
6177 self.path_data_mut(path_id).validated = true;
6178 let ConnectionSide::Server { server_config } = &self.side else {
6179 return;
6180 };
6181 let remote_addr = self.path_data(path_id).remote;
6182 let new_tokens = &mut self.spaces[SpaceId::Data as usize].pending.new_tokens;
6183 new_tokens.clear();
6184 for _ in 0..server_config.validation_token.sent {
6185 new_tokens.push(remote_addr);
6186 }
6187 }
6188
6189 fn on_path_status(&mut self, path_id: PathId, status: PathStatus, status_seq_no: VarInt) {
6191 if let Some(path) = self.paths.get_mut(&path_id) {
6192 path.data.status.remote_update(status, status_seq_no);
6193 } else {
6194 debug!("PATH_STATUS_AVAILABLE received unknown path {:?}", path_id);
6195 }
6196 self.events.push_back(
6197 PathEvent::RemoteStatus {
6198 id: path_id,
6199 status,
6200 }
6201 .into(),
6202 );
6203 }
6204
6205 fn max_path_id(&self) -> Option<PathId> {
6214 if self.is_multipath_negotiated() {
6215 Some(self.remote_max_path_id.min(self.local_max_path_id))
6216 } else {
6217 None
6218 }
6219 }
6220
6221 pub fn add_nat_traversal_address(&mut self, address: SocketAddr) -> Result<(), iroh_hp::Error> {
6223 if let Some(added) = self.iroh_hp.add_local_address(address)? {
6224 self.spaces[SpaceId::Data].pending.add_address.insert(added);
6225 };
6226 Ok(())
6227 }
6228
6229 pub fn remove_nat_traversal_address(
6233 &mut self,
6234 address: SocketAddr,
6235 ) -> Result<(), iroh_hp::Error> {
6236 if let Some(removed) = self.iroh_hp.remove_local_address(address)? {
6237 self.spaces[SpaceId::Data]
6238 .pending
6239 .remove_address
6240 .insert(removed);
6241 }
6242 Ok(())
6243 }
6244
6245 pub fn get_local_nat_traversal_addresses(&self) -> Result<Vec<SocketAddr>, iroh_hp::Error> {
6247 self.iroh_hp.get_local_nat_traversal_addresses()
6248 }
6249
6250 pub fn get_remote_nat_traversal_addresses(&self) -> Result<Vec<SocketAddr>, iroh_hp::Error> {
6252 Ok(self
6253 .iroh_hp
6254 .client_side()?
6255 .get_remote_nat_traversal_addresses())
6256 }
6257
6258 pub fn initiate_nat_traversal_round(
6266 &mut self,
6267 now: Instant,
6268 ) -> Result<Vec<SocketAddr>, iroh_hp::Error> {
6269 if self.state.is_closed() {
6270 return Err(iroh_hp::Error::Closed);
6271 }
6272
6273 let client_state = self.iroh_hp.client_side_mut()?;
6274 let iroh_hp::NatTraversalRound {
6275 new_round,
6276 reach_out_at,
6277 addresses_to_probe,
6278 prev_round_path_ids,
6279 } = client_state.initiate_nat_traversal_round()?;
6280
6281 self.spaces[SpaceId::Data].pending.reach_out = Some((new_round, reach_out_at));
6282
6283 for path_id in prev_round_path_ids {
6284 let validated = self
6287 .path(path_id)
6288 .map(|path| path.validated)
6289 .unwrap_or(false);
6290
6291 if !validated {
6292 let _ = self.close_path(
6293 now,
6294 path_id,
6295 TransportErrorCode::APPLICATION_ABANDON_PATH.into(),
6296 );
6297 }
6298 }
6299
6300 let mut err = None;
6301
6302 let mut path_ids = Vec::with_capacity(addresses_to_probe.len());
6303 let mut probed_addresses = Vec::with_capacity(addresses_to_probe.len());
6304 let ipv6 = self.paths.values().any(|p| p.data.remote.is_ipv6());
6305
6306 for (ip, port) in addresses_to_probe {
6307 let remote = match ip {
6309 IpAddr::V4(addr) if ipv6 => SocketAddr::new(addr.to_ipv6_mapped().into(), port),
6310 IpAddr::V4(addr) => SocketAddr::new(addr.into(), port),
6311 IpAddr::V6(_) if ipv6 => SocketAddr::new(ip, port),
6312 IpAddr::V6(_) => {
6313 trace!("not using IPv6 nat candidate for IPv4 socket");
6314 continue;
6315 }
6316 };
6317 match self.open_path_ensure(remote, PathStatus::Backup, now) {
6318 Ok((path_id, path_was_known)) if !path_was_known => {
6319 path_ids.push(path_id);
6320 probed_addresses.push(remote);
6321 }
6322 Ok((path_id, _)) => {
6323 trace!(%path_id, %remote,"nat traversal: path existed for remote")
6324 }
6325 Err(e) => {
6326 debug!(%remote, %e,"nat traversal: failed to probe remote");
6327 err.get_or_insert(e);
6328 }
6329 }
6330 }
6331
6332 if let Some(err) = err {
6333 if probed_addresses.is_empty() {
6335 return Err(iroh_hp::Error::Multipath(err));
6336 }
6337 }
6338
6339 self.iroh_hp
6340 .client_side_mut()
6341 .expect("connection side validated")
6342 .set_round_path_ids(path_ids);
6343
6344 Ok(probed_addresses)
6345 }
6346}
6347
6348impl fmt::Debug for Connection {
6349 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
6350 f.debug_struct("Connection")
6351 .field("handshake_cid", &self.handshake_cid)
6352 .finish()
6353 }
6354}
6355
6356#[derive(Debug, Copy, Clone, PartialEq, Eq)]
6357enum PathBlocked {
6358 No,
6359 AntiAmplification,
6360 Congestion,
6361 Pacing,
6362}
6363
6364enum ConnectionSide {
6366 Client {
6367 token: Bytes,
6369 token_store: Arc<dyn TokenStore>,
6370 server_name: String,
6371 },
6372 Server {
6373 server_config: Arc<ServerConfig>,
6374 },
6375}
6376
6377impl ConnectionSide {
6378 fn remote_may_migrate(&self, state: &State) -> bool {
6379 match self {
6380 Self::Server { server_config } => server_config.migration,
6381 Self::Client { .. } => {
6382 if let Some(hs) = state.as_handshake() {
6383 hs.allow_server_migration
6384 } else {
6385 false
6386 }
6387 }
6388 }
6389 }
6390
6391 fn is_client(&self) -> bool {
6392 self.side().is_client()
6393 }
6394
6395 fn is_server(&self) -> bool {
6396 self.side().is_server()
6397 }
6398
6399 fn side(&self) -> Side {
6400 match *self {
6401 Self::Client { .. } => Side::Client,
6402 Self::Server { .. } => Side::Server,
6403 }
6404 }
6405}
6406
6407impl From<SideArgs> for ConnectionSide {
6408 fn from(side: SideArgs) -> Self {
6409 match side {
6410 SideArgs::Client {
6411 token_store,
6412 server_name,
6413 } => Self::Client {
6414 token: token_store.take(&server_name).unwrap_or_default(),
6415 token_store,
6416 server_name,
6417 },
6418 SideArgs::Server {
6419 server_config,
6420 pref_addr_cid: _,
6421 path_validated: _,
6422 } => Self::Server { server_config },
6423 }
6424 }
6425}
6426
6427pub(crate) enum SideArgs {
6429 Client {
6430 token_store: Arc<dyn TokenStore>,
6431 server_name: String,
6432 },
6433 Server {
6434 server_config: Arc<ServerConfig>,
6435 pref_addr_cid: Option<ConnectionId>,
6436 path_validated: bool,
6437 },
6438}
6439
6440impl SideArgs {
6441 pub(crate) fn pref_addr_cid(&self) -> Option<ConnectionId> {
6442 match *self {
6443 Self::Client { .. } => None,
6444 Self::Server { pref_addr_cid, .. } => pref_addr_cid,
6445 }
6446 }
6447
6448 pub(crate) fn path_validated(&self) -> bool {
6449 match *self {
6450 Self::Client { .. } => true,
6451 Self::Server { path_validated, .. } => path_validated,
6452 }
6453 }
6454
6455 pub(crate) fn side(&self) -> Side {
6456 match *self {
6457 Self::Client { .. } => Side::Client,
6458 Self::Server { .. } => Side::Server,
6459 }
6460 }
6461}
6462
6463#[derive(Debug, Error, Clone, PartialEq, Eq)]
6465pub enum ConnectionError {
6466 #[error("peer doesn't implement any supported version")]
6468 VersionMismatch,
6469 #[error(transparent)]
6471 TransportError(#[from] TransportError),
6472 #[error("aborted by peer: {0}")]
6474 ConnectionClosed(frame::ConnectionClose),
6475 #[error("closed by peer: {0}")]
6477 ApplicationClosed(frame::ApplicationClose),
6478 #[error("reset by peer")]
6480 Reset,
6481 #[error("timed out")]
6487 TimedOut,
6488 #[error("closed")]
6490 LocallyClosed,
6491 #[error("CIDs exhausted")]
6495 CidsExhausted,
6496}
6497
6498impl From<Close> for ConnectionError {
6499 fn from(x: Close) -> Self {
6500 match x {
6501 Close::Connection(reason) => Self::ConnectionClosed(reason),
6502 Close::Application(reason) => Self::ApplicationClosed(reason),
6503 }
6504 }
6505}
6506
6507impl From<ConnectionError> for io::Error {
6509 fn from(x: ConnectionError) -> Self {
6510 use ConnectionError::*;
6511 let kind = match x {
6512 TimedOut => io::ErrorKind::TimedOut,
6513 Reset => io::ErrorKind::ConnectionReset,
6514 ApplicationClosed(_) | ConnectionClosed(_) => io::ErrorKind::ConnectionAborted,
6515 TransportError(_) | VersionMismatch | LocallyClosed | CidsExhausted => {
6516 io::ErrorKind::Other
6517 }
6518 };
6519 Self::new(kind, x)
6520 }
6521}
6522
6523#[derive(Debug, Error, PartialEq, Eq, Clone, Copy)]
6526pub enum PathError {
6527 #[error("multipath extension not negotiated")]
6529 MultipathNotNegotiated,
6530 #[error("the server side may not open a path")]
6532 ServerSideNotAllowed,
6533 #[error("maximum number of concurrent paths reached")]
6535 MaxPathIdReached,
6536 #[error("remoted CIDs exhausted")]
6538 RemoteCidsExhausted,
6539 #[error("path validation failed")]
6541 ValidationFailed,
6542 #[error("invalid remote address")]
6544 InvalidRemoteAddress(SocketAddr),
6545}
6546
6547#[derive(Debug, Error, Clone, Eq, PartialEq)]
6549pub enum ClosePathError {
6550 #[error("closed path")]
6552 ClosedPath,
6553 #[error("last open path")]
6555 LastOpenPath,
6556}
6557
6558#[derive(Debug, Error, Clone, Copy)]
6559#[error("Multipath extension not negotiated")]
6560pub struct MultipathNotNegotiated {
6561 _private: (),
6562}
6563
6564#[derive(Debug)]
6566pub enum Event {
6567 HandshakeDataReady,
6569 Connected,
6571 HandshakeConfirmed,
6573 ConnectionLost {
6577 reason: ConnectionError,
6579 },
6580 Stream(StreamEvent),
6582 DatagramReceived,
6584 DatagramsUnblocked,
6586 Path(PathEvent),
6588 NatTraversal(iroh_hp::Event),
6590}
6591
6592impl From<PathEvent> for Event {
6593 fn from(source: PathEvent) -> Self {
6594 Self::Path(source)
6595 }
6596}
6597
6598fn get_max_ack_delay(params: &TransportParameters) -> Duration {
6599 Duration::from_micros(params.max_ack_delay.0 * 1000)
6600}
6601
6602const MAX_BACKOFF_EXPONENT: u32 = 16;
6604
6605const MIN_PACKET_SPACE: usize = MAX_HANDSHAKE_OR_0RTT_HEADER_SIZE + 32;
6613
6614const MAX_HANDSHAKE_OR_0RTT_HEADER_SIZE: usize =
6620 1 + 4 + 1 + MAX_CID_SIZE + 1 + MAX_CID_SIZE + VarInt::from_u32(u16::MAX as u32).size() + 4;
6621
6622const KEY_UPDATE_MARGIN: u64 = 10_000;
6626
6627#[derive(Default)]
6628struct SentFrames {
6629 retransmits: ThinRetransmits,
6630 largest_acked: FxHashMap<PathId, u64>,
6632 stream_frames: StreamMetaVec,
6633 non_retransmits: bool,
6635 requires_padding: bool,
6637}
6638
6639impl SentFrames {
6640 fn is_ack_only(&self, streams: &StreamsState) -> bool {
6642 !self.largest_acked.is_empty()
6643 && !self.non_retransmits
6644 && self.stream_frames.is_empty()
6645 && self.retransmits.is_empty(streams)
6646 }
6647}
6648
6649fn negotiate_max_idle_timeout(x: Option<VarInt>, y: Option<VarInt>) -> Option<Duration> {
6657 match (x, y) {
6658 (Some(VarInt(0)) | None, Some(VarInt(0)) | None) => None,
6659 (Some(VarInt(0)) | None, Some(y)) => Some(Duration::from_millis(y.0)),
6660 (Some(x), Some(VarInt(0)) | None) => Some(Duration::from_millis(x.0)),
6661 (Some(x), Some(y)) => Some(Duration::from_millis(cmp::min(x, y).0)),
6662 }
6663}
6664
6665#[cfg(test)]
6666mod tests {
6667 use super::*;
6668
6669 #[test]
6670 fn negotiate_max_idle_timeout_commutative() {
6671 let test_params = [
6672 (None, None, None),
6673 (None, Some(VarInt(0)), None),
6674 (None, Some(VarInt(2)), Some(Duration::from_millis(2))),
6675 (Some(VarInt(0)), Some(VarInt(0)), None),
6676 (
6677 Some(VarInt(2)),
6678 Some(VarInt(0)),
6679 Some(Duration::from_millis(2)),
6680 ),
6681 (
6682 Some(VarInt(1)),
6683 Some(VarInt(4)),
6684 Some(Duration::from_millis(1)),
6685 ),
6686 ];
6687
6688 for (left, right, result) in test_params {
6689 assert_eq!(negotiate_max_idle_timeout(left, right), result);
6690 assert_eq!(negotiate_max_idle_timeout(right, left), result);
6691 }
6692 }
6693}