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