rtci-sctp 0.5.0

Sans-I/O SCTP (RFC 9260) with partial reliability and stream reconfiguration, for WebRTC data channels
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
use std::time::{Duration, Instant};

pub(crate) const ACK_INTERVAL: u64 = 200;
const MAX_INIT_RETRANS: usize = 8;
const PATH_MAX_RETRANS: usize = 5;
/// Association.Max.Retrans (RFC 9260 16).
const ASSOCIATION_MAX_RETRANS: usize = 10;
const NO_MAX_RETRANS: usize = usize::MAX;
const TIMER_COUNT: usize = 9;

#[derive(Debug, Copy, Clone)]
/// Retransmission limits for the association's timers.
///
/// Each field caps how many times the corresponding timer may fire before the association is
/// abandoned. `Default` follows the RFC 9260 recommendations.
pub struct TimerConfig {
    /// How many times INIT may be retransmitted (T1-init) before the association fails.
    pub max_t1_init_retrans: usize,
    /// How many times COOKIE-ECHO may be retransmitted (T1-cookie).
    pub max_t1_cookie_retrans: usize,
    /// How many times SHUTDOWN (or SHUTDOWN ACK) may be retransmitted without a packet from
    /// the peer (T2-shutdown) before the association ends with
    /// [`AssociationError::TimedOut`](crate::AssociationError::TimedOut). Defaults to
    /// Association.Max.Retrans, 10 (RFC 9260 9.2).
    pub max_t2_shutdown_retrans: usize,
    /// How many consecutive T3-rtx expiries, with no new DATA acknowledged in between, are
    /// tolerated before the peer is declared unreachable and the association closes with
    /// [`AssociationError::TimedOut`](crate::AssociationError::TimedOut) (RFC 9260 8.1).
    ///
    /// An unanswered HEARTBEAT counts as one more.
    ///
    /// Defaults to Association.Max.Retrans, 10 (RFC 9260 16): with the RTO doubling up to
    /// RTO.Max that is about five minutes without an answer. `usize::MAX` never gives up and
    /// leaves the failure of the path to whatever runs underneath (ICE consent, for WebRTC).
    pub max_t3_rtx_retrans: usize,
    /// Not a limit of its own any more: a RE-CONFIG request (RFC 6525 5.1.1) is retransmitted
    /// until it is answered, its timer doubling up to RTO.Max, and each expiry that does not
    /// follow an "In progress" answer counts toward
    /// [`max_t3_rtx_retrans`](Self::max_t3_rtx_retrans), as an unanswered HEARTBEAT does.
    /// Past that limit the association ends with
    /// [`AssociationError::TimedOut`](crate::AssociationError::TimedOut).
    pub max_reconfig_retrans: usize,
    /// How many times a delayed SACK may be retransmitted.
    pub max_ack_retrans: usize,
}

impl Default for TimerConfig {
    fn default() -> Self {
        Self {
            max_t1_init_retrans: MAX_INIT_RETRANS,
            max_t1_cookie_retrans: MAX_INIT_RETRANS,
            max_t2_shutdown_retrans: ASSOCIATION_MAX_RETRANS,
            max_t3_rtx_retrans: ASSOCIATION_MAX_RETRANS,
            max_reconfig_retrans: PATH_MAX_RETRANS,
            max_ack_retrans: PATH_MAX_RETRANS,
        }
    }
}

#[derive(Debug, Copy, Clone, Ord, PartialOrd, Eq, PartialEq)]
pub(crate) enum Timer {
    T1Init = 0,
    T1Cookie = 1,
    T2Shutdown = 2,
    T3RTX = 3,
    Reconfig = 4,
    Ack = 5,
    /// How long an accepting association waits for the COOKIE ECHO. Its first expiry ends
    /// the association.
    HalfOpen = 6,
    /// T5-shutdown-guard (RFC 9260 9.2): bounds a graceful shutdown. Its first expiry aborts
    /// the association.
    T5ShutdownGuard = 7,
    /// The heartbeat timer (RFC 9260 8.3): the wait before a HEARTBEAT on an idle path, then
    /// the wait for its HEARTBEAT ACK.
    Heartbeat = 8,
}

impl Timer {
    pub(crate) const VALUES: [Self; TIMER_COUNT] = [
        Timer::T1Init,
        Timer::T1Cookie,
        Timer::T2Shutdown,
        Timer::T3RTX,
        Timer::Reconfig,
        Timer::Ack,
        Timer::HalfOpen,
        Timer::T5ShutdownGuard,
        Timer::Heartbeat,
    ];
}

