noq_proto/connection/paths.rs
1use std::{cmp, net::SocketAddr};
2
3use identity_hash::IntMap;
4use thiserror::Error;
5use tracing::{debug, trace};
6
7use super::{
8 PathStats, SpaceKind,
9 mtud::MtuDiscovery,
10 pacing::Pacer,
11 spaces::{PacketNumberSpace, SentPacket},
12};
13use crate::{
14 ConnectionId, Duration, FourTuple, Instant, TIMER_GRANULARITY, TransportConfig,
15 TransportErrorCode, VarInt,
16 coding::{self, Decodable, Encodable},
17 congestion,
18 frame::ObservedAddr,
19};
20
21#[cfg(feature = "qlog")]
22use qlog::events::quic::RecoveryMetricsUpdated;
23
24/// Id representing different paths when using multipath extension
25#[cfg_attr(test, derive(test_strategy::Arbitrary))]
26#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Default)]
27pub struct PathId(pub(crate) u32);
28
29impl std::hash::Hash for PathId {
30 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
31 state.write_u32(self.0);
32 }
33}
34
35impl identity_hash::IdentityHashable for PathId {}
36
37impl Decodable for PathId {
38 fn decode<B: bytes::Buf>(r: &mut B) -> coding::Result<Self> {
39 let v = VarInt::decode(r)?;
40 let v = u32::try_from(v.0).map_err(|_| coding::UnexpectedEnd)?;
41 Ok(Self(v))
42 }
43}
44
45impl Encodable for PathId {
46 fn encode<B: bytes::BufMut>(&self, w: &mut B) {
47 VarInt(self.0.into()).encode(w)
48 }
49}
50
51impl PathId {
52 /// The maximum path ID allowed.
53 pub const MAX: Self = Self(u32::MAX);
54
55 /// The 0 path id.
56 pub const ZERO: Self = Self(0);
57
58 /// The number of bytes this [`PathId`] uses when encoded as a [`VarInt`]
59 pub(crate) const fn size(&self) -> usize {
60 VarInt(self.0 as u64).size()
61 }
62
63 /// Saturating integer addition. Computes self + rhs, saturating at the numeric bounds instead
64 /// of overflowing.
65 pub fn saturating_add(self, rhs: impl Into<Self>) -> Self {
66 let rhs = rhs.into();
67 let inner = self.0.saturating_add(rhs.0);
68 Self(inner)
69 }
70
71 /// Saturating integer subtraction. Computes self - rhs, saturating at the numeric bounds
72 /// instead of overflowing.
73 pub fn saturating_sub(self, rhs: impl Into<Self>) -> Self {
74 let rhs = rhs.into();
75 let inner = self.0.saturating_sub(rhs.0);
76 Self(inner)
77 }
78
79 /// Get the next [`PathId`]
80 pub(crate) fn next(&self) -> Self {
81 self.saturating_add(Self(1))
82 }
83
84 /// Get the underlying u32
85 pub(crate) fn as_u32(&self) -> u32 {
86 self.0
87 }
88}
89
90impl std::fmt::Display for PathId {
91 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
92 self.0.fmt(f)
93 }
94}
95
96impl<T: Into<u32>> From<T> for PathId {
97 fn from(source: T) -> Self {
98 Self(source.into())
99 }
100}
101
102/// State needed for a single path ID.
103///
104/// A single path ID can migrate according to the rules in RFC9000 §9, either voluntary or
105/// involuntary. We need to keep the [`PathData`] of the previously used such path available
106/// in order to defend against migration attacks (see RFC9000 §9.3.1, §9.3.2 and §9.3.3) as
107/// well as to support path probing (RFC9000 §9.1).
108#[derive(Debug)]
109pub(super) struct PathState {
110 pub(super) data: PathData,
111 pub(super) prev: Option<(ConnectionId, PathData)>,
112}
113
114impl PathState {
115 /// Update counters to account for a packet becoming acknowledged, lost, or abandoned
116 pub(super) fn remove_in_flight(&mut self, packet: &SentPacket) {
117 // Visit known paths from newest to oldest to find the one `pn` was sent on
118 for path_data in [&mut self.data]
119 .into_iter()
120 .chain(self.prev.as_mut().map(|(_, data)| data))
121 {
122 if path_data.remove_in_flight(packet) {
123 return;
124 }
125 }
126 }
127}
128
129#[derive(Debug)]
130pub(super) struct SentChallengeInfo {
131 /// When was the challenge sent on the wire.
132 pub(super) sent_instant: Instant,
133 /// The 4-tuple on which this path challenge was sent.
134 pub(super) network_path: FourTuple,
135}
136
137/// State of particular network path 4-tuple within a [`PacketNumberSpace`].
138///
139/// With QUIC-Multipath a path is identified by a [`PathId`] and it is possible to have
140/// multiple paths on the same 4-tuple. Furthermore a single QUIC-Multipath path can migrate
141/// to a different 4-tuple, in a similar manner as an RFC9000 connection can use "path
142/// migration" to move to a different 4-tuple. There are thus two states we keep for paths:
143///
144/// - [`PacketNumberSpace`]: The state for a single packet number space, i.e. [`PathId`],
145/// which remains in place across path migrations to different 4-tuples.
146///
147/// This is stored in [`PacketSpace::number_spaces`] indexed on [`PathId`].
148///
149/// - [`PathData`]: The state we keep for each unique 4-tuple within a space. Of note is
150/// that a single [`PathData`] can never belong to a different [`PacketNumberSpace`].
151///
152/// This is stored in [`Connection::paths`] indexed by the current [`PathId`] for which
153/// space it exists. Either as the primary 4-tuple or as the previous 4-tuple just after a
154/// migration.
155///
156/// It follows that there might be several [`PathData`] structs for the same 4-tuple if
157/// several spaces are sharing the same 4-tuple. Note that during the handshake, the
158/// Initial, Handshake and Data spaces for [`PathId::ZERO`] all share the same [`PathData`].
159///
160/// [`PacketSpace::number_spaces`]: super::spaces::PacketSpace::number_spaces
161/// [`Connection::paths`]: super::Connection::paths
162#[derive(Debug)]
163pub(super) struct PathData {
164 pub(super) network_path: FourTuple,
165 pub(super) rtt: RttEstimator,
166 /// Whether we're enabling ECN on outgoing packets
167 pub(super) sending_ecn: bool,
168 /// Congestion controller state
169 pub(super) congestion: Box<dyn congestion::Controller>,
170 /// Pacing state
171 pub(super) pacing: Pacer,
172 /// Whether the last `poll_transmit_on_path` call yielded no data because there was
173 /// no outgoing application data.
174 ///
175 /// The RFC writes:
176 /// > When bytes in flight is smaller than the congestion window and sending is not pacing limited,
177 /// > the congestion window is underutilized. This can happen due to insufficient application data
178 /// > or flow control limits. When this occurs, the congestion window SHOULD NOT be increased in
179 /// > either slow start or congestion avoidance.
180 ///
181 /// (RFC9002, section 7.8)
182 ///
183 /// I.e. when app_limited is true, the congestion controller doesn't increase the congestion window.
184 pub(super) app_limited: bool,
185
186 /// Path challenges sent (on the wire, on-path) that we didn't receive a path response for yet
187 on_path_challenges_unconfirmed: IntMap<u64, SentChallengeInfo>,
188 /// Path challenges sent (on the wire, off-path) that we didn't receive a path response for yet
189 off_path_challenges_unconfirmed: IntMap<u64, SentChallengeInfo>,
190 /// Whether to trigger sending another PATH_CHALLENGE in the next poll_transmit.
191 ///
192 /// This is picked up by [`super::Connection::space_can_send`].
193 ///
194 /// Only used for RFC9000-style path migration and multipath path validation (for opening).
195 ///
196 /// This is **not used** for n0 nat traversal challenge sending.
197 pub(super) pending_on_path_challenge: bool,
198 /// Pending responses to PATH_CHALLENGE frames
199 pub(super) path_responses: PathResponses,
200 /// Whether we're certain the peer can both send and receive on this address
201 ///
202 /// Initially equal to `use_stateless_retry` for servers, and becomes false again on every
203 /// migration. Always true for clients.
204 pub(super) validated: bool,
205 /// Total size of all UDP datagrams sent on this path
206 pub(super) total_sent: u64,
207 /// Total size of all UDP datagrams received on this path
208 pub(super) total_recvd: u64,
209 /// The state of the MTU discovery process
210 pub(super) mtud: MtuDiscovery,
211 /// Packet number of the first packet sent after an RTT sample was collected on this path
212 ///
213 /// Used in persistent congestion determination.
214 pub(super) first_packet_after_rtt_sample: Option<(SpaceKind, u64)>,
215 /// The in-flight packets and bytes
216 ///
217 /// Note that this is across all spaces on this path
218 pub(super) in_flight: InFlight,
219 /// Whether this path has had it's remote address reported back to the peer. This only happens
220 /// if both peers agree to so based on their transport parameters.
221 pub(super) observed_addr_sent: bool,
222 /// Observed address frame with the largest sequence number received from the peer on this path.
223 pub(super) last_observed_addr_report: Option<ObservedAddr>,
224 /// The QUIC-MULTIPATH path status
225 pub(super) status: PathStatusState,
226 /// Number of the first packet sent on this path
227 ///
228 /// With RFC9000 §9 style migration (i.e. not multipath) the PathId does not change and
229 /// hence packet numbers continue. This is used to determine whether a packet was sent
230 /// on such an earlier path. Insufficient to determine if a packet was sent on a later
231 /// path.
232 first_packet: Option<u64>,
233 /// The number of times a tail-loss probe has been sent without receiving an ack.
234 ///
235 /// This is incremented by one every time the [`LossDetection`] timer fires because a
236 /// tail-loss probe needs to be sent. Once an acknowledgement for a packet is received
237 /// again it is reset to 0. Used to compute the PTO duration.
238 ///
239 /// [`LossDetection`]: super::timer::PathTimer::LossDetection
240 pub(super) pto_count: u32,
241
242 //
243 // Per-path idle & keep alive
244 //
245 /// Idle timeout for the path
246 ///
247 /// If expired, the path will be abandoned. This is different from the connection-wide
248 /// idle timeout which closes the connection if expired.
249 pub(super) idle_timeout: Option<Duration>,
250 /// Keep alives to send on this path
251 ///
252 /// There is also a connection-level keep alive configured in the
253 /// [`TransportParameters`]. This triggers activity on any path which can keep the
254 /// connection alive.
255 ///
256 /// [`TransportParameters`]: crate::transport_parameters::TransportParameters
257 pub(super) keep_alive: Option<Duration>,
258 /// Whether to reset the idle timer when the next ack-eliciting packet is sent.
259 ///
260 /// Whenever we receive an authenticated packet the connection and path idle timers are
261 /// reset if a maximum idle timeout was negotiated. However on the first ack-eliciting
262 /// packet *sent* after this the idle timer also needs to be reset to avoid the idle
263 /// timer firing while the sent packet is in-fight. See
264 /// <https://www.rfc-editor.org/rfc/rfc9000.html#section-10.1>.
265 pub(super) permit_idle_reset: bool,
266
267 /// Whether the path has already been considered opened from an application perspective.
268 ///
269 /// This means, for paths other than the original [`PathId::ZERO`], a first path challenge has
270 /// been responded to, regardless of the initial validation status of the path. This state is
271 /// irreversible, since it's not affected by the path being closed.
272 ///
273 /// Sending a PATH_CHALLENGE and receiving a valid response before the application is informed
274 /// of the path, is a way to ensure the path is usable before it is reported. This is not
275 /// required by the spec, and in the future might be changed for simply requiring a first ack'd
276 /// packet.
277 pub(super) open_status: OpenStatus,
278
279 /// Whether we're currently draining the path after having abandoned it.
280 ///
281 /// This should only be true when a path discard timer is armed, and after the path was
282 /// abandoned (and added to the abandoned_paths set).
283 ///
284 /// This will only ever be set from false to true.
285 pub(super) draining: bool,
286
287 /// Snapshot of the qlog recovery metrics
288 #[cfg(feature = "qlog")]
289 recovery_metrics: RecoveryMetrics,
290
291 /// Tag uniquely identifying a path in a connection.
292 ///
293 /// When a migration happens on the same [`PathId`] we still detect a change in the
294 /// 4-tuple and generate a new [`PathData`] for it. Each such generation has a unique
295 /// value to keep track of which 4-tuple a packet belonged to.
296 generation: u64,
297}
298
299impl PathData {
300 pub(super) fn new(
301 network_path: FourTuple,
302 allow_mtud: bool,
303 peer_max_udp_payload_size: Option<u16>,
304 generation: u64,
305 now: Instant,
306 config: &TransportConfig,
307 ) -> Self {
308 let congestion = config
309 .congestion_controller_factory
310 .clone()
311 .build(now, config.get_initial_mtu());
312 Self {
313 network_path,
314 rtt: RttEstimator::new(config.initial_rtt),
315 sending_ecn: true,
316 pacing: Pacer::new(
317 config.initial_rtt,
318 congestion.initial_window(),
319 config.get_initial_mtu(),
320 now,
321 ),
322 congestion,
323 app_limited: false,
324 on_path_challenges_unconfirmed: Default::default(),
325 off_path_challenges_unconfirmed: Default::default(),
326 pending_on_path_challenge: false,
327 path_responses: PathResponses::default(),
328 validated: false,
329 total_sent: 0,
330 total_recvd: 0,
331 mtud: config
332 .mtu_discovery_config
333 .as_ref()
334 .filter(|_| allow_mtud)
335 .map_or_else(
336 || MtuDiscovery::disabled(config.get_initial_mtu(), config.min_mtu),
337 |mtud_config| {
338 MtuDiscovery::new(
339 config.get_initial_mtu(),
340 config.min_mtu,
341 peer_max_udp_payload_size,
342 mtud_config.clone(),
343 )
344 },
345 ),
346 first_packet_after_rtt_sample: None,
347 in_flight: InFlight::new(),
348 observed_addr_sent: false,
349 last_observed_addr_report: None,
350 status: Default::default(),
351 first_packet: None,
352 pto_count: 0,
353 idle_timeout: config.default_path_max_idle_timeout,
354 keep_alive: config.default_path_keep_alive_interval,
355 permit_idle_reset: true,
356 open_status: OpenStatus::default(),
357 draining: false,
358 #[cfg(feature = "qlog")]
359 recovery_metrics: RecoveryMetrics::default(),
360 generation,
361 }
362 }
363
364 /// Create a new path from a previous one.
365 ///
366 /// This should only be called when migrating paths.
367 pub(super) fn from_previous(
368 network_path: FourTuple,
369 prev: &Self,
370 generation: u64,
371 now: Instant,
372 ) -> Self {
373 let congestion = prev.congestion.clone_box();
374 let smoothed_rtt = prev.rtt.get();
375 Self {
376 network_path,
377 rtt: prev.rtt,
378 pacing: Pacer::new(smoothed_rtt, congestion.window(), prev.current_mtu(), now),
379 sending_ecn: true,
380 congestion,
381 app_limited: false,
382 on_path_challenges_unconfirmed: Default::default(),
383 off_path_challenges_unconfirmed: Default::default(),
384 pending_on_path_challenge: false,
385 path_responses: PathResponses::default(),
386 validated: false,
387 total_sent: 0,
388 total_recvd: 0,
389 mtud: prev.mtud.clone(),
390 first_packet_after_rtt_sample: prev.first_packet_after_rtt_sample,
391 in_flight: InFlight::new(),
392 observed_addr_sent: false,
393 last_observed_addr_report: None,
394 status: prev.status.clone(),
395 first_packet: None,
396 pto_count: 0,
397 idle_timeout: prev.idle_timeout,
398 keep_alive: prev.keep_alive,
399 permit_idle_reset: true,
400 open_status: OpenStatus::default(),
401 draining: false,
402 #[cfg(feature = "qlog")]
403 recovery_metrics: prev.recovery_metrics.clone(),
404 generation,
405 }
406 }
407
408 /// Whether we're in the process of validating this path with PATH_CHALLENGEs
409 pub(super) fn is_validating_path(&self) -> bool {
410 !self.on_path_challenges_unconfirmed.is_empty() || self.pending_on_path_challenge
411 }
412
413 /// Indicates whether we're a server that hasn't validated the peer's address and hasn't
414 /// received enough data from the peer to permit sending `bytes_to_send` additional bytes
415 pub(super) fn anti_amplification_blocked(&self, bytes_to_send: u64) -> bool {
416 !self.validated && self.total_recvd * 3 < self.total_sent + bytes_to_send
417 }
418
419 /// Returns the path's current MTU
420 pub(super) fn current_mtu(&self) -> u16 {
421 self.mtud.current_mtu()
422 }
423
424 /// Account for transmission of `packet` with number `pn` in `space`
425 pub(super) fn sent(&mut self, pn: u64, packet: SentPacket, space: &mut PacketNumberSpace) {
426 self.in_flight.insert(&packet);
427 if self.first_packet.is_none() {
428 self.first_packet = Some(pn);
429 }
430 if let Some(forgotten) = space.sent(pn, packet) {
431 self.remove_in_flight(&forgotten);
432 }
433 }
434
435 pub(super) fn record_path_challenge_sent(
436 &mut self,
437 now: Instant,
438 token: u64,
439 network_path: FourTuple,
440 ) {
441 let info = SentChallengeInfo {
442 sent_instant: now,
443 network_path,
444 };
445 if network_path == self.network_path {
446 self.on_path_challenges_unconfirmed.insert(token, info);
447 } else {
448 self.off_path_challenges_unconfirmed.insert(token, info);
449 }
450 }
451
452 /// Remove `packet` with number `pn` from this path's congestion control counters, or return
453 /// `false` if `pn` was sent before this path was established.
454 pub(super) fn remove_in_flight(&mut self, packet: &SentPacket) -> bool {
455 if packet.path_generation != self.generation {
456 return false;
457 }
458 self.in_flight.remove(packet);
459 true
460 }
461
462 /// Increment the total size of sent UDP datagrams
463 pub(super) fn inc_total_sent(&mut self, inc: u64) {
464 self.total_sent = self.total_sent.saturating_add(inc);
465 if !self.validated {
466 trace!(
467 network_path = %self.network_path,
468 anti_amplification_budget = %(self.total_recvd * 3).saturating_sub(self.total_sent),
469 "anti amplification budget decreased"
470 );
471 }
472 }
473
474 /// Increment the total size of received UDP datagrams
475 pub(super) fn inc_total_recvd(&mut self, inc: u64) {
476 self.total_recvd = self.total_recvd.saturating_add(inc);
477 if !self.validated {
478 trace!(
479 network_path = %self.network_path,
480 anti_amplification_budget = %(self.total_recvd * 3).saturating_sub(self.total_sent),
481 "anti amplification budget increased"
482 );
483 }
484 }
485
486 /// The earliest time at which an on-path challenge we sent is considered lost.
487 pub(super) fn earliest_on_path_expiring_challenge(&self) -> Option<Instant> {
488 if self.on_path_challenges_unconfirmed.is_empty() {
489 return None;
490 }
491 let pto = self.rtt.pto_base();
492 self.on_path_challenges_unconfirmed
493 .values()
494 .map(|info| info.sent_instant + pto)
495 .min()
496 }
497
498 /// Handle receiving a PATH_RESPONSE.
499 pub(super) fn on_path_response_received(
500 &mut self,
501 now: Instant,
502 token: u64,
503 network_path: FourTuple,
504 ) -> OnPathResponseReceived {
505 // > § 8.2.3
506 // > Path validation succeeds when a PATH_RESPONSE frame is received that contains the
507 // > data that was sent in a previous PATH_CHALLENGE frame. A PATH_RESPONSE frame
508 // > received on any network path validates the path on which the PATH_CHALLENGE was
509 // > sent.
510 //
511 // At this point we have three potentially different network paths:
512 // - current network path (`Self::network_path`)
513 // - network path used to send the path challenge (`SentChallengeInfo::network_path`)
514 // - network path over which the response arrived (`network_path`)
515 //
516 // As per the spec, this only validates the network path on which this was *sent*.
517 match self.on_path_challenges_unconfirmed.remove(&token) {
518 // Response to an on-path PathChallenge that validates this path.
519 // The sent path should match the current path. However, it's possible that the
520 // challenge was sent when no local_ip was known. This case is allowed as well
521 Some(info) if info.network_path.is_probably_same_path(&self.network_path) => {
522 self.network_path.update_local_if_same_remote(&network_path);
523 let sent_instant = info.sent_instant;
524 if !std::mem::replace(&mut self.validated, true) {
525 trace!("new path validated");
526 }
527 // Clear any other on-path sent challenge
528 self.on_path_challenges_unconfirmed.clear();
529
530 self.pending_on_path_challenge = false;
531
532 // This RTT can only be used for the initial RTT, not as a normal
533 // sample: https://www.rfc-editor.org/rfc/rfc9002#section-6.2.2-2.
534 let rtt = now.saturating_duration_since(sent_instant);
535 self.rtt.reset_initial_rtt(rtt);
536
537 let prev_status = std::mem::replace(&mut self.open_status, OpenStatus::Informed);
538 OnPathResponseReceived::OnPath {
539 was_open: matches!(
540 prev_status,
541 OpenStatus::Informed | OpenStatus::Revalidating
542 ),
543 }
544 }
545 // Response to an on-path PathChallenge that does not validate this path
546 Some(info) => {
547 // This is a valid path response, but this validates a path we no longer have in
548 // use. Keep only sent challenges for the current path.
549
550 self.on_path_challenges_unconfirmed
551 .retain(|_token, i| i.network_path == self.network_path);
552
553 // if there are no challenges for the current path, schedule one
554 if !self.on_path_challenges_unconfirmed.is_empty() {
555 self.pending_on_path_challenge = true;
556 }
557 OnPathResponseReceived::Ignored {
558 sent_on: info.network_path,
559 current_path: self.network_path,
560 }
561 }
562 None => match self.off_path_challenges_unconfirmed.remove(&token) {
563 // Response to an off-path PathChallenge
564 Some(info) => {
565 // Since we do not store validation state for these paths, we only really care
566 // about reaching the same remote
567 self.off_path_challenges_unconfirmed
568 .retain(|_token, i| i.network_path.remote != info.network_path.remote);
569 OnPathResponseReceived::OffPath
570 }
571 // Response to an unknown PathChallenge. Does not indicate failure
572 None => OnPathResponseReceived::Unknown,
573 },
574 }
575 }
576
577 /// Removes all on-path challenges we remember and cancels sending new on-path challenges.
578 pub(super) fn reset_on_path_challenges(&mut self) {
579 self.on_path_challenges_unconfirmed.clear();
580 self.pending_on_path_challenge = false;
581 }
582
583 /// Returns whether there are any pending off-path challenges.
584 pub(super) fn has_off_path_challenges(&self) -> bool {
585 !self.off_path_challenges_unconfirmed.is_empty()
586 }
587
588 /// Clears all off-path challenges.
589 ///
590 /// Used when a new NAT traversal round starts and old probes are obsolete.
591 pub(super) fn clear_off_path_challenges(&mut self) {
592 self.off_path_challenges_unconfirmed.clear();
593 }
594
595 #[cfg(feature = "qlog")]
596 pub(super) fn qlog_recovery_metrics(
597 &mut self,
598 path_id: PathId,
599 ) -> Option<RecoveryMetricsUpdated> {
600 let controller_metrics = self.congestion.metrics();
601
602 let metrics = RecoveryMetrics {
603 min_rtt: Some(self.rtt.min),
604 smoothed_rtt: Some(self.rtt.get()),
605 latest_rtt: Some(self.rtt.latest),
606 rtt_variance: Some(self.rtt.var),
607 pto_count: Some(self.pto_count),
608 bytes_in_flight: Some(self.in_flight.bytes),
609 packets_in_flight: Some(self.in_flight.ack_eliciting),
610
611 congestion_window: Some(controller_metrics.congestion_window),
612 ssthresh: controller_metrics.ssthresh,
613 pacing_rate: controller_metrics.pacing_rate,
614 };
615
616 let event = metrics.to_qlog_event(path_id, &self.recovery_metrics);
617 self.recovery_metrics = metrics;
618 event
619 }
620
621 /// Return how long we need to wait before sending `bytes_to_send`
622 ///
623 /// See [`Pacer::delay`].
624 pub(super) fn pacing_delay(&mut self, bytes_to_send: u64, now: Instant) -> Option<Duration> {
625 let smoothed_rtt = self.rtt.get();
626 self.pacing.delay(
627 smoothed_rtt,
628 bytes_to_send,
629 self.current_mtu(),
630 self.congestion.window(),
631 now,
632 )
633 }
634
635 /// Updates the last observed address report received on this path.
636 ///
637 /// If the address was updated, it's returned to be informed to the application.
638 #[must_use = "updated observed address must be reported to the application"]
639 pub(super) fn update_observed_addr_report(
640 &mut self,
641 observed: ObservedAddr,
642 ) -> Option<SocketAddr> {
643 match self.last_observed_addr_report.as_mut() {
644 Some(prev) => {
645 if prev.seq_no >= observed.seq_no {
646 // frames that do not increase the sequence number on this path are ignored
647 None
648 } else if prev.ip == observed.ip && prev.port == observed.port {
649 // keep track of the last seq_no but do not report the address as updated
650 prev.seq_no = observed.seq_no;
651 None
652 } else {
653 let addr = observed.socket_addr();
654 self.last_observed_addr_report = Some(observed);
655 Some(addr)
656 }
657 }
658 None => {
659 let addr = observed.socket_addr();
660 self.last_observed_addr_report = Some(observed);
661 Some(addr)
662 }
663 }
664 }
665
666 pub(crate) fn remote_status(&self) -> Option<PathStatus> {
667 self.status.remote_status.map(|(_seq, status)| status)
668 }
669
670 pub(crate) fn local_status(&self) -> PathStatus {
671 self.status.local_status
672 }
673
674 /// Tag uniquely identifying a path in a connection.
675 ///
676 /// When a migration happens on the same [`PathId`] we still detect a change in the
677 /// 4-tuple and generate a new [`PathData`] for it. Each such generation has a unique
678 /// value to keep track of which 4-tuple a packet belonged to.
679 pub(super) fn generation(&self) -> u64 {
680 self.generation
681 }
682}
683
684pub(super) enum OnPathResponseReceived {
685 /// This response validates the path on its current remote address.
686 OnPath { was_open: bool },
687 /// This response is valid, but it's for a remote other than the path's current remote address.
688 OffPath,
689 /// The received token is unknown.
690 Unknown,
691 /// The response is valid but it's not usable for path validation.
692 Ignored {
693 sent_on: FourTuple,
694 current_path: FourTuple,
695 },
696}
697
698#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
699pub(super) enum OpenStatus {
700 /// A first packet has not been sent using this [`PathId`].
701 #[default]
702 Pending,
703 /// The first packet has been sent using this [`PathId`]. However, it is not yet deemed good
704 /// enough to be reported to the application.
705 Sent,
706 /// The application has been informed of this path.
707 Informed,
708 /// The path was [`Self::Informed`] before, but we want to trigger path validation again.
709 ///
710 /// This is used to ensure we properly stop trying to re-send path challenges eventually, without
711 /// having to switch to [`Self::Pending`] when re-validating, as that would trigger another
712 /// application-level event about the path opening once validation succeeds.
713 Revalidating,
714}
715
716/// Congestion metrics as described in [`recovery_metrics_updated`].
717///
718/// [`recovery_metrics_updated`]: https://datatracker.ietf.org/doc/html/draft-ietf-quic-qlog-quic-events.html#name-recovery_metrics_updated
719#[cfg(feature = "qlog")]
720#[derive(Default, Clone, PartialEq, Debug)]
721#[non_exhaustive]
722struct RecoveryMetrics {
723 pub min_rtt: Option<Duration>,
724 pub smoothed_rtt: Option<Duration>,
725 pub latest_rtt: Option<Duration>,
726 pub rtt_variance: Option<Duration>,
727 pub pto_count: Option<u32>,
728 pub bytes_in_flight: Option<u64>,
729 pub packets_in_flight: Option<u64>,
730 pub congestion_window: Option<u64>,
731 pub ssthresh: Option<u64>,
732 pub pacing_rate: Option<u64>,
733}
734
735#[cfg(feature = "qlog")]
736impl RecoveryMetrics {
737 /// Retain only values that have been updated since the last snapshot.
738 fn retain_updated(&self, previous: &Self) -> Self {
739 macro_rules! keep_if_changed {
740 ($name:ident) => {
741 if previous.$name == self.$name {
742 None
743 } else {
744 self.$name
745 }
746 };
747 }
748
749 Self {
750 min_rtt: keep_if_changed!(min_rtt),
751 smoothed_rtt: keep_if_changed!(smoothed_rtt),
752 latest_rtt: keep_if_changed!(latest_rtt),
753 rtt_variance: keep_if_changed!(rtt_variance),
754 pto_count: keep_if_changed!(pto_count),
755 bytes_in_flight: keep_if_changed!(bytes_in_flight),
756 packets_in_flight: keep_if_changed!(packets_in_flight),
757 congestion_window: keep_if_changed!(congestion_window),
758 ssthresh: keep_if_changed!(ssthresh),
759 pacing_rate: keep_if_changed!(pacing_rate),
760 }
761 }
762
763 /// Emit a `MetricsUpdated` event containing only updated values
764 fn to_qlog_event(&self, path_id: PathId, previous: &Self) -> Option<RecoveryMetricsUpdated> {
765 let updated = self.retain_updated(previous);
766
767 if updated == Self::default() {
768 return None;
769 }
770
771 Some(RecoveryMetricsUpdated {
772 min_rtt: updated.min_rtt.map(|rtt| rtt.as_secs_f32()),
773 smoothed_rtt: updated.smoothed_rtt.map(|rtt| rtt.as_secs_f32()),
774 latest_rtt: updated.latest_rtt.map(|rtt| rtt.as_secs_f32()),
775 rtt_variance: updated.rtt_variance.map(|rtt| rtt.as_secs_f32()),
776 pto_count: updated
777 .pto_count
778 .map(|count| count.try_into().unwrap_or(u16::MAX)),
779 bytes_in_flight: updated.bytes_in_flight,
780 packets_in_flight: updated.packets_in_flight,
781 congestion_window: updated.congestion_window,
782 ssthresh: updated.ssthresh,
783 pacing_rate: updated.pacing_rate,
784 path_id: Some(path_id.as_u32() as u64),
785 })
786 }
787}
788
789/// RTT estimation for a particular network path
790#[derive(Copy, Clone, Debug)]
791pub struct RttEstimator {
792 /// The most recent RTT measurement made when receiving an ack for a previously unacked packet
793 latest: Duration,
794 /// The smoothed RTT of the connection, computed as described in RFC6298
795 smoothed: Option<Duration>,
796 /// The RTT variance, computed as described in RFC6298
797 var: Duration,
798 /// The minimum RTT seen in the connection, ignoring ack delay.
799 min: Duration,
800}
801
802impl RttEstimator {
803 pub(super) fn new(initial_rtt: Duration) -> Self {
804 Self {
805 latest: initial_rtt,
806 smoothed: None,
807 var: initial_rtt / 2,
808 min: initial_rtt,
809 }
810 }
811
812 /// Resets the estimator using a new initial_rtt value.
813 ///
814 /// This only resets the initial_rtt **if** no samples have been recorded yet. If there
815 /// are any recorded samples the initial estimate can not be adjusted after the fact.
816 ///
817 /// This is useful when you receive a PATH_RESPONSE in the first packet received on a
818 /// new path. In this case you can use the delay of the PATH_CHALLENGE-PATH_RESPONSE as
819 /// the initial RTT to get a better expected estimation.
820 ///
821 /// A PATH_CHALLENGE-PATH_RESPONSE pair later in the connection should not be used
822 /// explicitly as an estimation since PATH_CHALLENGE is an ACK-eliciting packet itself
823 /// already.
824 pub(crate) fn reset_initial_rtt(&mut self, initial_rtt: Duration) {
825 if self.smoothed.is_none() {
826 self.latest = initial_rtt;
827 self.var = initial_rtt / 2;
828 self.min = initial_rtt;
829 }
830 }
831
832 /// The current best RTT estimation.
833 pub fn get(&self) -> Duration {
834 self.smoothed.unwrap_or(self.latest)
835 }
836
837 /// Conservative estimate of RTT
838 ///
839 /// Takes the maximum of smoothed and latest RTT, as recommended
840 /// in 6.1.2 of the recovery spec (draft 29).
841 pub fn conservative(&self) -> Duration {
842 self.get().max(self.latest)
843 }
844
845 /// Minimum RTT registered so far for this estimator.
846 pub fn min(&self) -> Duration {
847 self.min
848 }
849
850 /// PTO computed as described in RFC9002#6.2.1.
851 pub(crate) fn pto_base(&self) -> Duration {
852 self.get() + cmp::max(4 * self.var, TIMER_GRANULARITY)
853 }
854
855 /// Records an RTT sample.
856 pub(crate) fn update(&mut self, ack_delay: Duration, rtt: Duration) {
857 self.latest = rtt;
858 // https://www.rfc-editor.org/rfc/rfc9002.html#section-5.2-3:
859 // min_rtt does not adjust for ack_delay to avoid underestimating.
860 self.min = cmp::min(self.min, self.latest);
861 // Based on RFC6298.
862 if let Some(smoothed) = self.smoothed {
863 let adjusted_rtt = if self.min + ack_delay <= self.latest {
864 self.latest - ack_delay
865 } else {
866 self.latest
867 };
868 let var_sample = smoothed.abs_diff(adjusted_rtt);
869 self.var = (3 * self.var + var_sample) / 4;
870 self.smoothed = Some((7 * smoothed + adjusted_rtt) / 8);
871 } else {
872 self.smoothed = Some(self.latest);
873 self.var = self.latest / 2;
874 self.min = self.latest;
875 }
876 }
877}
878
879#[derive(Default, Debug)]
880pub(crate) struct PathResponses {
881 pending: Vec<PathResponse>,
882}
883
884impl PathResponses {
885 pub(crate) fn push(&mut self, packet: u64, token: u64, network_path: FourTuple) {
886 /// Arbitrary permissive limit to prevent abuse
887 const MAX_PATH_RESPONSES: usize = 16;
888 let response = PathResponse {
889 packet,
890 token,
891 network_path,
892 };
893 let existing = self
894 .pending
895 .iter_mut()
896 .find(|x| x.network_path.remote == network_path.remote);
897 if let Some(existing) = existing {
898 // Update a queued response
899 if existing.packet <= packet {
900 *existing = response;
901 }
902 return;
903 }
904 if self.pending.len() < MAX_PATH_RESPONSES {
905 self.pending.push(response);
906 } else {
907 // We don't expect to ever hit this with well-behaved peers, so we don't bother dropping
908 // older challenges.
909 trace!("ignoring excessive PATH_CHALLENGE");
910 }
911 }
912
913 pub(crate) fn pop_off_path(&mut self, network_path: FourTuple) -> Option<(u64, FourTuple)> {
914 let response = *self.pending.last()?;
915 // We use an exact comparison here, because once we've received for the first time,
916 // we really should either already have a local_ip, or we will never get one
917 // (because our OS doesn't support it).
918 if response.network_path == network_path {
919 // We don't bother searching further because we expect that the on-path response will
920 // get drained in the immediate future by a call to `pop_on_path`
921 return None;
922 }
923 self.pending.pop();
924 Some((response.token, response.network_path))
925 }
926
927 pub(crate) fn pop_on_path(&mut self, network_path: FourTuple) -> Option<u64> {
928 let response = *self.pending.last()?;
929 // Using an exact comparison. See explanation in `pop_off_path`.
930 if response.network_path != network_path {
931 // We don't bother searching further because we expect that the off-path response will
932 // get drained in the immediate future by a call to `pop_off_path`
933 return None;
934 }
935 self.pending.pop();
936 Some(response.token)
937 }
938
939 pub(crate) fn is_empty(&self) -> bool {
940 self.pending.is_empty()
941 }
942}
943
944#[derive(Copy, Clone, Debug)]
945struct PathResponse {
946 /// The packet number the corresponding PATH_CHALLENGE was received in
947 packet: u64,
948 /// The token of the PATH_CHALLENGE
949 token: u64,
950 /// The path the corresponding PATH_CHALLENGE was received from
951 network_path: FourTuple,
952}
953
954/// Summary statistics of packets that have been sent on a particular path, but which have not yet
955/// been acked or deemed lost
956#[derive(Debug)]
957pub(super) struct InFlight {
958 /// Sum of the sizes of all sent packets considered "in flight" by congestion control
959 ///
960 /// The size does not include IP or UDP overhead. Packets only containing ACK frames do not
961 /// count towards this to ensure congestion control does not impede congestion feedback.
962 pub(super) bytes: u64,
963 /// Number of packets in flight containing frames other than ACK and PADDING
964 ///
965 /// This can be 0 even when bytes is not 0 because PADDING frames cause a packet to be
966 /// considered "in flight" by congestion control. However, if this is nonzero, bytes will always
967 /// also be nonzero.
968 pub(super) ack_eliciting: u64,
969}
970
971impl InFlight {
972 fn new() -> Self {
973 Self {
974 bytes: 0,
975 ack_eliciting: 0,
976 }
977 }
978
979 fn insert(&mut self, packet: &SentPacket) {
980 self.bytes += u64::from(packet.size);
981 self.ack_eliciting += u64::from(packet.ack_eliciting);
982 }
983
984 /// Update counters to account for a packet becoming acknowledged, lost, or abandoned
985 fn remove(&mut self, packet: &SentPacket) {
986 self.bytes -= u64::from(packet.size);
987 self.ack_eliciting -= u64::from(packet.ack_eliciting);
988 }
989}
990
991/// State for QUIC-MULTIPATH PATH_STATUS_AVAILABLE and PATH_STATUS_BACKUP frames
992#[derive(Debug, Clone, Default)]
993pub(super) struct PathStatusState {
994 /// The local status
995 local_status: PathStatus,
996 /// Local sequence number, for both PATH_STATUS_AVAILABLE and PATH_STATUS_BACKUP
997 ///
998 /// This is the number of the *next* path status frame to be sent.
999 local_seq: VarInt,
1000 /// The status set by the remote
1001 remote_status: Option<(VarInt, PathStatus)>,
1002}
1003
1004impl PathStatusState {
1005 /// To be called on received PATH_STATUS_AVAILABLE/PATH_STATUS_BACKUP frames
1006 pub(super) fn remote_update(&mut self, status: PathStatus, seq: VarInt) {
1007 if self.remote_status.is_some_and(|(curr, _)| curr >= seq) {
1008 return trace!(%seq, "ignoring path status update");
1009 }
1010
1011 let prev = self.remote_status.replace((seq, status)).map(|(_, s)| s);
1012 if prev != Some(status) {
1013 debug!(?status, ?seq, "remote changed path status");
1014 }
1015 }
1016
1017 /// Updates the local status
1018 ///
1019 /// If the local status changed, the previous value is returned
1020 pub(super) fn local_update(&mut self, status: PathStatus) -> Option<PathStatus> {
1021 if self.local_status == status {
1022 return None;
1023 }
1024
1025 self.local_seq = self.local_seq.saturating_add(1u8);
1026 Some(std::mem::replace(&mut self.local_status, status))
1027 }
1028
1029 pub(crate) fn seq(&self) -> VarInt {
1030 self.local_seq
1031 }
1032}
1033
1034/// The QUIC-MULTIPATH path status
1035///
1036/// See section "3.3 Path Status Management":
1037/// <https://quicwg.org/multipath/draft-ietf-quic-multipath.html#name-path-status-management>
1038#[cfg_attr(test, derive(test_strategy::Arbitrary))]
1039#[derive(Debug, Copy, Clone, Default, PartialEq, Eq)]
1040pub enum PathStatus {
1041 /// Paths marked with as available will be used when scheduling packets
1042 ///
1043 /// If multiple paths are available, packets will be scheduled on whichever has
1044 /// capacity.
1045 #[default]
1046 Available,
1047 /// Paths marked as backup will only be used if there are no available paths
1048 ///
1049 /// If the max_idle_timeout is specified the path will be kept alive so that it does not
1050 /// expire.
1051 Backup,
1052}
1053
1054/// Application events about paths
1055#[derive(Debug, Clone, PartialEq, Eq)]
1056pub enum PathEvent {
1057 /// A new path has been opened
1058 Opened {
1059 /// Which path is now open
1060 id: PathId,
1061 },
1062 /// A path was abandoned and is no longer usable.
1063 ///
1064 /// This event will always be followed by [`Self::Discarded`] after some time.
1065 Abandoned {
1066 /// With path was abandoned.
1067 id: PathId,
1068 /// Reason why this path was abandoned.
1069 reason: PathAbandonReason,
1070 },
1071 /// A path was discarded and all remaining state for it has been removed.
1072 ///
1073 /// This event is the last event for a path, and is always emitted after [`Self::Abandoned`].
1074 Discarded {
1075 /// Which path had its state dropped
1076 id: PathId,
1077 /// The final path stats, they are no longer available via [`Connection::stats`]
1078 ///
1079 /// [`Connection::stats`]: super::Connection::stats
1080 path_stats: Box<PathStats>,
1081 },
1082 /// The remote changed the status of the path
1083 ///
1084 /// The local status is not changed because of this event. It is up to the application
1085 /// to update the local status, which is used for packet scheduling, when the remote
1086 /// changes the status.
1087 RemoteStatus {
1088 /// Path which has changed status
1089 id: PathId,
1090 /// The new status set by the remote
1091 status: PathStatus,
1092 },
1093 /// Received an observation of our external address from the peer.
1094 ObservedAddr {
1095 /// Path over which the observed address was reported, [`PathId::ZERO`] when multipath is
1096 /// not negotiated
1097 id: PathId,
1098 /// The address observed by the remote over this path
1099 addr: SocketAddr,
1100 },
1101}
1102
1103/// Reason for why a path was abandoned.
1104#[derive(Debug, Clone, Eq, PartialEq)]
1105pub enum PathAbandonReason {
1106 /// The path was closed locally by the application.
1107 ApplicationClosed {
1108 /// The error code to be sent with the abandon frame.
1109 error_code: VarInt,
1110 },
1111 /// We didn't receive a path response in time after opening this path.
1112 ValidationFailed,
1113 /// We didn't receive any data from the remote within the path's idle timeout.
1114 TimedOut,
1115 /// The path became unusable after a local network change.
1116 UnusableAfterNetworkChange,
1117 /// The path was opened in a NAT traversal round which was terminated.
1118 NatTraversalRoundEnded,
1119 /// The remote closed the path.
1120 RemoteAbandoned {
1121 /// The error that was sent with the abandon frame.
1122 error_code: VarInt,
1123 },
1124}
1125
1126impl PathAbandonReason {
1127 /// Whether this abandon was initiated by the remote peer.
1128 pub(crate) fn is_remote(&self) -> bool {
1129 matches!(self, Self::RemoteAbandoned { .. })
1130 }
1131
1132 /// Returns the error code to send with a PATH_ABANDON frame.
1133 pub(crate) fn error_code(&self) -> TransportErrorCode {
1134 match self {
1135 Self::ApplicationClosed { error_code } => (*error_code).into(),
1136 Self::NatTraversalRoundEnded => TransportErrorCode::APPLICATION_ABANDON_PATH,
1137 Self::ValidationFailed | Self::TimedOut | Self::UnusableAfterNetworkChange => {
1138 TransportErrorCode::PATH_UNSTABLE_OR_POOR
1139 }
1140 Self::RemoteAbandoned { error_code } => (*error_code).into(),
1141 }
1142 }
1143}
1144
1145/// Error from setting path status
1146#[derive(Debug, Error, Clone, PartialEq, Eq)]
1147pub enum SetPathStatusError {
1148 /// Error indicating that a path has not been opened or has already been abandoned
1149 #[error("closed path")]
1150 ClosedPath,
1151 /// Error indicating that this operation requires multipath to be negotiated whereas it hasn't been
1152 #[error("multipath not negotiated")]
1153 MultipathNotNegotiated,
1154}
1155
1156/// Error indicating that a path has not been opened or has already been abandoned
1157#[derive(Debug, Default, Error, Clone, PartialEq, Eq)]
1158#[error("closed path")]
1159pub struct ClosedPath {
1160 pub(super) _private: (),
1161}
1162
1163#[cfg(test)]
1164mod tests {
1165 use super::*;
1166
1167 #[test]
1168 fn test_path_id_saturating_add() {
1169 // add within range behaves normally
1170 let large: PathId = u16::MAX.into();
1171 let next = u32::from(u16::MAX) + 1;
1172 assert_eq!(large.saturating_add(1u8), PathId::from(next));
1173
1174 // outside range saturates
1175 assert_eq!(PathId::MAX.saturating_add(1u8), PathId::MAX)
1176 }
1177}