Skip to main content

rtci_sctp/association/
timer.rs

1use std::time::{Duration, Instant};
2
3pub(crate) const ACK_INTERVAL: u64 = 200;
4const MAX_INIT_RETRANS: usize = 8;
5const PATH_MAX_RETRANS: usize = 5;
6/// Association.Max.Retrans (RFC 9260 16).
7const ASSOCIATION_MAX_RETRANS: usize = 10;
8const NO_MAX_RETRANS: usize = usize::MAX;
9const TIMER_COUNT: usize = 9;
10
11#[derive(Debug, Copy, Clone)]
12/// Retransmission limits for the association's timers.
13///
14/// Each field caps how many times the corresponding timer may fire before the association is
15/// abandoned. `Default` follows the RFC 9260 recommendations.
16pub struct TimerConfig {
17    /// How many times INIT may be retransmitted (T1-init) before the association fails.
18    pub max_t1_init_retrans: usize,
19    /// How many times COOKIE-ECHO may be retransmitted (T1-cookie).
20    pub max_t1_cookie_retrans: usize,
21    /// How many times SHUTDOWN (or SHUTDOWN ACK) may be retransmitted without a packet from
22    /// the peer (T2-shutdown) before the association ends with
23    /// [`AssociationError::TimedOut`](crate::AssociationError::TimedOut). Defaults to
24    /// Association.Max.Retrans, 10 (RFC 9260 9.2).
25    pub max_t2_shutdown_retrans: usize,
26    /// How many consecutive T3-rtx expiries, with no new DATA acknowledged in between, are
27    /// tolerated before the peer is declared unreachable and the association closes with
28    /// [`AssociationError::TimedOut`](crate::AssociationError::TimedOut) (RFC 9260 8.1).
29    ///
30    /// An unanswered HEARTBEAT counts as one more.
31    ///
32    /// Defaults to Association.Max.Retrans, 10 (RFC 9260 16): with the RTO doubling up to
33    /// RTO.Max that is about five minutes without an answer. `usize::MAX` never gives up and
34    /// leaves the failure of the path to whatever runs underneath (ICE consent, for WebRTC).
35    pub max_t3_rtx_retrans: usize,
36    /// Not a limit of its own any more: a RE-CONFIG request (RFC 6525 5.1.1) is retransmitted
37    /// until it is answered, its timer doubling up to RTO.Max, and each expiry that does not
38    /// follow an "In progress" answer counts toward
39    /// [`max_t3_rtx_retrans`](Self::max_t3_rtx_retrans), as an unanswered HEARTBEAT does.
40    /// Past that limit the association ends with
41    /// [`AssociationError::TimedOut`](crate::AssociationError::TimedOut).
42    pub max_reconfig_retrans: usize,
43    /// How many times a delayed SACK may be retransmitted.
44    pub max_ack_retrans: usize,
45}
46
47impl Default for TimerConfig {
48    fn default() -> Self {
49        Self {
50            max_t1_init_retrans: MAX_INIT_RETRANS,
51            max_t1_cookie_retrans: MAX_INIT_RETRANS,
52            max_t2_shutdown_retrans: ASSOCIATION_MAX_RETRANS,
53            max_t3_rtx_retrans: ASSOCIATION_MAX_RETRANS,
54            max_reconfig_retrans: PATH_MAX_RETRANS,
55            max_ack_retrans: PATH_MAX_RETRANS,
56        }
57    }
58}
59
60#[derive(Debug, Copy, Clone, Ord, PartialOrd, Eq, PartialEq)]
61pub(crate) enum Timer {
62    T1Init = 0,
63    T1Cookie = 1,
64    T2Shutdown = 2,
65    T3RTX = 3,
66    Reconfig = 4,
67    Ack = 5,
68    /// How long an accepting association waits for the COOKIE ECHO. Its first expiry ends
69    /// the association.
70    HalfOpen = 6,
71    /// T5-shutdown-guard (RFC 9260 9.2): bounds a graceful shutdown. Its first expiry aborts
72    /// the association.
73    T5ShutdownGuard = 7,
74    /// The heartbeat timer (RFC 9260 8.3): the wait before a HEARTBEAT on an idle path, then
75    /// the wait for its HEARTBEAT ACK.
76    Heartbeat = 8,
77}
78
79impl Timer {
80    pub(crate) const VALUES: [Self; TIMER_COUNT] = [
81        Timer::T1Init,
82        Timer::T1Cookie,
83        Timer::T2Shutdown,
84        Timer::T3RTX,
85        Timer::Reconfig,
86        Timer::Ack,
87        Timer::HalfOpen,
88        Timer::T5ShutdownGuard,
89        Timer::Heartbeat,
90    ];
91}
92
93/// A table of data associated with each distinct kind of `Timer`
94#[derive(Debug, Copy, Clone, Default)]
95pub(crate) struct TimerTable {
96    data: [Option<Instant>; TIMER_COUNT],
97    retrans: [usize; TIMER_COUNT],
98    max_retrans: [usize; TIMER_COUNT],
99    shutdown_interval: Option<u64>,
100    reconfig_interval: Option<u64>,
101    /// RTO.Max in milliseconds when it is not the default, bounding the backoff of the timers
102    /// that double their own interval.
103    rto_max: Option<u64>,
104    /// T1-init and T1-cookie run on the path's RTO, which their expiries back off (RFC 9260
105    /// 5.1 and 6.3.3 E2), instead of doubling an interval of their own.
106    t1_follows_rto: bool,
107}
108
109impl TimerTable {
110    pub fn new(time_config: TimerConfig) -> Self {
111        TimerTable {
112            max_retrans: [
113                time_config.max_t1_init_retrans,     //T1Init
114                time_config.max_t1_cookie_retrans,   //T1Cookie
115                time_config.max_t2_shutdown_retrans, //T2Shutdown
116                time_config.max_t3_rtx_retrans,      //T3RTX
117                time_config.max_reconfig_retrans,    //Reconfig
118                time_config.max_ack_retrans,         //Ack
119                0,                                   //HalfOpen
120                0,                                   //T5ShutdownGuard
121                NO_MAX_RETRANS,                      //Heartbeat
122            ],
123            ..Default::default()
124        }
125    }
126
127    /// Bounds the timers' backoff by `config.max` (RTO.Max) instead of the default 60 seconds.
128    pub fn with_rto_config(mut self, config: RtoConfig) -> Self {
129        let max = u64::try_from(config.max.as_millis())
130            .unwrap_or(u64::MAX)
131            .max(1);
132        self.rto_max = Some(max);
133        self
134    }
135
136    /// T1-init and T1-cookie are started with the RTO the caller passes, which their
137    /// expiries back off (`TransportConfig::with_handshake_timers_back_off_rto`), instead of
138    /// doubling that interval by themselves.
139    pub fn with_t1_following_rto(mut self, value: bool) -> Self {
140        self.t1_follows_rto = value;
141        self
142    }
143
144    fn backoff(&self, interval: u64, n_rtos: usize) -> u64 {
145        calculate_next_timeout(interval, n_rtos, self.rto_max.unwrap_or(RTO_MAX))
146    }
147
148    pub fn set(&mut self, timer: Timer, time: Option<Instant>) {
149        self.data[timer as usize] = time;
150    }
151
152    pub fn get(&self, timer: Timer) -> Option<Instant> {
153        self.data[timer as usize]
154    }
155
156    pub fn next_timeout(&self) -> Option<Instant> {
157        self.data.iter().filter_map(|&x| x).min()
158    }
159
160    fn control_interval(&mut self, timer: Timer) -> Option<&mut Option<u64>> {
161        match timer {
162            Timer::T2Shutdown => Some(&mut self.shutdown_interval),
163            Timer::Reconfig => Some(&mut self.reconfig_interval),
164            _ => None,
165        }
166    }
167
168    pub fn start(&mut self, timer: Timer, now: Instant, interval: u64) {
169        // T3 uses the destination's current RTO, which already includes backoff.
170        // Successful DATA acknowledgments reset its error counter independently.
171        let interval = if let Some(current) = self.control_interval(timer) {
172            // Seed T2/RECONFIG from the current DATA RTO, then double their own
173            // interval on expiry. Rearming after serialization must neither
174            // compound T3 backoff nor apply this control timer's backoff twice.
175            // See RFC 9260 9.2 and RFC 6525 5.1.1.
176            *current.get_or_insert(interval)
177        } else if matches!(
178            timer,
179            Timer::Ack | Timer::T3RTX | Timer::HalfOpen | Timer::T5ShutdownGuard
180        ) || (self.t1_follows_rto && matches!(timer, Timer::T1Init | Timer::T1Cookie))
181        {
182            // T1-init and T1-cookie following RFC 9260 6.3: the RTO passed is the path's,
183            // already backed off by their expiries (E2).
184            interval
185        } else {
186            self.backoff(interval, self.retrans[timer as usize])
187        };
188
189        let time = now + Duration::from_millis(interval);
190        self.data[timer as usize] = Some(time);
191    }
192
193    /// Start an idle timer without hiding an unhandled expiration. A due
194    /// deadline stays armed until timeout processing consumes it, unless an
195    /// explicit protocol restart first clears it (for T3, acknowledgment of
196    /// the earliest outstanding TSN under RFC 9260 section 6.3.2 R3).
197    pub fn start_if_idle(&mut self, timer: Timer, now: Instant, interval: u64) {
198        if self.data[timer as usize].is_none() {
199            self.start(timer, now, interval);
200        }
201    }
202
203    pub fn stop(&mut self, timer: Timer) {
204        self.data[timer as usize] = None;
205        self.reset_retrans(timer);
206        if let Some(interval) = self.control_interval(timer) {
207            *interval = None;
208        }
209    }
210
211    /// Counts a failure that is not this timer's own expiry against its limit (an
212    /// unanswered HEARTBEAT counts with the T3-rtx expiries, RFC 9260 8.1). Returns whether
213    /// the limit is passed.
214    pub fn count_error(&mut self, timer: Timer) -> bool {
215        self.retrans[timer as usize] = self.retrans[timer as usize].saturating_add(1);
216        self.retrans[timer as usize] > self.max_retrans[timer as usize]
217    }
218
219    /// How many times `timer` may expire before it fails.
220    pub fn max_retrans(&self, timer: Timer) -> usize {
221        self.max_retrans[timer as usize]
222    }
223
224    pub fn reset_retrans(&mut self, timer: Timer) {
225        self.retrans[timer as usize] = 0;
226    }
227
228    pub fn is_expired(&mut self, timer: Timer, after: Instant) -> (bool, bool, usize) {
229        let expired = self.data[timer as usize].is_some_and(|x| x <= after);
230        let mut failure = false;
231        let rto_max = self.rto_max.unwrap_or(RTO_MAX);
232        if expired && let Some(interval) = self.control_interval(timer) {
233            *interval = interval.map(|previous| calculate_next_timeout(previous, 1, rto_max));
234        }
235        if expired {
236            self.retrans[timer as usize] += 1;
237            if self.retrans[timer as usize] > self.max_retrans[timer as usize] {
238                failure = true;
239            }
240        }
241
242        (expired, failure, self.retrans[timer as usize])
243    }
244}
245
246// RFC 9260 ยง16 recommends a one-second initial RTO.  This value is used by
247// both T1-init and T1-cookie before an RTT measurement is available.
248const RTO_INITIAL: u64 = 1000; // msec
249const RTO_MIN: u64 = 1000; // msec
250const RTO_MAX: u64 = 60000; // msec
251/// G of RFC 9260 6.3.1: the granularity of the clock, in milliseconds.
252const CLOCK_GRANULARITY: f64 = 1.0;
253const RTO_ALPHA: u64 = 1;
254const RTO_BETA: u64 = 2;
255const RTO_BASE: u64 = 8;
256
257/// RTO.Initial, RTO.Min and RTO.Max (RFC 9260 section 16), the bounds of the retransmission
258/// timeout. `Default` is the RFC's recommended values: 1, 1 and 60 seconds.
259#[derive(Debug, Copy, Clone, PartialEq, Eq)]
260pub struct RtoConfig {
261    /// RTO.Initial: the RTO before a round trip was measured (and after a reset).
262    pub initial: Duration,
263    /// RTO.Min: the smallest RTO a measurement gives.
264    pub min: Duration,
265    /// RTO.Max: the largest RTO, measured or backed off.
266    pub max: Duration,
267}
268
269impl Default for RtoConfig {
270    fn default() -> Self {
271        Self {
272            initial: Duration::from_millis(RTO_INITIAL),
273            min: Duration::from_millis(RTO_MIN),
274            max: Duration::from_millis(RTO_MAX),
275        }
276    }
277}
278
279/// rtoManager manages Rtx timeout values.
280/// This is an implementation of RFC 9260 sec 6.3.1.
281#[derive(Debug)]
282pub(crate) struct RtoManager {
283    pub(crate) srtt: u64,
284    pub(crate) rttvar: f64,
285    pub(crate) rto: u64,
286    pub(crate) no_update: bool,
287    /// RTO.Initial, RTO.Min, RTO.Max in milliseconds.
288    initial: u64,
289    min: u64,
290    max: u64,
291}
292
293impl Default for RtoManager {
294    fn default() -> Self {
295        RtoManager {
296            srtt: 0,
297            rttvar: 0.0,
298            rto: 0,
299            no_update: false,
300            initial: RTO_INITIAL,
301            min: RTO_MIN,
302            max: RTO_MAX,
303        }
304    }
305}
306
307impl RtoManager {
308    /// newRTOManager creates a new rtoManager.
309    pub(crate) fn new() -> Self {
310        Self::with_config(RtoConfig::default())
311    }
312
313    /// A manager whose RTO starts at `config.initial` and stays within `config.min` and
314    /// `config.max` (each at least a millisecond, the maximum at least the minimum).
315    pub(crate) fn with_config(config: RtoConfig) -> Self {
316        let millis = |d: Duration| u64::try_from(d.as_millis()).unwrap_or(u64::MAX).max(1);
317        let min = millis(config.min);
318        let max = millis(config.max).max(min);
319        let initial = millis(config.initial).clamp(min, max);
320        RtoManager {
321            rto: initial,
322            initial,
323            min,
324            max,
325            ..Default::default()
326        }
327    }
328
329    /// set_new_rtt takes a newly measured RTT then adjust the RTO in msec.
330    pub(crate) fn set_new_rtt(&mut self, rtt: u64) -> u64 {
331        if self.no_update {
332            return self.srtt;
333        }
334
335        if self.srtt == 0 {
336            // First measurement
337            self.srtt = rtt;
338            self.rttvar = rtt as f64 / 2.0;
339        } else {
340            // Subsequent rtt measurement
341            self.rttvar = ((RTO_BASE - RTO_BETA) as f64 * self.rttvar
342                + RTO_BETA as f64 * (self.srtt as i64 - rtt as i64).abs() as f64)
343                / RTO_BASE as f64;
344            self.srtt = ((RTO_BASE - RTO_ALPHA) * self.srtt + RTO_ALPHA * rtt) / RTO_BASE;
345        }
346
347        // RFC 9260 6.3.1 G1: "Whenever RTTVAR is computed, if RTTVAR == 0, then adjust
348        // RTTVAR <- G", the clock granularity: a millisecond here.
349        if self.rttvar == 0.0 {
350            self.rttvar = CLOCK_GRANULARITY;
351        }
352
353        self.rto = (self.srtt + (4.0 * self.rttvar) as u64).clamp(self.min, self.max);
354
355        self.srtt
356    }
357
358    /// get_rto simply returns the current RTO in msec.
359    pub(crate) fn get_rto(&self) -> u64 {
360        self.rto
361    }
362
363    /// RFC 9260 6.3.3 E2: retain backoff until a new RTT measurement updates RTO.
364    pub(crate) fn backoff(&mut self) {
365        if !self.no_update {
366            self.rto = self.rto.saturating_mul(2).min(self.max);
367        }
368    }
369
370    /// reset resets the RTO variables to the initial values.
371    pub(crate) fn reset(&mut self) {
372        if self.no_update {
373            return;
374        }
375
376        self.srtt = 0;
377        self.rttvar = 0.0;
378        self.rto = self.initial;
379    }
380
381    /// set RTO value for testing
382    pub(crate) fn set_rto(&mut self, rto: u64, no_update: bool) {
383        self.rto = rto;
384        self.no_update = no_update;
385    }
386}
387
388fn calculate_next_timeout(rto: u64, n_rtos: usize, rto_max: u64) -> u64 {
389    // RFC 4096 sec 6.3.3.  Handle T3-rtx Expiration
390    //   E2)  For the destination address for which the timer expires, set RTO
391    //        <- RTO * 2 ("back off the timer").  The maximum value discussed
392    //        in rule C7 above (RTO.max) may be used to provide an upper bound
393    //        to this doubling operation.
394    if n_rtos < 31 {
395        std::cmp::min(rto << n_rtos, rto_max)
396    } else {
397        rto_max
398    }
399}
400
401#[cfg(test)]
402#[path = "timer_test.rs"]
403mod timer_test;
404
405#[cfg(test)]
406mod tests {
407    use super::*;
408
409    #[test]
410    fn rto_backoff_respects_pinned_rto() {
411        let mut rto = RtoManager::new();
412        rto.set_rto(1000, true);
413        rto.backoff();
414        assert_eq!(1000, rto.get_rto());
415        rto.set_rto(1000, false);
416        rto.backoff();
417        assert_eq!(2000, rto.get_rto());
418        rto.set_rto(RTO_MAX - 1, false);
419        rto.backoff();
420        assert_eq!(RTO_MAX, rto.get_rto());
421    }
422
423    #[test]
424    fn rto_manager_uses_rfc9260_initial_rto() {
425        assert_eq!(RTO_INITIAL, 1000);
426        assert_eq!(RtoManager::new().get_rto(), RTO_INITIAL);
427    }
428
429    #[test]
430    fn t1_init_starts_at_initial_rto_before_an_rtt_is_measured() {
431        let now = Instant::now();
432        let mut timers = TimerTable::new(TimerConfig::default());
433
434        timers.start(Timer::T1Init, now, RtoManager::new().get_rto());
435
436        assert_eq!(timers.next_timeout(), Some(now + Duration::from_secs(1)));
437    }
438
439    #[test]
440    fn control_backoff_uses_one_interval_until_stopped() {
441        for timer in [Timer::T2Shutdown, Timer::Reconfig] {
442            let mut timers = TimerTable::new(TimerConfig {
443                max_reconfig_retrans: usize::MAX,
444                ..TimerConfig::default()
445            });
446            let mut now = Instant::now();
447            // A new procedure uses the current RTO, including previous DATA
448            // backoff. Later DATA RTT updates/backoffs cannot compound it.
449            timers.start(timer, now, 8000);
450            assert_eq!(Some(now + Duration::from_secs(8)), timers.get(timer));
451            for interval in [16, 32, 60, 60] {
452                now = timers.get(timer).unwrap();
453                assert_eq!((true, false), {
454                    let (expired, failed, _) = timers.is_expired(timer, now);
455                    (expired, failed)
456                });
457                timers.set(timer, None);
458                for data_rto in [60_000, 1000] {
459                    timers.start(timer, now, data_rto);
460                    assert_eq!(Some(now + Duration::from_secs(interval)), timers.get(timer));
461                }
462            }
463            timers.stop(timer);
464            timers.start(timer, now, 3000);
465            assert_eq!(Some(now + Duration::from_secs(3)), timers.get(timer));
466            assert_eq!((false, false, 0), timers.is_expired(timer, now));
467        }
468    }
469}