/// A table of data associated with each distinct kind of `Timer`
#[derive(Debug, Copy, Clone, Default)]
pub(crate) struct TimerTable {
    data: [Option<Instant>; TIMER_COUNT],
    retrans: [usize; TIMER_COUNT],
    max_retrans: [usize; TIMER_COUNT],
    shutdown_interval: Option<u64>,
    reconfig_interval: Option<u64>,
    /// RTO.Max in milliseconds when it is not the default, bounding the backoff of the timers
    /// that double their own interval.
    rto_max: Option<u64>,
    /// T1-init and T1-cookie run on the path's RTO, which their expiries back off (RFC 9260
    /// 5.1 and 6.3.3 E2), instead of doubling an interval of their own.
    t1_follows_rto: bool,
}

impl TimerTable {
    pub fn new(time_config: TimerConfig) -> Self {
        TimerTable {
            max_retrans: [
                time_config.max_t1_init_retrans,     //T1Init
                time_config.max_t1_cookie_retrans,   //T1Cookie
                time_config.max_t2_shutdown_retrans, //T2Shutdown
                time_config.max_t3_rtx_retrans,      //T3RTX
                time_config.max_reconfig_retrans,    //Reconfig
                time_config.max_ack_retrans,         //Ack
                0,                                   //HalfOpen
                0,                                   //T5ShutdownGuard
                NO_MAX_RETRANS,                      //Heartbeat
            ],
            ..Default::default()
        }
    }

    /// Bounds the timers' backoff by `config.max` (RTO.Max) instead of the default 60 seconds.
    pub fn with_rto_config(mut self, config: RtoConfig) -> Self {
        let max = u64::try_from(config.max.as_millis())
            .unwrap_or(u64::MAX)
            .max(1);
        self.rto_max = Some(max);
        self
    }

    /// T1-init and T1-cookie are started with the RTO the caller passes, which their
    /// expiries back off (`TransportConfig::with_handshake_timers_back_off_rto`), instead of
    /// doubling that interval by themselves.
    pub fn with_t1_following_rto(mut self, value: bool) -> Self {
        self.t1_follows_rto = value;
        self
    }

    fn backoff(&self, interval: u64, n_rtos: usize) -> u64 {
        calculate_next_timeout(interval, n_rtos, self.rto_max.unwrap_or(RTO_MAX))
    }

    pub fn set(&mut self, timer: Timer, time: Option<Instant>) {
        self.data[timer as usize] = time;
    }

    pub fn get(&self, timer: Timer) -> Option<Instant> {
        self.data[timer as usize]
    }

    pub fn next_timeout(&self) -> Option<Instant> {
        self.data.iter().filter_map(|&x| x).min()
    }

    fn control_interval(&mut self, timer: Timer) -> Option<&mut Option<u64>> {
        match timer {
            Timer::T2Shutdown => Some(&mut self.shutdown_interval),
            Timer::Reconfig => Some(&mut self.reconfig_interval),
            _ => None,
        }
    }

    pub fn start(&mut self, timer: Timer, now: Instant, interval: u64) {
        // T3 uses the destination's current RTO, which already includes backoff.
        // Successful DATA acknowledgments reset its error counter independently.
        let interval = if let Some(current) = self.control_interval(timer) {
            // Seed T2/RECONFIG from the current DATA RTO, then double their own
            // interval on expiry. Rearming after serialization must neither
            // compound T3 backoff nor apply this control timer's backoff twice.
            // See RFC 9260 9.2 and RFC 6525 5.1.1.
            *current.get_or_insert(interval)
        } else if matches!(
            timer,
            Timer::Ack | Timer::T3RTX | Timer::HalfOpen | Timer::T5ShutdownGuard
        ) || (self.t1_follows_rto && matches!(timer, Timer::T1Init | Timer::T1Cookie))
        {
            // T1-init and T1-cookie following RFC 9260 6.3: the RTO passed is the path's,
            // already backed off by their expiries (E2).
            interval
        } else {
            self.backoff(interval, self.retrans[timer as usize])
        };

        let time = now + Duration::from_millis(interval);
        self.data[timer as usize] = Some(time);
    }

    /// Start an idle timer without hiding an unhandled expiration. A due
    /// deadline stays armed until timeout processing consumes it, unless an
    /// explicit protocol restart first clears it (for T3, acknowledgment of
    /// the earliest outstanding TSN under RFC 9260 section 6.3.2 R3).
    pub fn start_if_idle(&mut self, timer: Timer, now: Instant, interval: u64) {
        if self.data[timer as usize].is_none() {
            self.start(timer, now, interval);
        }
    }

    pub fn stop(&mut self, timer: Timer) {
        self.data[timer as usize] = None;
        self.reset_retrans(timer);
        if let Some(interval) = self.control_interval(timer) {
            *interval = None;
        }
    }

