Skip to main content

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            now,
612            &metrics,
613        )
614    }
615
616    /// Updates the last observed address report received on this path.
617    ///
618    /// If the address was updated, it's returned to be informed to the application.
619    #[must_use = "updated observed address must be reported to the application"]
620    pub(super) fn update_observed_addr_report(
621        &mut self,
622        observed: ObservedAddr,
623    ) -> Option<SocketAddr> {
624        match self.last_observed_addr_report.as_mut() {
625            Some(prev) => {
626                if prev.seq_no >= observed.seq_no {
627                    // frames that do not increase the sequence number on this path are ignored
628                    None
629                } else if prev.ip == observed.ip && prev.port == observed.port {
630                    // keep track of the last seq_no but do not report the address as updated
631                    prev.seq_no = observed.seq_no;
632                    None
633                } else {
634                    let addr = observed.socket_addr();
635                    self.last_observed_addr_report = Some(observed);
636                    Some(addr)
637                }
638            }
639            None => {
640                let addr = observed.socket_addr();
641                self.last_observed_addr_report = Some(observed);
642                Some(addr)
643            }
644        }
645    }
646
647    pub(crate) fn remote_status(&self) -> Option<PathStatus> {
648        self.status.remote_status.map(|(_seq, status)| status)
649    }
650
651    pub(crate) fn local_status(&self) -> PathStatus {
652        self.status.local_status
653    }
654
655    /// Tag uniquely identifying a path in a connection.
656    ///
657    /// When a migration happens on the same [`PathId`] we still detect a change in the
658    /// 4-tuple and generate a new [`PathData`] for it. Each such generation has a unique
659    /// value to keep track of which 4-tuple a packet belonged to.
660    pub(super) fn generation(&self) -> u64 {
661        self.generation
662    }
663}
664
665pub(super) enum OnPathResponseReceived {
666    /// This response validates the path on its current remote address.
667    OnPath,
668    /// The received token is unknown.
669    Unknown,
670    /// The response is valid but it's not usable for path validation.
671    Ignored {
672        sent_on: FourTuple,
673        current_path: FourTuple,
674    },
675}
676
677/// Congestion metrics as described in [`recovery_metrics_updated`].
678///
679/// [`recovery_metrics_updated`]: https://datatracker.ietf.org/doc/html/draft-ietf-quic-qlog-quic-events.html#name-recovery_metrics_updated
680#[cfg(feature = "qlog")]
681#[derive(Default, Clone, PartialEq, Debug)]
682#[non_exhaustive]
683struct RecoveryMetrics {
684    pub min_rtt: Option<Duration>,
685    pub smoothed_rtt: Option<Duration>,
686    pub latest_rtt: Option<Duration>,
687    pub rtt_variance: Option<Duration>,
688    pub pto_count: Option<u32>,
689    pub bytes_in_flight: Option<u64>,
690    pub packets_in_flight: Option<u64>,
691    pub congestion_window: Option<u64>,
692    pub ssthresh: Option<u64>,
693    pub pacing_rate: Option<u64>,
694}
695
696#[cfg(feature = "qlog")]
697impl RecoveryMetrics {
698    /// Retain only values that have been updated since the last snapshot.
699    fn retain_updated(&self, previous: &Self) -> Self {
700        macro_rules! keep_if_changed {
701            ($name:ident) => {
702                if previous.$name == self.$name {
703                    None
704                } else {
705                    self.$name
706                }
707            };
708        }
709
710        Self {
711            min_rtt: keep_if_changed!(min_rtt),
712            smoothed_rtt: keep_if_changed!(smoothed_rtt),
713            latest_rtt: keep_if_changed!(latest_rtt),
714            rtt_variance: keep_if_changed!(rtt_variance),
715            pto_count: keep_if_changed!(pto_count),
716            bytes_in_flight: keep_if_changed!(bytes_in_flight),
717            packets_in_flight: keep_if_changed!(packets_in_flight),
718            congestion_window: keep_if_changed!(congestion_window),
719            ssthresh: keep_if_changed!(ssthresh),
720            pacing_rate: keep_if_changed!(pacing_rate),
721        }
722    }
723
724    /// Emit a `MetricsUpdated` event containing only updated values
725    fn to_qlog_event(&self, path_id: PathId, previous: &Self) -> Option<RecoveryMetricsUpdated> {
726        let updated = self.retain_updated(previous);
727
728        if updated == Self::default() {
729            return None;
730        }
731
732        Some(RecoveryMetricsUpdated {
733            min_rtt: updated.min_rtt.map(|rtt| rtt.as_micros() as f32 / 1000.0),
734            smoothed_rtt: updated
735                .smoothed_rtt
736                .map(|rtt| rtt.as_micros() as f32 / 1000.0),
737            latest_rtt: updated
738                .latest_rtt
739                .map(|rtt| rtt.as_micros() as f32 / 1000.0),
740            rtt_variance: updated
741                .rtt_variance
742                .map(|rtt| rtt.as_micros() as f32 / 1000.0),
743            pto_count: updated
744                .pto_count
745                .map(|count| count.try_into().unwrap_or(u16::MAX)),
746            bytes_in_flight: updated.bytes_in_flight,
747            packets_in_flight: updated.packets_in_flight,
748            congestion_window: updated.congestion_window,
749            ssthresh: updated.ssthresh,
750            pacing_rate: updated.pacing_rate,
751            path_id: Some(path_id.as_u32() as u64),
752            ex_data: Default::default(),
753        })
754    }
755}
756
757/// RTT estimation for a particular network path
758#[derive(Copy, Clone, Debug)]
759pub struct RttEstimator {
760    /// The most recent RTT measurement made when receiving an ack for a previously unacked packet
761    latest: Duration,
762    /// The smoothed RTT of the connection, computed as described in RFC6298
763    smoothed: Option<Duration>,
764    /// The RTT variance, computed as described in RFC6298
765    var: Duration,
766    /// The minimum RTT seen in the connection, ignoring ack delay.
767    min: Duration,
768}
769
770impl RttEstimator {
771    pub(crate) fn new(initial_rtt: Duration) -> Self {
772        Self {
773            latest: initial_rtt,
774            smoothed: None,
775            var: initial_rtt / 2,
776            min: initial_rtt,
777        }
778    }
779
780    /// Resets the estimator using a new initial_rtt value.
781    ///
782    /// This only resets the initial_rtt **if** no samples have been recorded yet. If there
783    /// are any recorded samples the initial estimate can not be adjusted after the fact.
784    ///
785    /// This is useful when you receive a PATH_RESPONSE in the first packet received on a
786    /// new path. In this case you can use the delay of the PATH_CHALLENGE-PATH_RESPONSE as
787    /// the initial RTT to get a better expected estimation.
788    ///
789    /// A PATH_CHALLENGE-PATH_RESPONSE pair later in the connection should not be used
790    /// explicitly as an estimation since PATH_CHALLENGE is an ACK-eliciting packet itself
791    /// already.
792    pub(crate) fn reset_initial_rtt(&mut self, initial_rtt: Duration) {
793        if self.smoothed.is_none() {
794            self.latest = initial_rtt;
795            self.var = initial_rtt / 2;
796            self.min = initial_rtt;
797        }
798    }
799
800    /// The current best RTT estimation.
801    pub fn get(&self) -> Duration {
802        self.smoothed.unwrap_or(self.latest)
803    }
804
805    /// Conservative estimate of RTT
806    ///
807    /// Takes the maximum of smoothed and latest RTT, as recommended
808    /// in 6.1.2 of the recovery spec (draft 29).
809    pub fn conservative(&self) -> Duration {
810        self.get().max(self.latest)
811    }
812
813    /// Minimum RTT registered so far for this estimator.
814    pub fn min(&self) -> Duration {
815        self.min
816    }
817
818    /// PTO computed as described in RFC9002#6.2.1.
819    pub(crate) fn pto_base(&self) -> Duration {
820        self.get() + cmp::max(4 * self.var, TIMER_GRANULARITY)
821    }
822
823    /// Records an RTT sample.
824    pub(crate) fn update(&mut self, ack_delay: Duration, rtt: Duration) {
825        self.latest = rtt;
826        // https://www.rfc-editor.org/rfc/rfc9002.html#section-5.2-3:
827        // min_rtt does not adjust for ack_delay to avoid underestimating.
828        self.min = cmp::min(self.min, self.latest);
829        // Based on RFC6298.
830        if let Some(smoothed) = self.smoothed {
831            let adjusted_rtt = if self.min + ack_delay <= self.latest {
832                self.latest - ack_delay
833            } else {
834                self.latest
835            };
836            let var_sample = smoothed.abs_diff(adjusted_rtt);
837            self.var = (3 * self.var + var_sample) / 4;
838            self.smoothed = Some((7 * smoothed + adjusted_rtt) / 8);
839        } else {
840            self.smoothed = Some(self.latest);
841            self.var = self.latest / 2;
842            self.min = self.latest;
843        }
844    }
845}
846
847#[derive(Default, Debug)]
848pub(crate) struct PathResponses {
849    pending: Vec<PathResponse>,
850}
851
852impl PathResponses {
853    pub(crate) fn push(&mut self, packet: u64, token: u64, network_path: FourTuple) {
854        /// An arbitrary permissive limit to prevent abuse.
855        ///
856        /// If we've negotiated the n0 NAT Traversal extension, and one user might have a lot
857        /// of addresses, e.g. because of having lots of interfaces (we've seen >25 interfaces
858        /// on Macs with docker and other things), then we need to be able to process at least
859        /// as many PATH_CHALLENGE frames as there are interfaces.
860        /// On top of that, there are retries, which make it possible that we need to process
861        /// even more.
862        ///
863        /// Considering that there can be up to 2 `PathData`s per active `PathId`, and
864        /// reasonable default values for maximum concurrent multipath paths are ~8 and each
865        /// `PathResponse` struct takes up 72 bytes at the moment this, means an attacker can
866        /// cause us to keep `32 * 2 * 8 * 72 = ~37KB` of data around.
867        const MAX_PATH_RESPONSES: usize = 32;
868        let response = PathResponse {
869            packet,
870            token,
871            network_path,
872        };
873        let existing = self
874            .pending
875            .iter_mut()
876            .find(|x| x.network_path.remote == network_path.remote);
877        if let Some(existing) = existing {
878            // Update a queued response
879            if existing.packet <= packet {
880                *existing = response;
881            }
882            return;
883        }
884        if self.pending.len() < MAX_PATH_RESPONSES {
885            self.pending.push(response);
886        } else {
887            // We don't expect to ever hit this with well-behaved peers, so we don't bother dropping
888            // older challenges.
889            trace!("ignoring excessive PATH_CHALLENGE");
890        }
891    }
892
893    pub(crate) fn pop_off_path(&mut self, network_path: FourTuple) -> Option<(u64, FourTuple)> {
894        let response = *self.pending.last()?;
895        // We use an exact comparison here, because once we've received for the first time,
896        // we really should either already have a local_ip, or we will never get one
897        // (because our OS doesn't support it). And even if we get it wrong we are only
898        // slightly less efficient and would not include other on-path data in the packet.
899        if response.network_path == network_path {
900            // We don't bother searching further because we expect that the on-path response will
901            // get drained in the immediate future by a call to `pop_on_path`
902            return None;
903        }
904        self.pending.pop();
905        Some((response.token, response.network_path))
906    }
907
908    pub(crate) fn pop_on_path(&mut self, network_path: FourTuple) -> Option<u64> {
909        let response = *self.pending.last()?;
910        // Using an exact comparison. See explanation in `pop_off_path`.
911        if response.network_path != network_path {
912            // We don't bother searching further because we expect that the off-path response will
913            // get drained in the immediate future by a call to `pop_off_path`
914            return None;
915        }
916        self.pending.pop();
917        Some(response.token)
918    }
919
920    /// Whether the next [`Self::pop_on_path`] will return something to send.
921    pub(crate) fn has_pending_on_path(&self, network_path: FourTuple) -> bool {
922        self.pending
923            .last()
924            .is_some_and(|response| response.network_path == network_path)
925    }
926
927    pub(crate) fn is_empty(&self) -> bool {
928        self.pending.is_empty()
929    }
930}
931
932#[derive(Copy, Clone, Debug)]
933struct PathResponse {
934    /// The packet number the corresponding PATH_CHALLENGE was received in
935    packet: u64,
936    /// The token of the PATH_CHALLENGE
937    token: u64,
938    /// The path the corresponding PATH_CHALLENGE was received from
939    network_path: FourTuple,
940}
941
942/// Summary statistics of packets that have been sent on a particular path, but which have not yet
943/// been acked or deemed lost
944#[derive(Debug)]
945pub(super) struct InFlight {
946    /// Sum of the sizes of all sent packets considered "in flight" by congestion control
947    ///
948    /// The size does not include IP or UDP overhead. Packets only containing ACK frames do not
949    /// count towards this to ensure congestion control does not impede congestion feedback.
950    pub(super) bytes: u64,
951    /// Number of packets in flight containing frames other than ACK and PADDING
952    ///
953    /// This can be 0 even when bytes is not 0 because PADDING frames cause a packet to be
954    /// considered "in flight" by congestion control. However, if this is nonzero, bytes will
955    /// always also be nonzero.
956    pub(super) ack_eliciting: u64,
957}
958
959impl InFlight {
960    fn new() -> Self {
961        Self {
962            bytes: 0,
963            ack_eliciting: 0,
964        }
965    }
966
967    fn insert(&mut self, packet: &SentPacket) {
968        self.bytes += u64::from(packet.size);
969        self.ack_eliciting += u64::from(packet.ack_eliciting);
970    }
971
972    /// Update counters to account for a packet becoming acknowledged, lost, or abandoned
973    fn remove(&mut self, packet: &SentPacket) {
974        self.bytes -= u64::from(packet.size);
975        self.ack_eliciting -= u64::from(packet.ack_eliciting);
976    }
977}
978
979/// State for QUIC-MULTIPATH PATH_STATUS_AVAILABLE and PATH_STATUS_BACKUP frames
980#[derive(Debug, Clone, Default)]
981pub(super) struct PathStatusState {
982    /// The local status
983    local_status: PathStatus,
984    /// Local sequence number, for both PATH_STATUS_AVAILABLE and PATH_STATUS_BACKUP
985    ///
986    /// This is the number of the *next* path status frame to be sent.
987    local_seq: VarInt,
988    /// The status set by the remote
989    remote_status: Option<(VarInt, PathStatus)>,
990}
991
992impl PathStatusState {
993    /// To be called on received PATH_STATUS_AVAILABLE/PATH_STATUS_BACKUP frames
994    pub(super) fn remote_update(&mut self, status: PathStatus, seq: VarInt) {
995        if self.remote_status.is_some_and(|(curr, _)| curr >= seq) {
996            return trace!(%seq, "ignoring path status update");
997        }
998
999        let prev = self.remote_status.replace((seq, status)).map(|(_, s)| s);
1000        if prev != Some(status) {
1001            debug!(?status, ?seq, "remote changed path status");
1002        }
1003    }
1004
1005    /// Updates the local status
1006    ///
1007    /// If the local status changed, the previous value is returned
1008    pub(super) fn local_update(&mut self, status: PathStatus) -> Option<PathStatus> {
1009        if self.local_status == status {
1010            return None;
1011        }
1012
1013        self.local_seq = self.local_seq.saturating_add(1u8);
1014        Some(std::mem::replace(&mut self.local_status, status))
1015    }
1016
1017    pub(crate) fn seq(&self) -> VarInt {
1018        self.local_seq
1019    }
1020}
1021
1022/// The QUIC-MULTIPATH path status
1023///
1024/// See section "3.3 Path Status Management":
1025/// <https://quicwg.org/multipath/draft-ietf-quic-multipath.html#name-path-status-management>
1026#[cfg_attr(test, derive(test_strategy::Arbitrary))]
1027#[derive(Debug, Copy, Clone, Default, PartialEq, Eq)]
1028pub enum PathStatus {
1029    /// Paths marked with as available will be used when scheduling packets
1030    ///
1031    /// If multiple paths are available, packets will be scheduled on whichever has
1032    /// capacity.
1033    #[default]
1034    Available,
1035    /// Paths marked as backup will only be used if there are no available paths
1036    ///
1037    /// If the max_idle_timeout is specified the path will be kept alive so that it does not
1038    /// expire.
1039    Backup,
1040}
1041
1042/// Application events about paths
1043#[derive(Debug, Clone, PartialEq, Eq)]
1044#[non_exhaustive]
1045pub enum PathEvent {
1046    /// A new path has established connection with the peer.
1047    #[non_exhaustive]
1048    Established {
1049        /// The path which can now be used for application data.
1050        id: PathId,
1051    },
1052    /// A path was abandoned and is no longer usable.
1053    ///
1054    /// Note that this may be the first event for a path: If a path is abandoned
1055    /// before having been established, no [`Self::Established`] event is emitted.
1056    ///
1057    /// This event will always be followed by [`Self::Discarded`] after some time.
1058    #[non_exhaustive]
1059    Abandoned {
1060        /// The path that was abandoned.
1061        id: PathId,
1062        /// Reason why this path was abandoned.
1063        reason: PathAbandonReason,
1064    },
1065    /// A path was discarded and all remaining state for it has been removed.
1066    ///
1067    /// This event is the last event for a path, and is always emitted after [`Self::Abandoned`].
1068    #[non_exhaustive]
1069    Discarded {
1070        /// Which path had its state dropped
1071        id: PathId,
1072        /// The final path stats, they are no longer available via [`Connection::stats`]
1073        ///
1074        /// [`Connection::stats`]: super::Connection::stats
1075        path_stats: Box<PathStats>,
1076    },
1077    /// The remote changed the status of the path
1078    ///
1079    /// The local status is not changed because of this event. It is up to the application
1080    /// to update the local status, which is used for packet scheduling, when the remote
1081    /// changes the status.
1082    #[non_exhaustive]
1083    RemoteStatus {
1084        /// Path which has changed status
1085        id: PathId,
1086        /// The new status set by the remote
1087        status: PathStatus,
1088    },
1089    /// Received an observation of our external address from the peer.
1090    #[non_exhaustive]
1091    ObservedAddr {
1092        /// Path over which the observed address was reported, [`PathId::ZERO`] when multipath is
1093        /// not negotiated
1094        id: PathId,
1095        /// The address observed by the remote over this path
1096        addr: SocketAddr,
1097    },
1098}
1099
1100/// Reason for why a path was abandoned.
1101#[derive(Debug, Clone, Eq, PartialEq)]
1102pub enum PathAbandonReason {
1103    /// The path was closed locally by the application.
1104    ApplicationClosed {
1105        /// The error code to be sent with the abandon frame.
1106        error_code: VarInt,
1107    },
1108    /// We didn't receive a path response in time after opening this path.
1109    ///
1110    /// This event is no longer emitted, when validation fails a path is only abandoned once
1111    /// there's a path timeout and the [`Self::TimedOut`] event will be emitted instead.
1112    #[deprecated(
1113        since = "1.1.0",
1114        note = "This event is no longer emitted, TimedOut will be emitted instead"
1115    )]
1116    ValidationFailed,
1117    /// We didn't receive any data from the remote within the path's idle timeout.
1118    TimedOut,
1119    /// The path became unusable after a local network change.
1120    UnusableAfterNetworkChange,
1121    /// The remote closed the path.
1122    RemoteAbandoned {
1123        /// The error that was sent with the abandon frame.
1124        error_code: VarInt,
1125    },
1126}
1127
1128impl PathAbandonReason {
1129    /// Whether this abandon was initiated by the remote peer.
1130    pub(crate) fn is_remote(&self) -> bool {
1131        matches!(self, Self::RemoteAbandoned { .. })
1132    }
1133
1134    /// Returns the error code to send with a PATH_ABANDON frame.
1135    pub(crate) fn error_code(&self) -> TransportErrorCode {
1136        match self {
1137            Self::ApplicationClosed { error_code } => (*error_code).into(),
1138            #[allow(deprecated)]
1139            Self::ValidationFailed | Self::TimedOut | Self::UnusableAfterNetworkChange => {
1140                TransportErrorCode::PATH_UNSTABLE_OR_POOR
1141            }
1142            Self::RemoteAbandoned { error_code } => (*error_code).into(),
1143        }
1144    }
1145}
1146
1147/// Error from setting path status
1148#[derive(Debug, Error, Clone, PartialEq, Eq)]
1149pub enum SetPathStatusError {
1150    /// Error indicating that a path has not been opened or has already been abandoned
1151    #[error("closed path")]
1152    ClosedPath,
1153    /// Error indicating that this operation requires multipath to be negotiated whereas it hasn't
1154    /// been
1155    #[error("multipath not negotiated")]
1156    MultipathNotNegotiated,
1157}
1158
1159/// Error indicating that a path has not been opened or has already been abandoned
1160#[derive(Debug, Default, Error, Clone, PartialEq, Eq)]
1161#[error("closed path")]
1162pub struct ClosedPath {
1163    pub(super) _private: (),
1164}
1165
1166/// Retransmittable data specific to a [`PathData::generation`].
1167#[derive(Debug, Default, Clone)]
1168pub(super) struct PathRetransmits {
1169    /// Whether this path needs to report its remote address back to the peer.
1170    ///
1171    /// This only happens if both peers agree to do so based on their transport parameters.
1172    pub(super) observed_address: bool,
1173}
1174
1175impl PathRetransmits {
1176    pub(super) fn is_empty(&self) -> bool {
1177        let Self { observed_address } = self;
1178        !observed_address
1179    }
1180}
1181
1182impl std::ops::BitOrAssign for PathRetransmits {
1183    fn bitor_assign(&mut self, rhs: Self) {
1184        let Self { observed_address } = rhs;
1185        self.observed_address |= observed_address;
1186    }
1187}
1188
1189#[cfg(test)]
1190mod tests {
1191    use super::*;
1192
1193    #[test]
1194    fn test_path_id_saturating_add() {
1195        // add within range behaves normally
1196        let large: PathId = u16::MAX.into();
1197        let next = u32::from(u16::MAX) + 1;
1198        assert_eq!(large.saturating_add(1u8), PathId::from(next));
1199
1200        // outside range saturates
1201        assert_eq!(PathId::MAX.saturating_add(1u8), PathId::MAX)
1202    }
1203}