iroh_quinn_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    PathError, PathStats,
9    mtud::MtuDiscovery,
10    pacing::Pacer,
11    spaces::{PacketNumberSpace, SentPacket},
12};
13use crate::{
14    ConnectionId, Duration, Instant, TIMER_GRANULARITY, TransportConfig, VarInt, coding,
15    congestion, frame::ObservedAddr, packet::SpaceId,
16};
17
18#[cfg(feature = "qlog")]
19use qlog::events::quic::RecoveryMetricsUpdated;
20
21/// Id representing different paths when using multipath extension
22#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Default)]
23pub struct PathId(pub(crate) u32);
24
25impl std::hash::Hash for PathId {
26    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
27        state.write_u32(self.0);
28    }
29}
30
31impl identity_hash::IdentityHashable for PathId {}
32
33impl coding::Codec for PathId {
34    fn decode<B: bytes::Buf>(r: &mut B) -> coding::Result<Self> {
35        let v = VarInt::decode(r)?;
36        let v = u32::try_from(v.0).map_err(|_| coding::UnexpectedEnd)?;
37        Ok(Self(v))
38    }
39
40    fn encode<B: bytes::BufMut>(&self, w: &mut B) {
41        VarInt(self.0.into()).encode(w)
42    }
43}
44
45impl PathId {
46    /// The maximum path ID allowed.
47    pub const MAX: Self = Self(u32::MAX);
48
49    /// The 0 path id.
50    pub const ZERO: Self = Self(0);
51
52    /// The number of bytes this [`PathId`] uses when encoded as a [`VarInt`]
53    pub(crate) const fn size(&self) -> usize {
54        VarInt(self.0 as u64).size()
55    }
56
57    /// Saturating integer addition. Computes self + rhs, saturating at the numeric bounds instead
58    /// of overflowing.
59    pub fn saturating_add(self, rhs: impl Into<Self>) -> Self {
60        let rhs = rhs.into();
61        let inner = self.0.saturating_add(rhs.0);
62        Self(inner)
63    }
64
65    /// Saturating integer subtraction. Computes self - rhs, saturating at the numeric bounds
66    /// instead of overflowing.
67    pub fn saturating_sub(self, rhs: impl Into<Self>) -> Self {
68        let rhs = rhs.into();
69        let inner = self.0.saturating_sub(rhs.0);
70        Self(inner)
71    }
72
73    /// Get the next [`PathId`]
74    pub(crate) fn next(&self) -> Self {
75        self.saturating_add(Self(1))
76    }
77
78    /// Get the underlying u32
79    pub(crate) fn as_u32(&self) -> u32 {
80        self.0
81    }
82}
83
84impl std::fmt::Display for PathId {
85    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
86        self.0.fmt(f)
87    }
88}
89
90impl<T: Into<u32>> From<T> for PathId {
91    fn from(source: T) -> Self {
92        Self(source.into())
93    }
94}
95
96/// State needed for a single path ID.
97///
98/// A single path ID can migrate according to the rules in RFC9000 §9, either voluntary or
99/// involuntary. We need to keep the [`PathData`] of the previously used such path available
100/// in order to defend against migration attacks (see RFC9000 §9.3.1, §9.3.2 and §9.3.3) as
101/// well as to support path probing (RFC9000 §9.1).
102#[derive(Debug)]
103pub(super) struct PathState {
104    pub(super) data: PathData,
105    pub(super) prev: Option<(ConnectionId, PathData)>,
106}
107
108impl PathState {
109    /// Update counters to account for a packet becoming acknowledged, lost, or abandoned
110    pub(super) fn remove_in_flight(&mut self, packet: &SentPacket) {
111        // Visit known paths from newest to oldest to find the one `pn` was sent on
112        for path_data in [&mut self.data]
113            .into_iter()
114            .chain(self.prev.as_mut().map(|(_, data)| data))
115        {
116            if path_data.remove_in_flight(packet) {
117                return;
118            }
119        }
120    }
121}
122
123#[derive(Debug)]
124pub(super) struct SentChallengeInfo {
125    /// When was the challenge sent on the wire.
126    pub(super) sent_instant: Instant,
127    /// The remote to which this path challenge was sent.
128    pub(super) remote: SocketAddr,
129}
130
131/// Description of a particular network path
132#[derive(Debug)]
133pub(super) struct PathData {
134    pub(super) remote: SocketAddr,
135    pub(super) rtt: RttEstimator,
136    /// Whether we're enabling ECN on outgoing packets
137    pub(super) sending_ecn: bool,
138    /// Congestion controller state
139    pub(super) congestion: Box<dyn congestion::Controller>,
140    /// Pacing state
141    pub(super) pacing: Pacer,
142    /// Actually sent challenges (on the wire).
143    pub(super) challenges_sent: IntMap<u64, SentChallengeInfo>,
144    /// Whether to *immediately* trigger another PATH_CHALLENGE (via [`super::Connection::can_send`])
145    pub(super) send_new_challenge: bool,
146    /// Pending responses to PATH_CHALLENGE frames
147    pub(super) path_responses: PathResponses,
148    /// Whether we're certain the peer can both send and receive on this address
149    ///
150    /// Initially equal to `use_stateless_retry` for servers, and becomes false again on every
151    /// migration. Always true for clients.
152    pub(super) validated: bool,
153    /// Total size of all UDP datagrams sent on this path
154    pub(super) total_sent: u64,
155    /// Total size of all UDP datagrams received on this path
156    pub(super) total_recvd: u64,
157    /// The state of the MTU discovery process
158    pub(super) mtud: MtuDiscovery,
159    /// Packet number of the first packet sent after an RTT sample was collected on this path
160    ///
161    /// Used in persistent congestion determination.
162    pub(super) first_packet_after_rtt_sample: Option<(SpaceId, u64)>,
163    /// The in-flight packets and bytes
164    ///
165    /// Note that this is across all spaces on this path
166    pub(super) in_flight: InFlight,
167    /// Whether this path has had it's remote address reported back to the peer. This only happens
168    /// if both peers agree to so based on their transport parameters.
169    pub(super) observed_addr_sent: bool,
170    /// Observed address frame with the largest sequence number received from the peer on this path.
171    pub(super) last_observed_addr_report: Option<ObservedAddr>,
172    /// The QUIC-MULTIPATH path status
173    pub(super) status: PathStatusState,
174    /// Number of the first packet sent on this path
175    ///
176    /// With RFC9000 §9 style migration (i.e. not multipath) the PathId does not change and
177    /// hence packet numbers continue. This is used to determine whether a packet was sent
178    /// on such an earlier path. Insufficient to determine if a packet was sent on a later
179    /// path.
180    first_packet: Option<u64>,
181    /// The number of times a PTO has been sent without receiving an ack.
182    pub(super) pto_count: u32,
183
184    //
185    // Per-path idle & keep alive
186    //
187    /// Idle timeout for the path
188    ///
189    /// If expired, the path will be abandoned.  This is different from the connection-wide
190    /// idle timeout which closes the connection if expired.
191    pub(super) idle_timeout: Option<Duration>,
192    /// Keep alives to send on this path
193    ///
194    /// There is also a connection-level keep alive configured in the
195    /// [`TransportParameters`].  This triggers activity on any path which can keep the
196    /// connection alive.
197    ///
198    /// [`TransportParameters`]: crate::transport_parameters::TransportParameters
199    pub(super) keep_alive: Option<Duration>,
200
201    /// Whether the path has already been considered opened from an application perspective
202    ///
203    /// This means, for paths other than the original [`PathId::ZERO`], a first path challenge has
204    /// been responded to, regardless of the initial validation status of the path. This state is
205    /// irreversible, since it's not affected by the path being closed.
206    pub(super) open: bool,
207
208    /// The time at which this path state should've received a PATH_ABANDON already.
209    ///
210    /// Receiving data on this path generates a transport error after that point in time.
211    /// This is checked in [`crate::Connection::on_packet_authenticated`].
212    ///
213    /// If set to `None`, then this path isn't abandoned yet and is allowed to receive data.
214    pub(super) last_allowed_receive: Option<Instant>,
215
216    /// Snapshot of the qlog recovery metrics
217    #[cfg(feature = "qlog")]
218    recovery_metrics: RecoveryMetrics,
219
220    /// Tag uniquely identifying a path in a connection
221    generation: u64,
222}
223
224impl PathData {
225    pub(super) fn new(
226        remote: SocketAddr,
227        allow_mtud: bool,
228        peer_max_udp_payload_size: Option<u16>,
229        generation: u64,
230        now: Instant,
231        config: &TransportConfig,
232    ) -> Self {
233        let congestion = config
234            .congestion_controller_factory
235            .clone()
236            .build(now, config.get_initial_mtu());
237        Self {
238            remote,
239            rtt: RttEstimator::new(config.initial_rtt),
240            sending_ecn: true,
241            pacing: Pacer::new(
242                config.initial_rtt,
243                congestion.initial_window(),
244                config.get_initial_mtu(),
245                now,
246            ),
247            congestion,
248            challenges_sent: Default::default(),
249            send_new_challenge: false,
250            path_responses: PathResponses::default(),
251            validated: false,
252            total_sent: 0,
253            total_recvd: 0,
254            mtud: config
255                .mtu_discovery_config
256                .as_ref()
257                .filter(|_| allow_mtud)
258                .map_or(
259                    MtuDiscovery::disabled(config.get_initial_mtu(), config.min_mtu),
260                    |mtud_config| {
261                        MtuDiscovery::new(
262                            config.get_initial_mtu(),
263                            config.min_mtu,
264                            peer_max_udp_payload_size,
265                            mtud_config.clone(),
266                        )
267                    },
268                ),
269            first_packet_after_rtt_sample: None,
270            in_flight: InFlight::new(),
271            observed_addr_sent: false,
272            last_observed_addr_report: None,
273            status: Default::default(),
274            first_packet: None,
275            pto_count: 0,
276            idle_timeout: None,
277            keep_alive: None,
278            open: false,
279            last_allowed_receive: None,
280            #[cfg(feature = "qlog")]
281            recovery_metrics: RecoveryMetrics::default(),
282            generation,
283        }
284    }
285
286    /// Create a new path from a previous one.
287    ///
288    /// This should only be called when migrating paths.
289    pub(super) fn from_previous(
290        remote: SocketAddr,
291        prev: &Self,
292        generation: u64,
293        now: Instant,
294    ) -> Self {
295        let congestion = prev.congestion.clone_box();
296        let smoothed_rtt = prev.rtt.get();
297        Self {
298            remote,
299            rtt: prev.rtt,
300            pacing: Pacer::new(smoothed_rtt, congestion.window(), prev.current_mtu(), now),
301            sending_ecn: true,
302            congestion,
303            challenges_sent: Default::default(),
304            send_new_challenge: false,
305            path_responses: PathResponses::default(),
306            validated: false,
307            total_sent: 0,
308            total_recvd: 0,
309            mtud: prev.mtud.clone(),
310            first_packet_after_rtt_sample: prev.first_packet_after_rtt_sample,
311            in_flight: InFlight::new(),
312            observed_addr_sent: false,
313            last_observed_addr_report: None,
314            status: prev.status.clone(),
315            first_packet: None,
316            pto_count: 0,
317            idle_timeout: prev.idle_timeout,
318            keep_alive: prev.keep_alive,
319            open: false,
320            last_allowed_receive: None,
321            #[cfg(feature = "qlog")]
322            recovery_metrics: prev.recovery_metrics.clone(),
323            generation,
324        }
325    }
326
327    /// Whether we're in the process of validating this path with PATH_CHALLENGEs
328    pub(super) fn is_validating_path(&self) -> bool {
329        !self.challenges_sent.is_empty() || self.send_new_challenge
330    }
331
332    /// Indicates whether we're a server that hasn't validated the peer's address and hasn't
333    /// received enough data from the peer to permit sending `bytes_to_send` additional bytes
334    pub(super) fn anti_amplification_blocked(&self, bytes_to_send: u64) -> bool {
335        !self.validated && self.total_recvd * 3 < self.total_sent + bytes_to_send
336    }
337
338    /// Returns the path's current MTU
339    pub(super) fn current_mtu(&self) -> u16 {
340        self.mtud.current_mtu()
341    }
342
343    /// Account for transmission of `packet` with number `pn` in `space`
344    pub(super) fn sent(&mut self, pn: u64, packet: SentPacket, space: &mut PacketNumberSpace) {
345        self.in_flight.insert(&packet);
346        if self.first_packet.is_none() {
347            self.first_packet = Some(pn);
348        }
349        if let Some(forgotten) = space.sent(pn, packet) {
350            self.remove_in_flight(&forgotten);
351        }
352    }
353
354    /// Remove `packet` with number `pn` from this path's congestion control counters, or return
355    /// `false` if `pn` was sent before this path was established.
356    pub(super) fn remove_in_flight(&mut self, packet: &SentPacket) -> bool {
357        if packet.path_generation != self.generation {
358            return false;
359        }
360        self.in_flight.remove(packet);
361        true
362    }
363
364    /// Increment the total size of sent UDP datagrams
365    pub(super) fn inc_total_sent(&mut self, inc: u64) {
366        self.total_sent = self.total_sent.saturating_add(inc);
367        if !self.validated {
368            trace!(
369                remote = %self.remote,
370                anti_amplification_budget = %(self.total_recvd * 3).saturating_sub(self.total_sent),
371                "anti amplification budget decreased"
372            );
373        }
374    }
375
376    /// Increment the total size of received UDP datagrams
377    pub(super) fn inc_total_recvd(&mut self, inc: u64) {
378        self.total_recvd = self.total_recvd.saturating_add(inc);
379        if !self.validated {
380            trace!(
381                remote = %self.remote,
382                anti_amplification_budget = %(self.total_recvd * 3).saturating_sub(self.total_sent),
383                "anti amplification budget increased"
384            );
385        }
386    }
387
388    /// The earliest time at which a sent challenge is considered lost.
389    pub(super) fn earliest_expiring_challenge(&self) -> Option<Instant> {
390        if self.challenges_sent.is_empty() {
391            return None;
392        }
393        let pto = self.rtt.pto_base();
394        self.challenges_sent
395            .values()
396            .map(|info| info.sent_instant)
397            .min()
398            .map(|sent_instant| sent_instant + pto)
399    }
400
401    /// Handle receiving a PATH_RESPONSE.
402    pub(super) fn on_path_response_received(
403        &mut self,
404        now: Instant,
405        token: u64,
406        remote: SocketAddr,
407    ) -> OnPathResponseReceived {
408        match self.challenges_sent.get(&token) {
409            // Response to an on-path PathChallenge
410            Some(info) if info.remote == remote && self.remote == remote => {
411                let sent_instant = info.sent_instant;
412                if !std::mem::replace(&mut self.validated, true) {
413                    trace!("new path validated");
414                }
415                // Clear any other on-path sent challenge.
416                self.challenges_sent
417                    .retain(|_token, info| info.remote != remote);
418
419                self.send_new_challenge = false;
420
421                // This RTT can only be used for the initial RTT, not as a normal
422                // sample: https://www.rfc-editor.org/rfc/rfc9002#section-6.2.2-2.
423                let rtt = now.saturating_duration_since(sent_instant);
424                self.rtt.reset_initial_rtt(rtt);
425
426                let was_open = std::mem::replace(&mut self.open, true);
427                OnPathResponseReceived::OnPath { was_open }
428            }
429            // Response to an off-path PathChallenge
430            Some(info) if info.remote == remote => {
431                self.challenges_sent
432                    .retain(|_token, info| info.remote != remote);
433                OnPathResponseReceived::OffPath
434            }
435            // Response to a PathChallenge we recognize, but from an invalid remote
436            Some(info) => OnPathResponseReceived::Invalid {
437                expected: info.remote,
438            },
439            // Response to an unknown PathChallenge
440            None => OnPathResponseReceived::Unknown,
441        }
442    }
443
444    #[cfg(feature = "qlog")]
445    pub(super) fn qlog_recovery_metrics(
446        &mut self,
447        path_id: PathId,
448    ) -> Option<RecoveryMetricsUpdated> {
449        let controller_metrics = self.congestion.metrics();
450
451        let metrics = RecoveryMetrics {
452            min_rtt: Some(self.rtt.min),
453            smoothed_rtt: Some(self.rtt.get()),
454            latest_rtt: Some(self.rtt.latest),
455            rtt_variance: Some(self.rtt.var),
456            pto_count: Some(self.pto_count),
457            bytes_in_flight: Some(self.in_flight.bytes),
458            packets_in_flight: Some(self.in_flight.ack_eliciting),
459
460            congestion_window: Some(controller_metrics.congestion_window),
461            ssthresh: controller_metrics.ssthresh,
462            pacing_rate: controller_metrics.pacing_rate,
463        };
464
465        let event = metrics.to_qlog_event(path_id, &self.recovery_metrics);
466        self.recovery_metrics = metrics;
467        event
468    }
469
470    /// Return how long we need to wait before sending `bytes_to_send`
471    ///
472    /// See [`Pacer::delay`].
473    pub(super) fn pacing_delay(&mut self, bytes_to_send: u64, now: Instant) -> Option<Instant> {
474        let smoothed_rtt = self.rtt.get();
475        self.pacing.delay(
476            smoothed_rtt,
477            bytes_to_send,
478            self.current_mtu(),
479            self.congestion.window(),
480            now,
481        )
482    }
483
484    /// Updates the last observed address report received on this path.
485    ///
486    /// If the address was updated, it's returned to be informed to the application.
487    #[must_use = "updated observed address must be reported to the application"]
488    pub(super) fn update_observed_addr_report(
489        &mut self,
490        observed: ObservedAddr,
491    ) -> Option<SocketAddr> {
492        match self.last_observed_addr_report.as_mut() {
493            Some(prev) => {
494                if prev.seq_no >= observed.seq_no {
495                    // frames that do not increase the sequence number on this path are ignored
496                    None
497                } else if prev.ip == observed.ip && prev.port == observed.port {
498                    // keep track of the last seq_no but do not report the address as updated
499                    prev.seq_no = observed.seq_no;
500                    None
501                } else {
502                    let addr = observed.socket_addr();
503                    self.last_observed_addr_report = Some(observed);
504                    Some(addr)
505                }
506            }
507            None => {
508                let addr = observed.socket_addr();
509                self.last_observed_addr_report = Some(observed);
510                Some(addr)
511            }
512        }
513    }
514
515    pub(crate) fn remote_status(&self) -> Option<PathStatus> {
516        self.status.remote_status.map(|(_seq, status)| status)
517    }
518
519    pub(crate) fn local_status(&self) -> PathStatus {
520        self.status.local_status
521    }
522
523    pub(super) fn generation(&self) -> u64 {
524        self.generation
525    }
526}
527
528pub(super) enum OnPathResponseReceived {
529    /// This response validates the path on its current remote address.
530    OnPath { was_open: bool },
531    /// This response is valid, but it's for a remote other than the path's current remote address.
532    OffPath,
533    /// The received token is unknown.
534    Unknown,
535    /// The response is invalid.
536    Invalid {
537        /// The remote that was expected for this token.
538        expected: SocketAddr,
539    },
540}
541
542/// Congestion metrics as described in [`recovery_metrics_updated`].
543///
544/// [`recovery_metrics_updated`]: https://datatracker.ietf.org/doc/html/draft-ietf-quic-qlog-quic-events.html#name-recovery_metrics_updated
545#[cfg(feature = "qlog")]
546#[derive(Default, Clone, PartialEq, Debug)]
547#[non_exhaustive]
548struct RecoveryMetrics {
549    pub min_rtt: Option<Duration>,
550    pub smoothed_rtt: Option<Duration>,
551    pub latest_rtt: Option<Duration>,
552    pub rtt_variance: Option<Duration>,
553    pub pto_count: Option<u32>,
554    pub bytes_in_flight: Option<u64>,
555    pub packets_in_flight: Option<u64>,
556    pub congestion_window: Option<u64>,
557    pub ssthresh: Option<u64>,
558    pub pacing_rate: Option<u64>,
559}
560
561#[cfg(feature = "qlog")]
562impl RecoveryMetrics {
563    /// Retain only values that have been updated since the last snapshot.
564    fn retain_updated(&self, previous: &Self) -> Self {
565        macro_rules! keep_if_changed {
566            ($name:ident) => {
567                if previous.$name == self.$name {
568                    None
569                } else {
570                    self.$name
571                }
572            };
573        }
574
575        Self {
576            min_rtt: keep_if_changed!(min_rtt),
577            smoothed_rtt: keep_if_changed!(smoothed_rtt),
578            latest_rtt: keep_if_changed!(latest_rtt),
579            rtt_variance: keep_if_changed!(rtt_variance),
580            pto_count: keep_if_changed!(pto_count),
581            bytes_in_flight: keep_if_changed!(bytes_in_flight),
582            packets_in_flight: keep_if_changed!(packets_in_flight),
583            congestion_window: keep_if_changed!(congestion_window),
584            ssthresh: keep_if_changed!(ssthresh),
585            pacing_rate: keep_if_changed!(pacing_rate),
586        }
587    }
588
589    /// Emit a `MetricsUpdated` event containing only updated values
590    fn to_qlog_event(&self, path_id: PathId, previous: &Self) -> Option<RecoveryMetricsUpdated> {
591        let updated = self.retain_updated(previous);
592
593        if updated == Self::default() {
594            return None;
595        }
596
597        Some(RecoveryMetricsUpdated {
598            min_rtt: updated.min_rtt.map(|rtt| rtt.as_secs_f32()),
599            smoothed_rtt: updated.smoothed_rtt.map(|rtt| rtt.as_secs_f32()),
600            latest_rtt: updated.latest_rtt.map(|rtt| rtt.as_secs_f32()),
601            rtt_variance: updated.rtt_variance.map(|rtt| rtt.as_secs_f32()),
602            pto_count: updated
603                .pto_count
604                .map(|count| count.try_into().unwrap_or(u16::MAX)),
605            bytes_in_flight: updated.bytes_in_flight,
606            packets_in_flight: updated.packets_in_flight,
607            congestion_window: updated.congestion_window,
608            ssthresh: updated.ssthresh,
609            pacing_rate: updated.pacing_rate,
610            path_id: Some(path_id.as_u32() as u64),
611        })
612    }
613}
614
615/// RTT estimation for a particular network path
616#[derive(Copy, Clone, Debug)]
617pub struct RttEstimator {
618    /// The most recent RTT measurement made when receiving an ack for a previously unacked packet
619    latest: Duration,
620    /// The smoothed RTT of the connection, computed as described in RFC6298
621    smoothed: Option<Duration>,
622    /// The RTT variance, computed as described in RFC6298
623    var: Duration,
624    /// The minimum RTT seen in the connection, ignoring ack delay.
625    min: Duration,
626}
627
628impl RttEstimator {
629    pub(super) fn new(initial_rtt: Duration) -> Self {
630        Self {
631            latest: initial_rtt,
632            smoothed: None,
633            var: initial_rtt / 2,
634            min: initial_rtt,
635        }
636    }
637
638    /// Resets the estimator using a new initial_rtt value.
639    ///
640    /// This only resets the initial_rtt **if** no samples have been recorded yet. If there
641    /// are any recorded samples the initial estimate can not be adjusted after the fact.
642    ///
643    /// This is useful when you receive a PATH_RESPONSE in the first packet received on a
644    /// new path. In this case you can use the delay of the PATH_CHALLENGE-PATH_RESPONSE as
645    /// the initial RTT to get a better expected estimation.
646    ///
647    /// A PATH_CHALLENGE-PATH_RESPONSE pair later in the connection should not be used
648    /// explicitly as an estimation since PATH_CHALLENGE is an ACK-eliciting packet itself
649    /// already.
650    pub(crate) fn reset_initial_rtt(&mut self, initial_rtt: Duration) {
651        if self.smoothed.is_none() {
652            self.latest = initial_rtt;
653            self.var = initial_rtt / 2;
654            self.min = initial_rtt;
655        }
656    }
657
658    /// The current best RTT estimation.
659    pub fn get(&self) -> Duration {
660        self.smoothed.unwrap_or(self.latest)
661    }
662
663    /// Conservative estimate of RTT
664    ///
665    /// Takes the maximum of smoothed and latest RTT, as recommended
666    /// in 6.1.2 of the recovery spec (draft 29).
667    pub fn conservative(&self) -> Duration {
668        self.get().max(self.latest)
669    }
670
671    /// Minimum RTT registered so far for this estimator.
672    pub fn min(&self) -> Duration {
673        self.min
674    }
675
676    /// PTO computed as described in RFC9002#6.2.1.
677    pub(crate) fn pto_base(&self) -> Duration {
678        self.get() + cmp::max(4 * self.var, TIMER_GRANULARITY)
679    }
680
681    /// Records an RTT sample.
682    pub(crate) fn update(&mut self, ack_delay: Duration, rtt: Duration) {
683        self.latest = rtt;
684        // https://www.rfc-editor.org/rfc/rfc9002.html#section-5.2-3:
685        // min_rtt does not adjust for ack_delay to avoid underestimating.
686        self.min = cmp::min(self.min, self.latest);
687        // Based on RFC6298.
688        if let Some(smoothed) = self.smoothed {
689            let adjusted_rtt = if self.min + ack_delay <= self.latest {
690                self.latest - ack_delay
691            } else {
692                self.latest
693            };
694            let var_sample = smoothed.abs_diff(adjusted_rtt);
695            self.var = (3 * self.var + var_sample) / 4;
696            self.smoothed = Some((7 * smoothed + adjusted_rtt) / 8);
697        } else {
698            self.smoothed = Some(self.latest);
699            self.var = self.latest / 2;
700            self.min = self.latest;
701        }
702    }
703}
704
705#[derive(Default, Debug)]
706pub(crate) struct PathResponses {
707    pending: Vec<PathResponse>,
708}
709
710impl PathResponses {
711    pub(crate) fn push(&mut self, packet: u64, token: u64, remote: SocketAddr) {
712        /// Arbitrary permissive limit to prevent abuse
713        const MAX_PATH_RESPONSES: usize = 16;
714        let response = PathResponse {
715            packet,
716            token,
717            remote,
718        };
719        let existing = self.pending.iter_mut().find(|x| x.remote == remote);
720        if let Some(existing) = existing {
721            // Update a queued response
722            if existing.packet <= packet {
723                *existing = response;
724            }
725            return;
726        }
727        if self.pending.len() < MAX_PATH_RESPONSES {
728            self.pending.push(response);
729        } else {
730            // We don't expect to ever hit this with well-behaved peers, so we don't bother dropping
731            // older challenges.
732            trace!("ignoring excessive PATH_CHALLENGE");
733        }
734    }
735
736    pub(crate) fn pop_off_path(&mut self, remote: SocketAddr) -> Option<(u64, SocketAddr)> {
737        let response = *self.pending.last()?;
738        if response.remote == remote {
739            // We don't bother searching further because we expect that the on-path response will
740            // get drained in the immediate future by a call to `pop_on_path`
741            return None;
742        }
743        self.pending.pop();
744        Some((response.token, response.remote))
745    }
746
747    pub(crate) fn pop_on_path(&mut self, remote: SocketAddr) -> Option<u64> {
748        let response = *self.pending.last()?;
749        if response.remote != remote {
750            // We don't bother searching further because we expect that the off-path response will
751            // get drained in the immediate future by a call to `pop_off_path`
752            return None;
753        }
754        self.pending.pop();
755        Some(response.token)
756    }
757
758    pub(crate) fn is_empty(&self) -> bool {
759        self.pending.is_empty()
760    }
761}
762
763#[derive(Copy, Clone, Debug)]
764struct PathResponse {
765    /// The packet number the corresponding PATH_CHALLENGE was received in
766    packet: u64,
767    /// The token of the PATH_CHALLENGE
768    token: u64,
769    /// The address the corresponding PATH_CHALLENGE was received from
770    remote: SocketAddr,
771}
772
773/// Summary statistics of packets that have been sent on a particular path, but which have not yet
774/// been acked or deemed lost
775#[derive(Debug)]
776pub(super) struct InFlight {
777    /// Sum of the sizes of all sent packets considered "in flight" by congestion control
778    ///
779    /// The size does not include IP or UDP overhead. Packets only containing ACK frames do not
780    /// count towards this to ensure congestion control does not impede congestion feedback.
781    pub(super) bytes: u64,
782    /// Number of packets in flight containing frames other than ACK and PADDING
783    ///
784    /// This can be 0 even when bytes is not 0 because PADDING frames cause a packet to be
785    /// considered "in flight" by congestion control. However, if this is nonzero, bytes will always
786    /// also be nonzero.
787    pub(super) ack_eliciting: u64,
788}
789
790impl InFlight {
791    fn new() -> Self {
792        Self {
793            bytes: 0,
794            ack_eliciting: 0,
795        }
796    }
797
798    fn insert(&mut self, packet: &SentPacket) {
799        self.bytes += u64::from(packet.size);
800        self.ack_eliciting += u64::from(packet.ack_eliciting);
801    }
802
803    /// Update counters to account for a packet becoming acknowledged, lost, or abandoned
804    fn remove(&mut self, packet: &SentPacket) {
805        self.bytes -= u64::from(packet.size);
806        self.ack_eliciting -= u64::from(packet.ack_eliciting);
807    }
808}
809
810/// State for QUIC-MULTIPATH PATH_STATUS_AVAILABLE and PATH_STATUS_BACKUP frames
811#[derive(Debug, Clone, Default)]
812pub(super) struct PathStatusState {
813    /// The local status
814    local_status: PathStatus,
815    /// Local sequence number, for both PATH_STATUS_AVAILABLE and PATH_STATUS_BACKUP
816    ///
817    /// This is the number of the *next* path status frame to be sent.
818    local_seq: VarInt,
819    /// The status set by the remote
820    remote_status: Option<(VarInt, PathStatus)>,
821}
822
823impl PathStatusState {
824    /// To be called on received PATH_STATUS_AVAILABLE/PATH_STATUS_BACKUP frames
825    pub(super) fn remote_update(&mut self, status: PathStatus, seq: VarInt) {
826        if self.remote_status.is_some_and(|(curr, _)| curr >= seq) {
827            return trace!(%seq, "ignoring path status update");
828        }
829
830        let prev = self.remote_status.replace((seq, status)).map(|(_, s)| s);
831        if prev != Some(status) {
832            debug!(?status, ?seq, "remote changed path status");
833        }
834    }
835
836    /// Updates the local status
837    ///
838    /// If the local status changed, the previous value is returned
839    pub(super) fn local_update(&mut self, status: PathStatus) -> Option<PathStatus> {
840        if self.local_status == status {
841            return None;
842        }
843
844        self.local_seq = self.local_seq.saturating_add(1u8);
845        Some(std::mem::replace(&mut self.local_status, status))
846    }
847
848    pub(crate) fn seq(&self) -> VarInt {
849        self.local_seq
850    }
851}
852
853/// The QUIC-MULTIPATH path status
854///
855/// See section "3.3 Path Status Management":
856/// <https://quicwg.org/multipath/draft-ietf-quic-multipath.html#name-path-status-management>
857#[derive(Debug, Copy, Clone, Default, PartialEq, Eq)]
858pub enum PathStatus {
859    /// Paths marked with as available will be used when scheduling packets
860    ///
861    /// If multiple paths are available, packets will be scheduled on whichever has
862    /// capacity.
863    #[default]
864    Available,
865    /// Paths marked as backup will only be used if there are no available paths
866    ///
867    /// If the max_idle_timeout is specified the path will be kept alive so that it does not
868    /// expire.
869    Backup,
870}
871
872/// Application events about paths
873#[derive(Debug, Clone, PartialEq, Eq)]
874pub enum PathEvent {
875    /// A new path has been opened
876    Opened {
877        /// Which path is now open
878        id: PathId,
879    },
880    /// A path has been closed
881    Closed {
882        /// Which path has been closed
883        id: PathId,
884        /// Error code supplied by the peer
885        /// See <https://www.ietf.org/archive/id/draft-ietf-quic-multipath-14.html#name-error-codes>
886        /// for a list of known errors.
887        error_code: VarInt,
888    },
889    /// All remaining state for a path has been removed
890    ///
891    /// The [`PathEvent::Closed`] would have been emitted for this path earlier.
892    Abandoned {
893        /// Which path had its state dropped
894        id: PathId,
895        /// The final path stats, they are no longer available via [`Connection::stats`]
896        ///
897        /// [`Connection::stats`]: super::Connection::stats
898        path_stats: PathStats,
899    },
900    /// Path was closed locally
901    LocallyClosed {
902        /// Path for which the error occurred
903        id: PathId,
904        /// The error that occurred
905        error: PathError,
906    },
907    /// The remote changed the status of the path
908    ///
909    /// The local status is not changed because of this event. It is up to the application
910    /// to update the local status, which is used for packet scheduling, when the remote
911    /// changes the status.
912    RemoteStatus {
913        /// Path which has changed status
914        id: PathId,
915        /// The new status set by the remote
916        status: PathStatus,
917    },
918    /// Received an observation of our external address from the peer.
919    ObservedAddr {
920        /// Path over which the observed address was reported, [`PathId::ZERO`] when multipath is
921        /// not negotiated
922        id: PathId,
923        /// The address observed by the remote over this path
924        addr: SocketAddr,
925    },
926}
927
928/// Error from setting path status
929#[derive(Debug, Error, Clone, PartialEq, Eq)]
930pub enum SetPathStatusError {
931    /// Error indicating that a path has not been opened or has already been abandoned
932    #[error("closed path")]
933    ClosedPath,
934    /// Error indicating that this operation requires multipath to be negotiated whereas it hasn't been
935    #[error("multipath not negotiated")]
936    MultipathNotNegotiated,
937}
938
939/// Error indicating that a path has not been opened or has already been abandoned
940#[derive(Debug, Default, Error, Clone, PartialEq, Eq)]
941#[error("closed path")]
942pub struct ClosedPath {
943    pub(super) _private: (),
944}
945
946#[cfg(test)]
947mod tests {
948    use super::*;
949
950    #[test]
951    fn test_path_id_saturating_add() {
952        // add within range behaves normally
953        let large: PathId = u16::MAX.into();
954        let next = u32::from(u16::MAX) + 1;
955        assert_eq!(large.saturating_add(1u8), PathId::from(next));
956
957        // outside range saturates
958        assert_eq!(PathId::MAX.saturating_add(1u8), PathId::MAX)
959    }
960}