    /// Counts a failure that is not this timer's own expiry against its limit (an
    /// unanswered HEARTBEAT counts with the T3-rtx expiries, RFC 9260 8.1). Returns whether
    /// the limit is passed.
    pub fn count_error(&mut self, timer: Timer) -> bool {
        self.retrans[timer as usize] = self.retrans[timer as usize].saturating_add(1);
        self.retrans[timer as usize] > self.max_retrans[timer as usize]
    }

    /// How many times `timer` may expire before it fails.
    pub fn max_retrans(&self, timer: Timer) -> usize {
        self.max_retrans[timer as usize]
    }

    pub fn reset_retrans(&mut self, timer: Timer) {
        self.retrans[timer as usize] = 0;
    }

    pub fn is_expired(&mut self, timer: Timer, after: Instant) -> (bool, bool, usize) {
        let expired = self.data[timer as usize].is_some_and(|x| x <= after);
        let mut failure = false;
        let rto_max = self.rto_max.unwrap_or(RTO_MAX);
        if expired && let Some(interval) = self.control_interval(timer) {
            *interval = interval.map(|previous| calculate_next_timeout(previous, 1, rto_max));
        }
        if expired {
            self.retrans[timer as usize] += 1;
            if self.retrans[timer as usize] > self.max_retrans[timer as usize] {
                failure = true;
            }
        }

        (expired, failure, self.retrans[timer as usize])
    }
}

// RFC 9260 §16 recommends a one-second initial RTO.  This value is used by
// both T1-init and T1-cookie before an RTT measurement is available.
const RTO_INITIAL: u64 = 1000; // msec
const RTO_MIN: u64 = 1000; // msec
const RTO_MAX: u64 = 60000; // msec
/// G of RFC 9260 6.3.1: the granularity of the clock, in milliseconds.
const CLOCK_GRANULARITY: f64 = 1.0;
const RTO_ALPHA: u64 = 1;
const RTO_BETA: u64 = 2;
const RTO_BASE: u64 = 8;

/// RTO.Initial, RTO.Min and RTO.Max (RFC 9260 section 16), the bounds of the retransmission
/// timeout. `Default` is the RFC's recommended values: 1, 1 and 60 seconds.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct RtoConfig {
    /// RTO.Initial: the RTO before a round trip was measured (and after a reset).
    pub initial: Duration,
    /// RTO.Min: the smallest RTO a measurement gives.
    pub min: Duration,
    /// RTO.Max: the largest RTO, measured or backed off.
    pub max: Duration,
}

impl Default for RtoConfig {
    fn default() -> Self {
        Self {
            initial: Duration::from_millis(RTO_INITIAL),
            min: Duration::from_millis(RTO_MIN),
            max: Duration::from_millis(RTO_MAX),
        }
    }
}

/// rtoManager manages Rtx timeout values.
/// This is an implementation of RFC 9260 sec 6.3.1.
#[derive(Debug)]
pub(crate) struct RtoManager {
    pub(crate) srtt: u64,
    pub(crate) rttvar: f64,
    pub(crate) rto: u64,
    pub(crate) no_update: bool,
    /// RTO.Initial, RTO.Min, RTO.Max in milliseconds.
    initial: u64,
    min: u64,
    max: u64,
}

impl Default for RtoManager {
    fn default() -> Self {
        RtoManager {
            srtt: 0,
            rttvar: 0.0,
            rto: 0,
            no_update: false,
            initial: RTO_INITIAL,
            min: RTO_MIN,
            max: RTO_MAX,
        }
    }
}

impl RtoManager {
    /// newRTOManager creates a new rtoManager.
    pub(crate) fn new() -> Self {
        Self::with_config(RtoConfig::default())
    }

    /// A manager whose RTO starts at `config.initial` and stays within `config.min` and
    /// `config.max` (each at least a millisecond, the maximum at least the minimum).
    pub(crate) fn with_config(config: RtoConfig) -> Self {
        let millis = |d: Duration| u64::try_from(d.as_millis()).unwrap_or(u64::MAX).max(1);
        let min = millis(config.min);
        let max = millis(config.max).max(min);
        let initial = millis(config.initial).clamp(min, max);
        RtoManager {
            rto: initial,
            initial,
            min,
            max,
            ..Default::default()
        }
    }

