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