Skip to main content

rtci_sctp/association/
pmtud.rs

1//! Datagram Packetization Layer Path MTU Discovery (DPLPMTUD, RFC 8899) for an association.
2//!
3//! RFC 8261 section 4 and RFC 8831 section 5: SCTP over DTLS discovers the path MTU without
4//! ICMP. RFC 8899 section 6.2 is the method: a probe is an SCTP packet of exactly the size to
5//! try, a HEARTBEAT chunk followed by a PAD chunk (RFC 4820) that fills it up, and the
6//! HEARTBEAT ACK confirms that the size crosses the path. Probes carry no user data, so a lost
7//! one costs nothing to repair; they are neither congestion nor flow controlled and do not
8//! count against the path (RFC 8899 section 3, items 4, 7 and 8; section 6.2.1.2).
9//!
10//! This module is the state machine of RFC 8899 section 5.2 (DISABLED, BASE, SEARCHING,
11//! SEARCH_COMPLETE, ERROR) in SCTP packet bytes: the sizes are what the association hands the
12//! layer below, so the headers under SCTP (DTLS record, UDP, IP, TURN framing) are the
13//! caller's to subtract from an IP-layer MTU. The association sends the probes, routes their
14//! acknowledgements here and applies the PLPMTU this machine settles on.
15//!
16//! Black holes. SCTP is an acknowledged packetization layer, so it runs no
17//! CONFIRMATION_TIMER in SEARCH_COMPLETE (section 6.2.3.3, a MUST NOT); a path that stops
18//! carrying the current size shows as data that is not acknowledged. Two retransmission
19//! timeouts in a row without the cumulative TSN moving, while the PLPMTU is above the base,
20//! are taken as that indication (section 4.3, the third method): the PLPMTU falls back to
21//! BASE_PLPMTU, which is confirmed, and the search starts again from there.
22
23use std::time::{Duration, Instant};
24
25/// Smallest step the search takes: probing for less is not worth a probe (RFC 8899 section
26/// 5.3.2, "maximize the gain in PLPMTU from each search step").
27const SEARCH_STEP: u32 = 16;
28
29/// Retransmission timeouts in a row, without progress, that indicate a black hole.
30pub(crate) const BLACK_HOLE_TIMEOUTS: u32 = 2;
31
32/// The probe: an SCTP common header (12 bytes), a HEARTBEAT chunk with one Heartbeat Info
33/// parameter of 20 bytes (4 + 4 + 20 = 28 bytes) and the PAD chunk's own header (4 bytes).
34/// The smallest probe is this, with no padding at all.
35pub(crate) const PROBE_OVERHEAD: u32 = 12 + 28 + 4;
36
37/// The phase of the discovery (RFC 8899 section 5.2).
38#[derive(Debug, Copy, Clone, PartialEq, Eq)]
39pub enum PathMtuState {
40    /// Not started: the association is not established, or discovery is off.
41    Disabled,
42    /// Confirming that BASE_PLPMTU crosses the path.
43    Base,
44    /// Probing for a larger PLPMTU.
45    Searching,
46    /// The search is over; the PLPMTU stays until the raise timer or a black hole.
47    SearchComplete,
48    /// BASE_PLPMTU was not confirmed: the PLPMTU is MIN_PLPMTU and BASE_PLPMTU is probed
49    /// until it is.
50    Error,
51}
52
53/// Settings of the path MTU discovery (RFC 8899 sections 5.1.1 and 5.1.2), in SCTP packet
54/// bytes (common header and chunks).
55#[derive(Debug, Copy, Clone, PartialEq, Eq)]
56pub struct PathMtuDiscoveryConfig {
57    max_path_mtu: u32,
58    min_path_mtu: u32,
59    probe_timeout: Duration,
60    raise_interval: Duration,
61    max_probes: u32,
62}
63
64impl Default for PathMtuDiscoveryConfig {
65    /// MAX_PLPMTU 1452 (a 1500-byte IPv6 packet less the IPv6 and UDP headers; over DTLS the
66    /// record overhead comes off too, and a transport that knows it says so with
67    /// [`with_max_path_mtu`](Self::with_max_path_mtu)); MIN_PLPMTU the smallest packet that
68    /// carries DATA; PROBE_TIMER 16 s (section 5.1.1: at least 1 s, and it "SHOULD be larger
69    /// than 15 seconds"); PMTU_RAISE_TIMER 600 s; MAX_PROBES 3.
70    fn default() -> Self {
71        Self {
72            max_path_mtu: 1452,
73            min_path_mtu: crate::config::MIN_DATA_PACKET_MTU,
74            probe_timeout: Duration::from_secs(16),
75            raise_interval: Duration::from_secs(600),
76            max_probes: 3,
77        }
78    }
79}
80
81impl PathMtuDiscoveryConfig {
82    /// MAX_PLPMTU: the largest SCTP packet the search tries (the local interface MTU less
83    /// what lies under SCTP).
84    pub fn with_max_path_mtu(mut self, value: u32) -> Self {
85        self.max_path_mtu = value;
86        self
87    }
88
89    /// MAX_PLPMTU, see [`with_max_path_mtu`](Self::with_max_path_mtu).
90    pub fn max_path_mtu(&self) -> u32 {
91        self.max_path_mtu
92    }
93
94    /// MIN_PLPMTU: the PLPMTU used while BASE_PLPMTU is not confirmed (the ERROR state).
95    /// Raised to the smallest packet that carries DATA.
96    pub fn with_min_path_mtu(mut self, value: u32) -> Self {
97        self.min_path_mtu = value.max(crate::config::MIN_DATA_PACKET_MTU);
98        self
99    }
100
101    /// MIN_PLPMTU, see [`with_min_path_mtu`](Self::with_min_path_mtu).
102    pub fn min_path_mtu(&self) -> u32 {
103        self.min_path_mtu
104    }
105
106    /// PROBE_TIMER: how long a probe waits for its acknowledgement. Raised to 1 s (RFC 8899
107    /// section 5.1.1: it "MUST NOT be smaller than 1 second").
108    pub fn with_probe_timeout(mut self, value: Duration) -> Self {
109        self.probe_timeout = value.max(Duration::from_secs(1));
110        self
111    }
112
113    /// PROBE_TIMER, see [`with_probe_timeout`](Self::with_probe_timeout).
114    pub fn probe_timeout(&self) -> Duration {
115        self.probe_timeout
116    }
117
118    /// PMTU_RAISE_TIMER: how long a completed search is trusted before the next one.
119    pub fn with_raise_interval(mut self, value: Duration) -> Self {
120        self.raise_interval = value;
121        self
122    }
123
124    /// PMTU_RAISE_TIMER, see [`with_raise_interval`](Self::with_raise_interval).
125    pub fn raise_interval(&self) -> Duration {
126        self.raise_interval
127    }
128
129    /// MAX_PROBES: unacknowledged probes in a row, of any size, after which a phase ends.
130    /// At least 1.
131    pub fn with_max_probes(mut self, value: u32) -> Self {
132        self.max_probes = value.max(1);
133        self
134    }
135
136    /// MAX_PROBES, see [`with_max_probes`](Self::with_max_probes).
137    pub fn max_probes(&self) -> u32 {
138        self.max_probes
139    }
140}
141
142/// The discovery of one association's path.
143#[derive(Debug, Clone)]
144pub(crate) struct PathMtuDiscovery {
145    config: PathMtuDiscoveryConfig,
146    state: PathMtuState,
147    /// BASE_PLPMTU: the size the path is assumed to carry (RFC 8831 section 5's initial MTU).
148    base: u32,
149    /// PLPMTU: the largest size confirmed (or assumed, in BASE and ERROR).
150    plpmtu: u32,
151    /// PROBED_SIZE.
152    probed_size: u32,
153    /// PROBE_COUNT: probes in a row that went unacknowledged.
154    probe_count: u32,
155    /// The smallest size this search found not to cross the path; above MAX_PLPMTU while
156    /// none failed.
157    failed_size: u32,
158    /// A probe is due.
159    send_due: bool,
160    /// The probe in flight: its nonce, size and deadline.
161    outstanding: Option<(u64, u32, Instant)>,
162    /// When the next search starts (PMTU_RAISE_TIMER), in SEARCH_COMPLETE.
163    raise_at: Option<Instant>,
164    /// Retransmission timeouts in a row without progress (the black hole indication).
165    stalled_timeouts: u32,
166}
167
168impl PathMtuDiscovery {
169    pub(crate) fn new(config: PathMtuDiscoveryConfig, base: u32) -> Self {
170        Self {
171            config,
172            state: PathMtuState::Disabled,
173            base,
174            plpmtu: base,
175            probed_size: base,
176            probe_count: 0,
177            failed_size: u32::MAX,
178            send_due: false,
179            outstanding: None,
180            raise_at: None,
181            stalled_timeouts: 0,
182        }
183    }
184
185    pub(crate) fn state(&self) -> PathMtuState {
186        self.state
187    }
188
189    pub(crate) fn config(&self) -> &PathMtuDiscoveryConfig {
190        &self.config
191    }
192
193    /// BASE_PLPMTU.
194    pub(crate) fn base(&self) -> u32 {
195        self.base
196    }
197
198    /// The largest size the search tries: MAX_PLPMTU, never below BASE_PLPMTU.
199    fn max(&self) -> u32 {
200        round_down(self.config.max_path_mtu).max(self.base)
201    }
202
203    /// Starts over from DISABLED with `base` as BASE_PLPMTU (a new path, or a new base the
204    /// transport learned). The next [`start`](Self::start) enters BASE.
205    pub(crate) fn reset(&mut self, base: u32) {
206        *self = Self::new(self.config, base);
207    }
208
209    /// Sets MAX_PLPMTU. A PLPMTU above it comes down to it; the search goes on below it.
210    /// Returns the new PLPMTU when it changed.
211    pub(crate) fn set_max_path_mtu(&mut self, max: u32) -> Option<u32> {
212        self.config.max_path_mtu = max;
213        if self.state == PathMtuState::SearchComplete && self.plpmtu < self.max() {
214            // A larger MAX_PLPMTU is worth a search now rather than at the raise timer.
215            self.enter_searching();
216        }
217        if self.plpmtu > self.max() {
218            self.plpmtu = self.max();
219            return Some(self.plpmtu);
220        }
221        None
222    }
223
224    /// The association is established (RFC 8899 section 6.2.3.1: "A sender can enter the
225    /// BASE state as soon as SCTP connectivity has been confirmed"). Nothing in another state.
226    pub(crate) fn start(&mut self) {
227        if self.state == PathMtuState::Disabled {
228            self.enter_base();
229        }
230    }
231
232    fn enter_base(&mut self) {
233        self.state = PathMtuState::Base;
234        self.plpmtu = self.base;
235        self.probed_size = self.base;
236        self.probe_count = 0;
237        self.failed_size = u32::MAX;
238        self.outstanding = None;
239        self.raise_at = None;
240        self.send_due = true;
241    }
242
243    fn enter_searching(&mut self) {
244        self.state = PathMtuState::Searching;
245        self.probe_count = 0;
246        self.failed_size = u32::MAX;
247        self.outstanding = None;
248        self.raise_at = None;
249        match self.next_size() {
250            Some(size) => {
251                self.probed_size = size;
252                self.send_due = true;
253            }
254            None => self.enter_search_complete_without_timer(),
255        }
256    }
257
258    fn enter_search_complete_without_timer(&mut self) {
259        self.state = PathMtuState::SearchComplete;
260        self.outstanding = None;
261        self.send_due = false;
262    }
263
264    fn enter_search_complete(&mut self, now: Instant) {
265        self.enter_search_complete_without_timer();
266        self.raise_at = Some(now + self.config.raise_interval);
267    }
268
269    /// The next size to probe in SEARCHING: MAX_PLPMTU first (the largest gain, section
270    /// 5.3.2), then halfway between the PLPMTU and the smallest size that failed. `None` when
271    /// what is left is less than a step.
272    fn next_size(&self) -> Option<u32> {
273        let max = self.max();
274        if self.plpmtu >= max {
275            return None;
276        }
277        let high = self.failed_size.min(max.saturating_add(4));
278        if high <= self.plpmtu.saturating_add(SEARCH_STEP) {
279            return None;
280        }
281        if self.failed_size > max {
282            return Some(max);
283        }
284        let mid = round_down(self.plpmtu + (high - self.plpmtu) / 2);
285        (mid > self.plpmtu).then_some(mid)
286    }
287
288    /// The size of the probe to send now, if one is due. The caller sends it and reports it
289    /// with [`probe_sent`](Self::probe_sent).
290    pub(crate) fn poll_probe(&self) -> Option<u32> {
291        if !self.send_due || self.outstanding.is_some() {
292            return None;
293        }
294        match self.state {
295            PathMtuState::Base | PathMtuState::Searching | PathMtuState::Error => {
296                Some(self.probed_size.max(PROBE_OVERHEAD))
297            }
298            PathMtuState::Disabled | PathMtuState::SearchComplete => None,
299        }
300    }
301
302    pub(crate) fn probe_sent(&mut self, nonce: u64, size: u32, now: Instant) {
303        self.send_due = false;
304        self.outstanding = Some((nonce, size, now + self.config.probe_timeout));
305    }
306
307    /// The probe whose HEARTBEAT ACK carried `nonce` crossed the path. Returns the new
308    /// PLPMTU when it changed; `None` for a nonce that is not the outstanding probe's (a late
309    /// or duplicated acknowledgement, RFC 8899 section 3: robust to delay and duplication).
310    pub(crate) fn on_probe_ack(&mut self, nonce: u64, now: Instant) -> Option<u32> {
311        let (expected, size, _) = self.outstanding?;
312        if expected != nonce {
313            return None;
314        }
315        self.outstanding = None;
316        self.probe_count = 0;
317        let before = self.plpmtu;
318        match self.state {
319            PathMtuState::Base | PathMtuState::Error => {
320                self.plpmtu = size;
321                self.enter_searching();
322            }
323            PathMtuState::Searching => {
324                self.plpmtu = size;
325                match self.next_size() {
326                    Some(next) => {
327                        self.probed_size = next;
328                        self.send_due = true;
329                    }
330                    None => self.enter_search_complete(now),
331                }
332            }
333            PathMtuState::Disabled | PathMtuState::SearchComplete => {}
334        }
335        (self.plpmtu != before).then_some(self.plpmtu)
336    }
337
338    /// When [`on_timeout`](Self::on_timeout) is next due.
339    pub(crate) fn deadline(&self) -> Option<Instant> {
340        match (self.outstanding.map(|(_, _, at)| at), self.raise_at) {
341            (Some(a), Some(b)) => Some(a.min(b)),
342            (a, b) => a.or(b),
343        }
344    }
345
346    /// Runs the PROBE_TIMER and the PMTU_RAISE_TIMER. Returns the new PLPMTU when it changed.
347    pub(crate) fn on_timeout(&mut self, now: Instant) -> Option<u32> {
348        let before = self.plpmtu;
349        if let Some((_, size, at)) = self.outstanding
350            && now >= at
351        {
352            // The probe failed: it is discounted, not taken as congestion or as a path
353            // failure (section 3 item 7, section 6.2.1.2).
354            self.outstanding = None;
355            self.probe_count += 1;
356            let exhausted = self.probe_count >= self.config.max_probes;
357            match self.state {
358                PathMtuState::Base if exhausted => {
359                    // BASE_PLPMTU does not cross the path: MIN_PLPMTU until it does.
360                    self.state = PathMtuState::Error;
361                    self.plpmtu = self.config.min_path_mtu.min(self.base);
362                    self.probe_count = 0;
363                    self.send_due = true;
364                }
365                PathMtuState::Base | PathMtuState::Error => self.send_due = true,
366                PathMtuState::Searching => {
367                    self.failed_size = self.failed_size.min(size);
368                    if exhausted {
369                        self.enter_search_complete(now);
370                    } else {
371                        match self.next_size() {
372                            Some(next) => {
373                                self.probed_size = next;
374                                self.send_due = true;
375                            }
376                            None => self.enter_search_complete(now),
377                        }
378                    }
379                }
380                PathMtuState::Disabled | PathMtuState::SearchComplete => {}
381            }
382        }
383        if self.state == PathMtuState::SearchComplete && self.raise_at.is_some_and(|at| now >= at) {
384            self.enter_searching();
385        }
386        (self.plpmtu != before).then_some(self.plpmtu)
387    }
388
389    /// A retransmission timeout fired with nothing acknowledged since the last one. Returns
390    /// the new PLPMTU when this is taken as a black hole (section 4.3): the path no longer
391    /// carries the PLPMTU, which falls back to BASE_PLPMTU, to be confirmed by a probe.
392    pub(crate) fn on_retransmission_timeout(&mut self) -> Option<u32> {
393        if !matches!(
394            self.state,
395            PathMtuState::Searching | PathMtuState::SearchComplete
396        ) || self.plpmtu <= self.base
397        {
398            self.stalled_timeouts = 0;
399            return None;
400        }
401        self.stalled_timeouts += 1;
402        if self.stalled_timeouts < BLACK_HOLE_TIMEOUTS {
403            return None;
404        }
405        self.stalled_timeouts = 0;
406        self.enter_base();
407        Some(self.plpmtu)
408    }
409
410    /// A validated Packet Too Big reported the path to carry SCTP packets of `ptb_size`
411    /// bytes (PL_PTB_SIZE, the headers below SCTP taken off). RFC 8899 section 4.6.2: PTB
412    /// messages "MUST NOT be used directly to set the PLPMTU"; by the size reported:
413    ///
414    /// - below BASE_PLPMTU (below MIN_PLPMTU: "ought to be discarded"; between the two "A
415    ///   robust PL MAY enter an error state"): nothing changes, probing stays the judge;
416    /// - BASE_PLPMTU <= PL_PTB_SIZE < PLPMTU: "This could be an indication of a black hole.
417    ///   The PLPMTU SHOULD be set to BASE_PLPMTU", which is confirmed by a probe, and the
418    ///   search starts again from there;
419    /// - at or above the PLPMTU (a probe larger than the path, or "Inconsistent network
420    ///   signal"): "The PLPMTU is not updated".
421    ///
422    /// Returns the new PLPMTU when it changed.
423    pub(crate) fn on_packet_too_big(&mut self, ptb_size: u32) -> Option<u32> {
424        if self.state == PathMtuState::Disabled || ptb_size < self.base || ptb_size >= self.plpmtu {
425            return None;
426        }
427        self.enter_base();
428        Some(self.plpmtu)
429    }
430
431    /// The cumulative TSN moved: data crosses the path at the PLPMTU.
432    pub(crate) fn on_progress(&mut self) {
433        self.stalled_timeouts = 0;
434    }
435}
436
437/// Probes are a whole number of 4-byte words (the PAD chunk then needs no padding of its own).
438fn round_down(size: u32) -> u32 {
439    size & !3
440}
441
442#[cfg(test)]
443mod test {
444    use super::*;
445
446    /// RFC 8899 section 4.6.2: a Packet Too Big below the PLPMTU and not below BASE_PLPMTU
447    /// takes the PLPMTU back to BASE_PLPMTU, to be confirmed by a probe; one below the base,
448    /// or not below the PLPMTU, changes nothing; none raises it.
449    #[test]
450    fn a_packet_too_big_takes_the_plpmtu_back_to_the_base_and_never_up() {
451        let now = Instant::now();
452        let config = PathMtuDiscoveryConfig::default().with_max_path_mtu(1400);
453        let mut d = PathMtuDiscovery::new(config, 1100);
454        d.start();
455        acked(&mut d, now);
456        acked(&mut d, now);
457        assert_eq!(
458            d.plpmtu, 1400,
459            "precondition: the search reached MAX_PLPMTU"
460        );
461        assert_eq!(d.on_packet_too_big(1400), None, "not below the PLPMTU");
462        assert_eq!(d.on_packet_too_big(1099), None, "below the base");
463        assert_eq!(d.plpmtu, 1400);
464        assert_eq!(d.on_packet_too_big(1250), Some(1100), "back to the base");
465        assert_eq!(d.state(), PathMtuState::Base);
466        assert_eq!(d.poll_probe(), Some(1100), "the base is confirmed again");
467        assert_eq!(d.on_packet_too_big(1200), None, "never raised");
468    }
469
470    fn acked(d: &mut PathMtuDiscovery, now: Instant) -> Option<u32> {
471        let size = d.poll_probe()?;
472        d.probe_sent(7, size, now);
473        d.on_probe_ack(7, now);
474        Some(size)
475    }
476
477    /// The search climbs from BASE_PLPMTU to the largest size the path takes, by halves,
478    /// with MAX_PLPMTU tried first; MAX_PROBES failures in a row end it.
479    #[test]
480    fn the_search_finds_the_largest_size_below_the_first_failure() {
481        let now = Instant::now();
482        let config = PathMtuDiscoveryConfig::default().with_max_path_mtu(1400);
483        let mut d = PathMtuDiscovery::new(config, 1100);
484        assert_eq!(d.poll_probe(), None, "nothing before the association is up");
485        d.start();
486        assert_eq!(acked(&mut d, now), Some(1100), "BASE_PLPMTU first");
487        assert_eq!(d.state(), PathMtuState::Searching);
488        let path = 1300;
489        let mut t = now;
490        let mut probes = Vec::new();
491        while let Some(size) = d.poll_probe() {
492            probes.push(size);
493            d.probe_sent(size as u64, size, t);
494            if size <= path {
495                d.on_probe_ack(size as u64, t);
496            } else {
497                t += config.probe_timeout();
498                d.on_timeout(t);
499            }
500        }
501        assert_eq!(probes[0], 1400, "MAX_PLPMTU first: {probes:?}");
502        assert_eq!(d.state(), PathMtuState::SearchComplete, "{probes:?}");
503        assert!(
504            d.plpmtu <= path && d.plpmtu > path - SEARCH_STEP,
505            "{} for a path of {path}: {probes:?}",
506            d.plpmtu
507        );
508    }
509}