    /// set_new_rtt takes a newly measured RTT then adjust the RTO in msec.
    pub(crate) fn set_new_rtt(&mut self, rtt: u64) -> u64 {
        if self.no_update {
            return self.srtt;
        }

        if self.srtt == 0 {
            // First measurement
            self.srtt = rtt;
            self.rttvar = rtt as f64 / 2.0;
        } else {
            // Subsequent rtt measurement
            self.rttvar = ((RTO_BASE - RTO_BETA) as f64 * self.rttvar
                + RTO_BETA as f64 * (self.srtt as i64 - rtt as i64).abs() as f64)
                / RTO_BASE as f64;
            self.srtt = ((RTO_BASE - RTO_ALPHA) * self.srtt + RTO_ALPHA * rtt) / RTO_BASE;
        }

        // RFC 9260 6.3.1 G1: "Whenever RTTVAR is computed, if RTTVAR == 0, then adjust
        // RTTVAR <- G", the clock granularity: a millisecond here.
        if self.rttvar == 0.0 {
            self.rttvar = CLOCK_GRANULARITY;
        }

        self.rto = (self.srtt + (4.0 * self.rttvar) as u64).clamp(self.min, self.max);

        self.srtt
    }

    /// get_rto simply returns the current RTO in msec.
    pub(crate) fn get_rto(&self) -> u64 {
        self.rto
    }

    /// RFC 9260 6.3.3 E2: retain backoff until a new RTT measurement updates RTO.
    pub(crate) fn backoff(&mut self) {
        if !self.no_update {
            self.rto = self.rto.saturating_mul(2).min(self.max);
        }
    }

    /// reset resets the RTO variables to the initial values.
    pub(crate) fn reset(&mut self) {
        if self.no_update {
            return;
        }

        self.srtt = 0;
        self.rttvar = 0.0;
        self.rto = self.initial;
    }

    /// set RTO value for testing
    pub(crate) fn set_rto(&mut self, rto: u64, no_update: bool) {
        self.rto = rto;
        self.no_update = no_update;
    }
}

fn calculate_next_timeout(rto: u64, n_rtos: usize, rto_max: u64) -> u64 {
    // RFC 4096 sec 6.3.3.  Handle T3-rtx Expiration
    //   E2)  For the destination address for which the timer expires, set RTO
    //        <- RTO * 2 ("back off the timer").  The maximum value discussed
    //        in rule C7 above (RTO.max) may be used to provide an upper bound
    //        to this doubling operation.
    if n_rtos < 31 {
        std::cmp::min(rto << n_rtos, rto_max)
    } else {
        rto_max
    }
}

#[cfg(test)]
#[path = "timer_test.rs"]
mod timer_test;

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn rto_backoff_respects_pinned_rto() {
        let mut rto = RtoManager::new();
        rto.set_rto(1000, true);
        rto.backoff();
        assert_eq!(1000, rto.get_rto());
        rto.set_rto(1000, false);
        rto.backoff();
        assert_eq!(2000, rto.get_rto());
        rto.set_rto(RTO_MAX - 1, false);
        rto.backoff();
        assert_eq!(RTO_MAX, rto.get_rto());
    }

    #[test]
    fn rto_manager_uses_rfc9260_initial_rto() {
        assert_eq!(RTO_INITIAL, 1000);
        assert_eq!(RtoManager::new().get_rto(), RTO_INITIAL);
    }

    #[test]
    fn t1_init_starts_at_initial_rto_before_an_rtt_is_measured() {
        let now = Instant::now();
        let mut timers = TimerTable::new(TimerConfig::default());

        timers.start(Timer::T1Init, now, RtoManager::new().get_rto());

        assert_eq!(timers.next_timeout(), Some(now + Duration::from_secs(1)));
    }

    #[test]
    fn control_backoff_uses_one_interval_until_stopped() {
        for timer in [Timer::T2Shutdown, Timer::Reconfig] {
            let mut timers = TimerTable::new(TimerConfig {
                max_reconfig_retrans: usize::MAX,
                ..TimerConfig::default()
            });
            let mut now = Instant::now();
            // A new procedure uses the current RTO, including previous DATA
            // backoff. Later DATA RTT updates/backoffs cannot compound it.
            timers.start(timer, now, 8000);
            assert_eq!(Some(now + Duration::from_secs(8)), timers.get(timer));
            for interval in [16, 32, 60, 60] {
                now = timers.get(timer).unwrap();
                assert_eq!((true, false), {
                    let (expired, failed, _) = timers.is_expired(timer, now);
                    (expired, failed)
                });
                timers.set(timer, None);
                for data_rto in [60_000, 1000] {
                    timers.start(timer, now, data_rto);
                    assert_eq!(Some(now + Duration::from_secs(interval)), timers.get(timer));
                }
            }
            timers.stop(timer);
            timers.start(timer, now, 3000);
            assert_eq!(Some(now + Duration::from_secs(3)), timers.get(timer));
            assert_eq!((false, false, 0), timers.is_expired(timer, now));
        }
    }
}