Skip to main content

srt_runtime/
link.rs

1//! One SRT connection as a sans-IO link: datagrams and the caller's `now` in, datagrams to
2//! send and delivered payloads out.
3//!
4//! [`Link`] holds the whole per-connection conversation once the handshake has settled: the ARQ
5//! receiver and sender, the TSBPD scheduler, the §6 payload cipher and KM Refresh, LiveCC pacing,
6//! Keep-Alive and peer-idle timing, end-of-stream reporting, and DROPREQ/SHUTDOWN handling. It
7//! never reads a clock and never touches a socket: every call takes `now` and leaves what must
8//! go on the wire in [`Link::take_sent`].
9//!
10//! [`CallerLink`] is the caller role on top of it: the sans-IO [`CallerHandshake`] with its
11//! retransmit period and budget, and the transition into a [`Link`] at the resolution. It serves
12//! the tokio adapter ([`crate::io`]) and any embedded host that owns its own socket loop alike, so
13//! the protocol has one implementation, not one per host.
14//!
15//! SRT: draft-sharabayko-srt-01 (handshake 4.3, TSBPD 4.5, too-late drop 4.6, ARQ 4.8, encryption 6).
16
17use alloc::collections::{BTreeMap, VecDeque};
18use alloc::vec::Vec;
19use core::mem::size_of;
20use core::num::NonZeroU32;
21use core::time::Duration;
22
23use broadcast_core::damage::{Damage, DamageError, DamagePolicy};
24use broadcast_core::stage::Instant;
25
26use crate::arq::seq::{contiguous_runs, seq_diff, seq_in_closed_range, seq_lt, seq_next};
27use crate::arq::{Receiver as ArqReceiver, Sender as ArqSender, timestamp_to_wire_us};
28use crate::caller::CallerHandshake;
29use crate::damage as damage_reports;
30use crate::handshake_sm::{HandshakeConfig, HandshakeOutput, NegotiatedParams, RejectionReason};
31use crate::livecc::{LiveCC, MaxBwConfig};
32use crate::packet::data::next_message_number;
33use crate::packet::misc::{KeepAlivePacket, ShutdownPacket};
34use crate::packet::{
35    ControlPacket, DropReqPacket, EncryptionField, EncryptionKeyField, SRT_HEADER_LEN, SocketId,
36    SrtPacket, SrtTimestamp,
37};
38use crate::tsbpd::{TickOutcome, TsbpdScheduler};
39use sha2::{Digest, Sha256};
40
41use crate::handshake_sm::CryptoConfig;
42use crate::km_refresh::{KeyParity, KmRefreshDriver, KmRefreshEvent, KmRefreshThresholds};
43use crate::packet::handshake::{EXT_TYPE_KMREQ, EXT_TYPE_KMRSP};
44use crate::packet::{KeyMaterial, KmKeyFlag};
45use zeroize::Zeroizing;
46
47/// Initial TSBPD drift (zero: the scheduler estimates it from there).
48const INITIAL_DRIFT_US: i64 = 0;
49
50#[cfg(test)]
51pub(crate) const TEST_DRIFT_WINDOW: NonZeroU32 = NonZeroU32::new(1000).expect("non-zero window");
52
53/// Floor on how soon [`Link::next_deadline`] may ask to be woken: never a
54/// deadline in the past, and a 1 ms minimum cannot spin (it matches the timer
55/// granularity every hosted adapter here has).
56pub const MIN_WAKE: Duration = Duration::from_millis(1);
57
58/// Default SEK length when the connection's own key length is unknown: AES-128.
59const DEFAULT_SEK_LEN: usize = 16;
60
61fn micros(d: Duration) -> u64 {
62    u64::try_from(d.as_micros()).unwrap_or(u64::MAX)
63}
64
65/// The `SHUTDOWN` datagram (§3.2.7) a leaving side sends its peer so the peer closes at once
66/// instead of waiting out its idle timeout. `None` when the packet cannot be serialized.
67#[must_use]
68pub fn shutdown_datagram(peer_socket_id: u32, timestamp: Duration) -> Option<Vec<u8>> {
69    let timestamp = timestamp_to_wire_us(Instant::from_micros(
70        u64::try_from(timestamp.as_micros()).unwrap_or(u64::MAX),
71    ));
72    let pkt = ControlPacket::Shutdown(ShutdownPacket {
73        timestamp,
74        dest_socket_id: SocketId::from_wire(peer_socket_id),
75        libsrt_pad: true,
76    });
77    let mut buf = alloc::vec![0u8; pkt.serialized_len()];
78    pkt.serialize_into(&mut buf).ok()?;
79    Some(buf)
80}
81
82// ===========================================================================
83// What a caller supplies
84// ===========================================================================
85
86/// The protocol cadence a link keeps, every period chosen by the caller (libsrt's values are a
87/// 250 ms handshake retransmit, a 1 s keep-alive; the rest are this crate's own choices).
88#[derive(Debug, Clone, Copy, PartialEq, Eq)]
89pub struct LinkCadence {
90    /// How often an unanswered handshake request is re-sent (§4.3.1.1).
91    pub handshake_retransmit: Duration,
92    /// Keep-Alive period, measured from the last packet of any kind sent (§3.2.3).
93    pub keepalive: Duration,
94    /// How often an unconfirmed refresh KMREQ is re-sent until its KMRSP arrives (§6.1.6).
95    pub km_resend: Duration,
96    /// Shortest interval between two peer Key Material messages this link processes: recovering
97    /// the SEK runs a 2048-iteration PBKDF2, so a peer that re-sends KMREQ back to back must not
98    /// spend a core on it (#2840).
99    pub kmreq_min_interval: Duration,
100}
101
102/// Every time bound a link needs, all chosen by the caller.
103#[derive(Debug, Clone, Copy, PartialEq, Eq)]
104pub struct LinkTimers {
105    /// The protocol cadence.
106    pub cadence: LinkCadence,
107    /// Longest the handshake may take before the attempt fails.
108    pub handshake_timeout: Duration,
109    /// Longest silence from a connected peer before the link ends.
110    pub read_idle: Duration,
111}
112
113/// What a [`CallerLink`] is configured by: the handshake this side advertises, the connection's
114/// own Socket ID and initial sequence number, its time bounds, and what the link may assume about
115/// the stream it delivers.
116///
117/// The caller supplies the Socket ID and the ISN; a link never draws them itself, so a host that
118/// reads no randomness (or derives them from a seed it keeps) can still open a connection.
119#[derive(Debug, Clone)]
120#[non_exhaustive]
121pub struct CallerParams {
122    /// The handshake this side advertises (latency, stream id, encryption).
123    pub handshake: HandshakeConfig,
124    /// This caller's own SRT Socket ID (§3).
125    pub own_socket_id: u32,
126    /// This caller's initial sequence number: the first sequence number it sends (§3.1).
127    pub initial_seq_number: u32,
128    /// The link's time bounds.
129    pub timers: LinkTimers,
130    /// The ARQ receiver's and sender's bounds.
131    pub arq: crate::arq::ArqBounds,
132    /// Secret entropy the link derives every refreshed stream key from; it draws none itself. A
133    /// refresh that cannot be derived (an empty seed) is counted in
134    /// [`LinkCounts::key_refresh_failed`] and reported as damage, never skipped silently.
135    pub key_refresh_seed: Zeroizing<Vec<u8>>,
136    /// A synchronous check on each delivered payload: one it refuses is counted and reported, and
137    /// never delivered. The host names the payload format it expects; the link imposes none, so a
138    /// link built with [`CallerParams::new`] admits every payload.
139    pub payload_admits: fn(&[u8]) -> bool,
140    /// The caller's decision about each damage report.
141    pub damage_policy: DamagePolicy,
142    /// Initial TSBPD drift. The scheduler estimates it from there; zero when none is known.
143    pub drift_us: i64,
144    /// Fresh in-sequence packets per drift-sampling window (§4.7, rules 26-27).
145    /// The draft names no count, so the caller supplies one.
146    pub drift_window: NonZeroU32,
147    /// The LiveCC bandwidth policy that paces DATA packets (§5.1.1).
148    pub max_bw: MaxBwConfig,
149    /// KM Refresh thresholds (§6.1.6, key rotation packet counts).
150    pub km_refresh_thresholds: KmRefreshThresholds,
151    /// Whether a connection that negotiated encryption refuses a DATA packet sent in the clear,
152    /// counting it undecryptable, rather than delivering it.
153    pub refuse_cleartext: bool,
154}
155
156impl CallerParams {
157    /// Parameters advertising `handshake` with this side's Socket ID and ISN, the caller's time
158    /// bounds and key-refresh entropy, [`DamagePolicy::default`] (report everything), the default
159    /// LiveCC policy and a link that admits every delivered payload.
160    #[must_use]
161    pub fn new(
162        handshake: HandshakeConfig,
163        own_socket_id: u32,
164        initial_seq_number: u32,
165        timers: LinkTimers,
166        arq: crate::arq::ArqBounds,
167        key_refresh_seed: Vec<u8>,
168        drift_window: NonZeroU32,
169    ) -> Self {
170        Self {
171            handshake,
172            own_socket_id,
173            initial_seq_number,
174            timers,
175            arq,
176            key_refresh_seed: Zeroizing::new(key_refresh_seed),
177            payload_admits: admits_every_payload,
178            damage_policy: DamagePolicy::default(),
179            drift_us: INITIAL_DRIFT_US,
180            drift_window,
181            max_bw: MaxBwConfig::default(),
182            km_refresh_thresholds: KmRefreshThresholds::RECOMMENDED,
183            refuse_cleartext: false,
184        }
185    }
186
187    /// Set how long the handshake may take.
188    #[must_use]
189    pub fn with_handshake_timeout(mut self, handshake_timeout: Duration) -> Self {
190        self.timers.handshake_timeout = handshake_timeout;
191        self
192    }
193
194    /// Set which payloads the link delivers (see [`CallerParams::payload_admits`]).
195    #[must_use]
196    pub fn with_payload_admits(mut self, payload_admits: fn(&[u8]) -> bool) -> Self {
197        self.payload_admits = payload_admits;
198        self
199    }
200
201    /// Set the caller's decision about each damage report.
202    #[must_use]
203    pub fn with_damage_policy(mut self, damage_policy: DamagePolicy) -> Self {
204        self.damage_policy = damage_policy;
205        self
206    }
207
208    /// Set the initial TSBPD drift.
209    #[must_use]
210    pub fn with_drift_us(mut self, drift_us: i64) -> Self {
211        self.drift_us = drift_us;
212        self
213    }
214
215    /// Set the LiveCC bandwidth policy.
216    #[must_use]
217    pub fn with_max_bw(mut self, max_bw: MaxBwConfig) -> Self {
218        self.max_bw = max_bw;
219        self
220    }
221
222    /// Set the peer-idle bound.
223    #[must_use]
224    pub fn with_read_idle(mut self, read_idle: Duration) -> Self {
225        self.timers.read_idle = read_idle;
226        self
227    }
228
229    /// Set the §6 passphrase a peer's Key Material is recovered with. The encryption
230    /// field this side advertises still comes from `handshake` (its `CryptoConfig`
231    /// salt and stream key are overwritten per attempt).
232    #[must_use]
233    pub fn with_passphrase(mut self, passphrase: Vec<u8>) -> Self {
234        self.handshake = self.handshake.with_crypto(Some(CryptoConfig {
235            passphrase,
236            salt: [0; crate::crypto::SALT_LEN],
237            sek: Vec::new(),
238        }));
239        self
240    }
241
242    /// Refuse cleartext DATA on a connection that negotiated encryption (see
243    /// [`CallerParams::refuse_cleartext`]).
244    #[must_use]
245    pub fn with_cleartext_refused(mut self) -> Self {
246        self.refuse_cleartext = true;
247        self
248    }
249
250    /// Set the KM Refresh thresholds.
251    #[must_use]
252    pub fn with_km_refresh_thresholds(mut self, thresholds: KmRefreshThresholds) -> Self {
253        self.km_refresh_thresholds = thresholds;
254        self
255    }
256}
257
258#[cfg(test)]
259pub(crate) const TEST_TIMERS: LinkTimers = LinkTimers {
260    cadence: LinkCadence {
261        handshake_retransmit: Duration::from_millis(250),
262        keepalive: Duration::from_secs(1),
263        km_resend: Duration::from_millis(500),
264        kmreq_min_interval: Duration::from_millis(100),
265    },
266    handshake_timeout: Duration::from_secs(5),
267    read_idle: Duration::from_secs(5),
268};
269
270fn admits_every_payload(_payload: &[u8]) -> bool {
271    true
272}
273
274/// How a link ended, named once.
275#[non_exhaustive]
276#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
277pub enum LinkEnd {
278    /// The peer refused the handshake, with its reason (§4.3.1.2).
279    Rejected(RejectionReason),
280    /// No resolution arrived inside the handshake budget or the retransmit budget.
281    HandshakeTimedOut,
282    /// Nothing at all arrived from the connected peer for the peer-idle bound.
283    PeerIdle,
284    /// The peer sent `SHUTDOWN` (§3.2.7).
285    PeerShutdown,
286    /// The send key reached the packet count after which its keystream would repeat, and no
287    /// refreshed key was confirmed: sending on would reuse keystream, so the link stops.
288    KeyExhausted,
289}
290
291impl LinkEnd {
292    /// A short label for this ending.
293    #[must_use]
294    pub fn name(&self) -> &'static str {
295        match self {
296            LinkEnd::Rejected(_) => "Rejected",
297            LinkEnd::HandshakeTimedOut => "HandshakeTimedOut",
298            LinkEnd::PeerIdle => "PeerIdle",
299            LinkEnd::PeerShutdown => "PeerShutdown",
300            LinkEnd::KeyExhausted => "KeyExhausted",
301        }
302    }
303}
304
305broadcast_core::impl_spec_display!(LinkEnd);
306
307/// What settled a connection: its negotiated parameters and the peer's own handshake values.
308///
309/// The peer's initial sequence number seeds ARQ/TSBPD sequence tracking and its handshake
310/// timestamp seeds the TSBPD time base (rule 12); its SRT Socket ID is the wire `dest_socket_id`
311/// for every outgoing packet (the two are unrelated values, §3).
312#[derive(Debug, Clone)]
313#[non_exhaustive]
314pub struct LinkSetup {
315    /// The negotiated parameters.
316    pub params: NegotiatedParams,
317    /// The peer's initial sequence number.
318    pub peer_initial_seq: u32,
319    /// The TSBPD time base (µs, signed): `T_NOW - HSREQ_TIMESTAMP`, with `T_NOW` the connection's
320    /// own clock at the instant the peer's handshake arrived.
321    pub time_base_us: i64,
322}
323
324impl LinkSetup {
325    /// What `params` and the peer's own handshake values settle, for a [`Link`] that starts
326    /// measuring at the instant that handshake arrived (the time base is the negated timestamp).
327    #[must_use]
328    pub fn new(params: NegotiatedParams, peer_initial_seq: u32, peer_timestamp_us: u32) -> Self {
329        Self {
330            params,
331            peer_initial_seq,
332            time_base_us: -i64::from(peer_timestamp_us),
333        }
334    }
335
336    /// The time base of a connection whose clock started before the peer's handshake arrived.
337    #[must_use]
338    pub fn with_time_base_us(mut self, time_base_us: i64) -> Self {
339        self.time_base_us = time_base_us;
340        self
341    }
342
343    /// The time base of a connection whose clock started before the peer's handshake arrived,
344    /// from `T_NOW`, the clock's reading at that arrival, and the peer's handshake timestamp.
345    #[must_use]
346    pub fn with_arrival(mut self, t_now: Duration, peer_timestamp_us: u32) -> Self {
347        let t_now_us = i64::try_from(t_now.as_micros()).unwrap_or(i64::MAX);
348        self.time_base_us = t_now_us.saturating_sub(i64::from(peer_timestamp_us));
349        self
350    }
351
352    /// The peer's SRT Socket ID.
353    #[must_use]
354    pub fn peer_socket_id(&self) -> u32 {
355        self.params.peer_socket_id
356    }
357
358    /// The TSBPD time base (§4.5.1.1, rule 12).
359    #[must_use]
360    pub fn time_base(&self) -> i64 {
361        self.time_base_us
362    }
363}
364
365/// One delivered application payload, held in the datagram it arrived in: the bytes from
366/// [`Payload::start`] on. A host that hands payloads on as shared buffers takes the datagram and
367/// the offset with [`Payload::into_parts`] and slices it, without a copy.
368#[derive(Debug, Clone, PartialEq, Eq)]
369pub struct Payload {
370    datagram: Vec<u8>,
371    start: usize,
372}
373
374impl Payload {
375    #[cfg(test)]
376    pub(crate) fn of(bytes: &[u8]) -> Self {
377        Self {
378            datagram: bytes.to_vec(),
379            start: 0,
380        }
381    }
382
383    /// The payload bytes.
384    #[must_use]
385    pub fn as_slice(&self) -> &[u8] {
386        self.datagram.get(self.start..).unwrap_or_default()
387    }
388
389    /// Where the payload starts in the datagram it arrived in.
390    #[must_use]
391    pub fn start(&self) -> usize {
392        self.start
393    }
394
395    /// The payload as its own vector: the datagram with the bytes before the payload removed,
396    /// in place.
397    #[must_use]
398    pub fn into_vec(self) -> Vec<u8> {
399        let Payload {
400            mut datagram,
401            start,
402        } = self;
403        datagram.drain(..start.min(datagram.len()));
404        datagram
405    }
406
407    /// The datagram the payload arrived in and the offset it starts at.
408    #[must_use]
409    pub fn into_parts(self) -> (Vec<u8>, usize) {
410        (self.datagram, self.start)
411    }
412}
413
414/// One item a link hands its host, in the order the stream needs it.
415#[non_exhaustive]
416#[derive(Debug, Clone, PartialEq, Eq)]
417pub enum DeliveredItem {
418    /// A delivered application payload.
419    Payload(Payload),
420    /// A [`Damage`] report.
421    Damage(Damage),
422    /// The caller's [`DamagePolicy`] refused a report, naming the same report: the link has ended.
423    Refused(DamageError),
424    /// How the link ended.
425    Ended(LinkEnd),
426}
427
428impl DeliveredItem {
429    /// The kind of item: `payload`, `damage`, `refused` or `ended`.
430    #[must_use]
431    pub fn name(&self) -> &'static str {
432        match self {
433            DeliveredItem::Payload(_) => "payload",
434            DeliveredItem::Damage(_) => "damage",
435            DeliveredItem::Refused(_) => "refused",
436            DeliveredItem::Ended(_) => "ended",
437        }
438    }
439}
440
441broadcast_core::impl_spec_display!(DeliveredItem);
442
443/// What one call on a link delivered, in order.
444#[derive(Debug, Clone, PartialEq, Eq, Default)]
445pub struct Delivered {
446    items: Vec<DeliveredItem>,
447}
448
449impl Delivered {
450    #[cfg(test)]
451    pub(crate) fn from_items(items: Vec<DeliveredItem>) -> Self {
452        Self { items }
453    }
454
455    /// Nothing was delivered.
456    #[must_use]
457    pub fn is_empty(&self) -> bool {
458        self.items.is_empty()
459    }
460
461    /// The items, in order.
462    #[must_use]
463    pub fn items(&self) -> &[DeliveredItem] {
464        &self.items
465    }
466
467    /// Take the items, in order.
468    #[must_use]
469    pub fn into_items(self) -> Vec<DeliveredItem> {
470        self.items
471    }
472
473    /// The payloads alone, in order.
474    pub fn payloads(&self) -> impl Iterator<Item = &[u8]> {
475        self.items.iter().filter_map(|item| match item {
476            DeliveredItem::Payload(payload) => Some(payload.as_slice()),
477            _ => None,
478        })
479    }
480}
481
482/// The items one call produced, collected before they are ordered.
483#[derive(Debug, Default)]
484struct Batch {
485    delivered: Vec<DeliveredItem>,
486    reports: Vec<(usize, Damage)>,
487    end: Option<LinkEnd>,
488    refused: Option<DamageError>,
489}
490
491impl Batch {
492    /// Place the reports at the points they belong to, and the ending (or refusal) last.
493    fn finish(self, ended: &mut bool) -> Delivered {
494        let Batch {
495            mut delivered,
496            reports,
497            end,
498            refused,
499        } = self;
500        for (at, damage) in reports.into_iter().rev() {
501            delivered.insert(at, DeliveredItem::Damage(damage));
502        }
503        if let Some(error) = refused {
504            *ended = true;
505            delivered.push(DeliveredItem::Refused(error));
506        }
507        if let Some(end) = end {
508            *ended = true;
509            delivered.push(DeliveredItem::Ended(end));
510        }
511        Delivered { items: delivered }
512    }
513
514    fn payload(&mut self, payload: Payload) {
515        self.delivered.push(DeliveredItem::Payload(payload));
516    }
517
518    fn report(&mut self, damage: Damage) {
519        let at = self.delivered.len();
520        self.reports.push((at, damage));
521    }
522
523    fn end(&mut self, end: LinkEnd) {
524        self.end.get_or_insert(end);
525    }
526}
527
528/// A count-based loss a link reports once per cause, so a recurring condition is one report, not
529/// one per datagram.
530#[derive(Debug, Clone, Copy, PartialEq, Eq)]
531enum CountedCause {
532    /// The caller's payload check refused a delivered payload.
533    PayloadRefused,
534    /// An inbound DATA packet was further ahead of the delivery cursor than the flow window.
535    OutOfWindow,
536    /// An encrypted DATA packet could not be decrypted: no SEK for its `KK` parity, or the
537    /// AES-CTR pass failed.
538    Undecryptable,
539    /// The peer sent a `PeerError` control packet, which this link has no reply for.
540    PeerError,
541    /// A datagram from the peer did not parse as an SRT packet at all.
542    MalformedDatagram,
543    /// A key refresh could not be announced.
544    KeyRefreshFailed,
545    /// A refresh key reached its switchover point without the peer confirming it, so the old
546    /// key stays in use.
547    KeyRefreshUnconfirmed,
548}
549
550/// How many [`CountedCause`]s a link tracks a report for, one per slot below.
551const COUNTED_CAUSES: usize = 7;
552/// Every count-based cause in slot order.
553#[cfg(test)]
554const COUNTED_BY_SLOT: [CountedCause; COUNTED_CAUSES] = [
555    CountedCause::PayloadRefused,
556    CountedCause::OutOfWindow,
557    CountedCause::Undecryptable,
558    CountedCause::PeerError,
559    CountedCause::MalformedDatagram,
560    CountedCause::KeyRefreshFailed,
561    CountedCause::KeyRefreshUnconfirmed,
562];
563
564impl CountedCause {
565    const fn slot(self) -> usize {
566        match self {
567            CountedCause::PayloadRefused => 0,
568            CountedCause::OutOfWindow => 1,
569            CountedCause::Undecryptable => 2,
570            CountedCause::PeerError => 3,
571            CountedCause::MalformedDatagram => 4,
572            CountedCause::KeyRefreshFailed => 5,
573            CountedCause::KeyRefreshUnconfirmed => 6,
574        }
575    }
576
577    const fn what(self) -> &'static str {
578        match self {
579            CountedCause::PayloadRefused => "SRT delivered payload (refused by the host)",
580            CountedCause::OutOfWindow => "SRT data packet (beyond the flow window)",
581            CountedCause::Undecryptable => "SRT encrypted data packet (no usable key)",
582            CountedCause::PeerError => "SRT peer error",
583            CountedCause::MalformedDatagram => "SRT datagram (unparseable)",
584            CountedCause::KeyRefreshFailed => "SRT key refresh (key material not announced)",
585            CountedCause::KeyRefreshUnconfirmed => {
586                "SRT key refresh (switchover without confirmation)"
587            }
588        }
589    }
590}
591
592/// What a link has counted about the DATA it received, one total per kind, for a host that keeps
593/// statistics.
594#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
595#[non_exhaustive]
596pub struct LinkCounts {
597    /// Datagrams from the peer that did not parse as SRT packets.
598    pub unparseable: u64,
599    /// Delivered payloads the caller's payload check refused.
600    pub refused: u64,
601    /// Encrypted DATA packets with no usable key, or that failed decryption.
602    pub undecryptable: u64,
603    /// DATA packets that arrived after their sequence number was delivered or given up on.
604    pub late: u64,
605    /// DATA packets that arrived while a copy was already staged.
606    pub duplicates: u64,
607    /// Sequence numbers given up on: too late for TSBPD (§4.6) or named by a peer drop request.
608    pub lost: u64,
609    /// Key refreshes that could not be announced (no key-refresh entropy, or the key material
610    /// could not be built); each is retried on the next send.
611    pub key_refresh_failed: u64,
612    /// Refresh keys that reached their switchover point unconfirmed by the peer, so the old key
613    /// stayed in use.
614    pub key_refresh_unconfirmed: u64,
615}
616
617/// Which count-based causes a link has already reported.
618#[derive(Debug, Default)]
619struct DamageOnce {
620    reported: [bool; COUNTED_CAUSES],
621}
622
623impl DamageOnce {
624    fn slot(&mut self, cause: CountedCause) -> &mut bool {
625        &mut self.reported[cause.slot()]
626    }
627}
628
629/// One queued outbound DATA datagram. `retransmit` names the sequence number when the datagram is
630/// a retransmission, so the sender's "already queued" mark is cleared when it leaves the queue
631/// (#2819).
632#[derive(Debug)]
633struct OutboundData {
634    bytes: Vec<u8>,
635    retransmit: Option<u32>,
636}
637
638type SekSlot = Option<(Zeroizing<Vec<u8>>, [u8; crate::crypto::SALT_LEN])>;
639
640/// The even/odd SEKs (with their Salts) of ONE direction. A connection holds two: what this side
641/// encrypts with (generated by its own KM Refresh) and what it decrypts with (installed from the
642/// peer's Key Material), because each side rotates its own SEKs (§6.1.6).
643#[derive(Default)]
644struct KeySet {
645    even: SekSlot,
646    odd: SekSlot,
647}
648
649impl KeySet {
650    fn initial(sek: Option<&[u8]>, salt: Option<[u8; crate::crypto::SALT_LEN]>) -> Self {
651        let mut keys = KeySet::default();
652        if let (Some(sek), Some(salt)) = (sek, salt) {
653            keys.install(KeyParity::Even, sek.to_vec(), salt);
654        }
655        keys
656    }
657
658    fn slot(&self, parity: KeyParity) -> &SekSlot {
659        match parity {
660            KeyParity::Even => &self.even,
661            KeyParity::Odd => &self.odd,
662        }
663    }
664
665    fn slot_mut(&mut self, parity: KeyParity) -> &mut SekSlot {
666        match parity {
667            KeyParity::Even => &mut self.even,
668            KeyParity::Odd => &mut self.odd,
669        }
670    }
671
672    fn get(&self, parity: KeyParity) -> Option<(&[u8], [u8; crate::crypto::SALT_LEN])> {
673        self.slot(parity)
674            .as_ref()
675            .map(|(sek, salt)| (sek.as_slice(), *salt))
676    }
677
678    fn parity_of(key_field: EncryptionKeyField) -> Option<KeyParity> {
679        match key_field {
680            EncryptionKeyField::Even => Some(KeyParity::Even),
681            EncryptionKeyField::Odd => Some(KeyParity::Odd),
682            _ => None,
683        }
684    }
685
686    fn install(&mut self, parity: KeyParity, sek: Vec<u8>, salt: [u8; crate::crypto::SALT_LEN]) {
687        *self.slot_mut(parity) = Some((Zeroizing::new(sek), salt));
688    }
689
690    fn clear(&mut self, parity: KeyParity) {
691        *self.slot_mut(parity) = None;
692    }
693
694    fn is_empty(&self) -> bool {
695        self.even.is_none() && self.odd.is_none()
696    }
697}
698
699fn key_field_of(parity: KeyParity) -> EncryptionKeyField {
700    match parity {
701        KeyParity::Even => EncryptionKeyField::Even,
702        KeyParity::Odd => EncryptionKeyField::Odd,
703    }
704}
705
706fn parity_of_kk(kk: KmKeyFlag) -> Option<KeyParity> {
707    match kk {
708        KmKeyFlag::Even => Some(KeyParity::Even),
709        KmKeyFlag::Odd => Some(KeyParity::Odd),
710        _ => None,
711    }
712}
713
714/// A KMREQ announcing a refreshed SEK the peer has not confirmed with a KMRSP yet, re-sent every
715/// [`KM_RESEND_INTERVAL`] until it is.
716struct PendingKm {
717    parity: KeyParity,
718    salt: [u8; crate::crypto::SALT_LEN],
719    datagram: Vec<u8>,
720    resend_at_us: Option<u64>,
721}
722
723// ===========================================================================
724// Link — one established connection
725// ===========================================================================
726
727/// One established SRT connection, driven by datagrams and the caller's clock.
728///
729/// The host reads datagrams off its socket and calls [`Link::on_datagram`], wakes at the next
730/// [`Link::next_deadline`] and calls [`Link::poll`], sends what [`Link::take_sent`] hands back,
731/// and feeds application payloads in with [`Link::send`]. A host that owns an asynchronous socket
732/// wakes on both at once and calls [`Link::poll_io`] after every wake-up.
733pub struct Link {
734    peer_socket_id: u32,
735    epoch_us: u64,
736    receiver: ArqReceiver,
737    sender: ArqSender,
738    pacing_burst_packets: usize,
739    tsbpd: TsbpdScheduler,
740    livecc: LiveCC,
741    staged: BTreeMap<u32, Payload>,
742    outbound_control: Vec<Vec<u8>>,
743    outbound_data: VecDeque<OutboundData>,
744    next_message_number: u32,
745    next_send_seq: u32,
746    last_rx_us: u64,
747    last_tx_us: u64,
748    read_idle_us: u64,
749    max_flow_window: u32,
750    payload_admits: fn(&[u8]) -> bool,
751    damage_policy: DamagePolicy,
752    reported: DamageOnce,
753    counts: LinkCounts,
754    refuse_cleartext: bool,
755    ended: bool,
756    /// The earliest instant the next DATA packet may go out; `None` while no DATA packet is
757    /// pacing-blocked.
758    next_data_send_at_us: Option<u64>,
759    crypto_passphrase: Zeroizing<Vec<u8>>,
760    tx_keys: KeySet,
761    rx_keys: KeySet,
762    tx_parity: KeyParity,
763    km_pending: Option<PendingKm>,
764    retire_deferred: Option<KeyParity>,
765    crypto_key_len: usize,
766    km_refresh: KmRefreshDriver,
767    #[cfg(test)]
768    km_refresh_thresholds: KmRefreshThresholds,
769    kek_cache: crate::crypto::KekCache,
770    last_peer_kmreq_us: Option<u64>,
771    timers: LinkTimers,
772    key_refresh_seed: Zeroizing<Vec<u8>>,
773    key_refresh_counter: u64,
774    key_refresh_retry: Option<KeyParity>,
775    tx_key_sent: u64,
776    tx_key_limit: u64,
777    key_exhausted: bool,
778}
779
780impl Link {
781    /// Starts the silence clocks (peer idle and keep-alive) at `now`, the instant the connection
782    /// was concluded, when the link's own clock began earlier, at the handshake's start.
783    pub fn start_idle_clock(&mut self, now: Instant) {
784        self.last_rx_us = now.as_micros();
785        self.last_tx_us = now.as_micros();
786    }
787
788    /// An established link to the peer `setup` settled with, whose clock reads `now` at its start.
789    #[must_use]
790    pub fn new(now: Instant, setup: &LinkSetup, params: &CallerParams) -> Self {
791        let now_us = now.as_micros();
792        let peer_socket_id = setup.peer_socket_id();
793        Self {
794            peer_socket_id,
795            epoch_us: now_us,
796            receiver: ArqReceiver::new(
797                peer_socket_id,
798                setup.peer_initial_seq,
799                setup.params.max_flow_window_size,
800                setup.params.mtu,
801                params.arq.receiver,
802            ),
803            sender: ArqSender::new(peer_socket_id, params.arq.sender),
804            pacing_burst_packets: params.arq.sender.pacing_burst_packets,
805            tsbpd: TsbpdScheduler::new(
806                setup.peer_initial_seq,
807                setup.time_base(),
808                setup.params.latency,
809                params.drift_us,
810                setup.params.flags.tlpktdrop(),
811                None,
812                params.arq.receiver.max_pending_skips,
813                params.drift_window,
814            ),
815            livecc: LiveCC::new(params.max_bw),
816            staged: BTreeMap::new(),
817            outbound_control: Vec::new(),
818            outbound_data: VecDeque::new(),
819            next_message_number: 1,
820            next_send_seq: params.initial_seq_number,
821            last_rx_us: now_us,
822            last_tx_us: now_us,
823            read_idle_us: micros(params.timers.read_idle),
824            max_flow_window: setup.params.max_flow_window_size,
825            payload_admits: params.payload_admits,
826            damage_policy: params.damage_policy.clone(),
827            reported: DamageOnce::default(),
828            counts: LinkCounts::default(),
829            refuse_cleartext: params.refuse_cleartext,
830            ended: false,
831            next_data_send_at_us: None,
832            crypto_passphrase: Zeroizing::new(
833                params
834                    .handshake
835                    .crypto
836                    .as_ref()
837                    .map(|c| c.passphrase.as_slice().to_vec())
838                    .unwrap_or_default(),
839            ),
840            tx_keys: KeySet::initial(setup.params.sek.as_deref(), setup.params.salt),
841            rx_keys: KeySet::initial(setup.params.sek.as_deref(), setup.params.salt),
842            tx_parity: KeyParity::Even,
843            km_pending: None,
844            retire_deferred: None,
845            crypto_key_len: setup
846                .params
847                .sek
848                .as_ref()
849                .map(|sek| sek.len())
850                .or_else(|| setup.params.salt.map(|_| DEFAULT_SEK_LEN))
851                .unwrap_or(0),
852            km_refresh: KmRefreshDriver::new(params.km_refresh_thresholds, KeyParity::Even),
853            #[cfg(test)]
854            km_refresh_thresholds: params.km_refresh_thresholds,
855            kek_cache: crate::crypto::KekCache::default(),
856            last_peer_kmreq_us: None,
857            timers: params.timers,
858            key_refresh_seed: params.key_refresh_seed.clone(),
859            key_refresh_counter: 0,
860            key_refresh_retry: None,
861            tx_key_sent: 0,
862            tx_key_limit: KEYSTREAM_PACKETS,
863            key_exhausted: false,
864        }
865    }
866
867    /// The peer's SRT Socket ID: the `dest_socket_id` of every packet sent, and the one a
868    /// `SHUTDOWN` names.
869    #[must_use]
870    pub fn peer_socket_id(&self) -> u32 {
871        self.peer_socket_id
872    }
873
874    /// The `now` this link measures its protocol time from.
875    #[must_use]
876    pub fn epoch(&self) -> Instant {
877        Instant::from_micros(self.epoch_us)
878    }
879
880    /// Whether the link has ended: it delivers and sends nothing more.
881    #[must_use]
882    pub fn is_ended(&self) -> bool {
883        self.ended
884    }
885
886    /// Room in the send window: fewer than a full flow window of packets are buffered
887    /// unacknowledged (§3.2.1), so the host may hand another payload over.
888    #[must_use]
889    pub fn send_window_open(&self) -> bool {
890        let window = usize::try_from(self.max_flow_window)
891            .unwrap_or(usize::MAX)
892            .max(1);
893        self.sender.buffered_count() < window
894    }
895
896    /// The link's own clock: `now` since the connection started.
897    fn elapsed(&self, now_us: u64) -> Instant {
898        Instant::from_micros(now_us.saturating_sub(self.epoch_us))
899    }
900
901    /// The wire `Instant` for a control packet: it wraps modulo `2^32` past ~71.58 minutes.
902    fn wire_now(&self, now_us: u64) -> SrtTimestamp {
903        timestamp_to_wire_us(self.elapsed(now_us))
904    }
905
906    /// The `SHUTDOWN` datagram (§3.2.7) telling the peer this side is leaving. `None` once the
907    /// link has ended: the peer is already gone and has nothing left to be told.
908    #[must_use]
909    pub fn shutdown_datagram(&self, now: Instant) -> Option<Vec<u8>> {
910        if self.ended {
911            return None;
912        }
913        shutdown_datagram(
914            self.peer_socket_id,
915            Duration::from_micros(now.as_micros().saturating_sub(self.epoch_us)),
916        )
917    }
918
919    /// The sequence number the scheduler releases next: every packet below it is
920    /// delivered or given up on.
921    #[must_use]
922    pub fn next_release(&self) -> u32 {
923        self.tsbpd.next_release()
924    }
925
926    /// Whether Too-Late Packet Drop was negotiated (§4.6): only then may the
927    /// receiver skip a gap nothing filled in time.
928    #[must_use]
929    pub fn tlpktdrop_enabled(&self) -> bool {
930        self.tsbpd.tlpktdrop_enabled()
931    }
932
933    /// Set the LiveCC bandwidth policy that paces DATA packets from here on.
934    pub fn set_max_bw(&mut self, max_bw: MaxBwConfig) {
935        self.livecc.set_max_bw_config(max_bw);
936    }
937
938    /// The next Full ACK / NAK instant of the receive direction, if it has one.
939    #[must_use]
940    pub fn next_ack(&self) -> Option<Instant> {
941        self.receiver
942            .next_deadline()
943            .map(|t| Instant::from_micros(self.epoch_us.saturating_add(t.as_micros())))
944    }
945
946    /// The pacing period one DATA packet's slot advances by under the current policy.
947    #[must_use]
948    pub fn pacing_period(&self) -> Duration {
949        self.livecc.on_ack_received()
950    }
951
952    /// How many DATA and control datagrams are still queued for the wire.
953    #[must_use]
954    pub fn queued_len(&self) -> usize {
955        self.outbound_data.len() + self.outbound_control.len()
956    }
957
958    /// How many DATA packets are buffered, acknowledged or not.
959    #[must_use]
960    pub fn buffered_count(&self) -> usize {
961        self.sender.buffered_count()
962    }
963
964    /// How many sequence numbers are waiting to be retransmitted.
965    #[must_use]
966    pub fn pending_retransmit_count(&self) -> usize {
967        self.sender.pending_retransmit_count()
968    }
969
970    /// The mean DATA payload size LiveCC paces from.
971    #[must_use]
972    pub fn average_payload_size(&self) -> u64 {
973        self.livecc.avg_payload_size()
974    }
975
976    /// How many received packets are staged, waiting for TSBPD to release them.
977    #[must_use]
978    pub fn staged_len(&self) -> usize {
979        self.staged.len()
980    }
981
982    /// The cumulative ACK point of the receive direction: every sequence number
983    /// below it is accounted for, delivered or given up on.
984    #[must_use]
985    pub fn ack_point(&self) -> u32 {
986        self.receiver.ack_point()
987    }
988
989    /// How many received packets are missing between the delivery cursor and the
990    /// highest one seen.
991    #[must_use]
992    pub fn loss_list_len(&self) -> usize {
993        self.receiver.loss_list_len()
994    }
995
996    /// The receive direction's round-trip estimate (rule 33).
997    #[must_use]
998    pub fn rtt(&self) -> Duration {
999        self.receiver.rtt()
1000    }
1001
1002    #[cfg(test)]
1003    /// The count-based drops this link has already reported, one flag per cause:
1004    /// a refused payload, an out-of-window packet, an undecryptable packet, a
1005    /// peer error, an unparseable datagram.
1006    #[must_use]
1007    pub fn reported_causes(&self) -> [bool; COUNTED_CAUSES] {
1008        self.reported.reported
1009    }
1010
1011    /// What this link has counted about the DATA it received.
1012    #[must_use]
1013    pub fn counts(&self) -> LinkCounts {
1014        self.counts
1015    }
1016
1017    #[cfg(test)]
1018    /// The reason a count-based report names for the cause at `index` of
1019    /// [`Link::reported_causes`].
1020    #[must_use]
1021    pub fn counted_cause_what(index: usize) -> Option<&'static str> {
1022        COUNTED_BY_SLOT.get(index).copied().map(CountedCause::what)
1023    }
1024
1025    /// The sequence number the next first transmission carries.
1026    #[must_use]
1027    pub fn next_send_seq(&self) -> u32 {
1028        self.next_send_seq
1029    }
1030
1031    /// The message number the next first transmission carries.
1032    #[must_use]
1033    pub fn next_message_number(&self) -> u32 {
1034        self.next_message_number
1035    }
1036
1037    #[cfg(test)]
1038    /// Put the next message number where `next` is, so a host can start a
1039    /// connection from an arbitrary point of the wrapping space.
1040    pub fn set_next_message_number(&mut self, next: u32) {
1041        self.next_message_number = next;
1042    }
1043
1044    #[cfg(test)]
1045    /// Set the §6 passphrase a peer's Key Material is recovered with.
1046    pub fn set_passphrase(&mut self, passphrase: Vec<u8>) {
1047        self.crypto_passphrase = Zeroizing::new(passphrase);
1048    }
1049
1050    #[cfg(test)]
1051    /// Whether both direction keys are installed (a `KK = Both` exchange).
1052    #[must_use]
1053    pub fn rx_keys_installed(&self) -> bool {
1054        self.rx_keys.get(KeyParity::Even).is_some() && self.rx_keys.get(KeyParity::Odd).is_some()
1055    }
1056
1057    #[cfg(test)]
1058    /// How many Key Material messages this connection has derived a KEK for.
1059    #[must_use]
1060    pub fn kek_derivations(&self) -> u64 {
1061        self.kek_cache.derivations()
1062    }
1063
1064    #[cfg(test)]
1065    /// Which of the two keys new outgoing packets are encrypted under.
1066    #[must_use]
1067    pub fn tx_parity_name(&self) -> &'static str {
1068        self.tx_parity.name()
1069    }
1070
1071    #[cfg(test)]
1072    /// Whether a refreshed SEK is still waiting for the peer's confirmation.
1073    #[must_use]
1074    pub fn refresh_pending(&self) -> bool {
1075        self.km_pending.is_some()
1076    }
1077
1078    #[cfg(test)]
1079    /// Put `sek` in the send direction under `parity`, without touching the active one.
1080    fn install_key(&mut self, parity: KeyParity, sek: Vec<u8>) {
1081        self.tx_keys
1082            .install(parity, sek, [0; crate::crypto::SALT_LEN]);
1083    }
1084
1085    #[cfg(test)]
1086    /// Put a key under `parity` and make that parity the send direction's active one.
1087    pub fn install_active_parity(&mut self, parity: KeyParity) {
1088        self.tx_keys.install(
1089            parity,
1090            alloc::vec![3u8; DEFAULT_SEK_LEN],
1091            [0; crate::crypto::SALT_LEN],
1092        );
1093        self.tx_parity = parity;
1094        self.km_refresh = KmRefreshDriver::new(self.km_refresh_thresholds, parity);
1095    }
1096
1097    #[cfg(test)]
1098    /// Mark `parity` for retirement at the next key refresh.
1099    pub fn defer_retire(&mut self, parity: KeyParity) {
1100        self.retire_deferred = Some(parity);
1101    }
1102
1103    #[cfg(test)]
1104    /// Whether the send direction holds a key under `parity`.
1105    #[must_use]
1106    pub fn tx_key_installed(&self, parity: KeyParity) -> bool {
1107        self.tx_keys.get(parity).is_some()
1108    }
1109
1110    #[cfg(test)]
1111    /// The length of the send direction's key under `parity`.
1112    #[must_use]
1113    pub fn tx_key_len(&self, parity: KeyParity) -> Option<usize> {
1114        self.tx_keys.get(parity).map(|(sek, _)| sek.len())
1115    }
1116
1117    #[cfg(test)]
1118    /// Run one key-refresh step at `now`.
1119    pub fn advance_key_refresh(&mut self, now_us: u64) {
1120        self.advance_key_refresh_step(now_us);
1121    }
1122
1123    #[cfg(test)]
1124    /// Announce a refreshed key for `parity` at `now`.
1125    pub fn announce_key_for_test(&mut self, parity: KeyParity) {
1126        self.announce_key(parity, 0);
1127    }
1128
1129    #[cfg(test)]
1130    /// Replace the pending KMREQ with a fixed datagram due at `resend_at_us`.
1131    fn pend_km_for_test(&mut self, parity: KeyParity, datagram: Vec<u8>, resend_at_us: u64) {
1132        self.km_pending = Some(PendingKm {
1133            parity,
1134            salt: [0; crate::crypto::SALT_LEN],
1135            datagram,
1136            resend_at_us: Some(resend_at_us),
1137        });
1138    }
1139
1140    #[cfg(test)]
1141    /// Install `sek` under both directions for `passphrase`, with KM Refresh at
1142    /// `thresholds` — the state a test starts a refresh from.
1143    pub fn install_refresh_test_keys(
1144        &mut self,
1145        passphrase: &[u8],
1146        sek: &[u8],
1147        salt: [u8; crate::crypto::SALT_LEN],
1148        thresholds: KmRefreshThresholds,
1149    ) {
1150        self.set_passphrase(passphrase.to_vec());
1151        self.crypto_key_len = sek.len();
1152        for keys in [&mut self.tx_keys, &mut self.rx_keys] {
1153            keys.install(KeyParity::Even, sek.to_vec(), salt);
1154        }
1155        self.km_refresh = KmRefreshDriver::new(thresholds, KeyParity::Even);
1156        self.km_refresh_thresholds = thresholds;
1157    }
1158
1159    /// The next instant this link must act without any inbound event: the next Full ACK / NAK, the
1160    /// next TSBPD release, the Keep-Alive when idle, the peer-idle expiry, a pending KMREQ resend
1161    /// and the next pacing slot. A deadline the clock cannot name is no deadline; the others still
1162    /// bind. `None` once the link has ended.
1163    #[must_use]
1164    pub fn next_deadline(&self, now: Instant) -> Option<Instant> {
1165        self.next_deadline_micros(now.as_micros())
1166            .map(Instant::from_micros)
1167    }
1168
1169    fn next_deadline_micros(&self, now_us: u64) -> Option<u64> {
1170        if self.ended {
1171            return None;
1172        }
1173        let fold = |at: Option<u64>, candidate: Option<u64>| match (at, candidate) {
1174            (Some(a), Some(c)) => Some(a.min(c)),
1175            (Some(a), None) => Some(a),
1176            (None, c) => c,
1177        };
1178        // Every span here can pass the end of the clock, which the host cannot
1179        // represent: such a term never fires.
1180        let span = |from: u64, len: u64| from.checked_add(len);
1181        let mut at = self
1182            .receiver
1183            .next_deadline()
1184            .and_then(|t| span(self.epoch_us, t.as_micros()));
1185        if let Some(t) = self.tsbpd.next_release_after(self.elapsed(now_us)) {
1186            at = fold(at, span(self.epoch_us, micros(t)));
1187        }
1188        if self.outbound_control.is_empty() && self.outbound_data.is_empty() {
1189            at = fold(
1190                at,
1191                span(self.last_tx_us, micros(self.timers.cadence.keepalive)),
1192            );
1193        }
1194        at = fold(at, span(self.last_rx_us, self.read_idle_us));
1195        if let Some(pending) = &self.km_pending {
1196            at = fold(at, pending.resend_at_us);
1197        }
1198        if !self.outbound_data.is_empty() {
1199            at = fold(at, self.next_data_send_at_us);
1200        }
1201        // Never a deadline already past, and never a spin: the same 1 ms floor every hosted
1202        // adapter of this crate keeps.
1203        at.map(|at| at.max(now_us.saturating_add(micros(MIN_WAKE))))
1204    }
1205
1206    /// How long until the DATA packet at the front of the queue may go out: `None`
1207    /// when the queue is empty or its slot has already arrived.
1208    #[must_use]
1209    pub fn next_paced_send_wait(&self, now: Instant) -> Option<Duration> {
1210        if self.outbound_data.is_empty() {
1211            return None;
1212        }
1213        let deadline = self.next_data_send_at_us?;
1214        Some(Duration::from_micros(
1215            deadline.saturating_sub(now.as_micros()),
1216        ))
1217    }
1218
1219    /// Feed one application payload for first transmission at `now`. It is encrypted (§6) when
1220    /// the connection negotiated it, queued behind any retransmission, and sent by the next
1221    /// [`Link::poll`] or [`Link::poll_io`].
1222    pub fn send(&mut self, payload: &[u8], now: Instant) {
1223        let now_us = now.as_micros();
1224        if self.ended || self.key_exhausted {
1225            return;
1226        }
1227        self.livecc
1228            .on_data_packet(u64::try_from(payload.len()).unwrap_or(u64::MAX));
1229
1230        self.advance_key_refresh_step(now_us);
1231
1232        if self.tx_keys.get(self.tx_parity).is_some() {
1233            if self.tx_key_sent >= self.tx_key_limit {
1234                self.key_exhausted = true;
1235                return;
1236            }
1237            self.tx_key_sent = self.tx_key_sent.saturating_add(1);
1238        }
1239        let encrypted: Option<Vec<u8>> = match self.tx_keys.get(self.tx_parity) {
1240            Some((sek, salt)) => {
1241                let mut enc = payload.to_vec();
1242                if crate::crypto::aes_ctr_apply(sek, &salt, self.next_send_seq, &mut enc).is_err() {
1243                    return;
1244                }
1245                Some(enc)
1246            }
1247            None => None,
1248        };
1249        let key_flag = if encrypted.is_some() {
1250            key_field_of(self.tx_parity)
1251        } else {
1252            EncryptionKeyField::NotEncrypted
1253        };
1254        let payload = encrypted.as_deref().unwrap_or(payload);
1255
1256        // The counters are kept within their wire widths, so framing them cannot fail; if it ever
1257        // did, the payload is dropped, not the link.
1258        let Ok(bytes) = self.sender.on_data_keyed(
1259            self.next_send_seq,
1260            self.next_message_number,
1261            payload,
1262            key_flag,
1263            self.elapsed(now_us),
1264        ) else {
1265            return;
1266        };
1267        self.next_send_seq = seq_next(self.next_send_seq);
1268        self.next_message_number = next_message_number(self.next_message_number);
1269        self.outbound_data.push_back(OutboundData {
1270            bytes,
1271            retransmit: None,
1272        });
1273    }
1274
1275    /// Take the datagrams queued for the peer since the last call, in send order: first
1276    /// transmissions, retransmissions and control feedback alike. They may leave at once — a host
1277    /// that writes them calls [`Link::flush`] instead, which applies the pacing slot and records the
1278    /// transmission the Keep-Alive period counts from.
1279    #[must_use]
1280    pub fn take_sent(&mut self) -> Vec<Vec<u8>> {
1281        let mut sent = core::mem::take(&mut self.outbound_control);
1282        sent.reserve(self.outbound_data.len());
1283        while let Some(datagram) = self.outbound_data.pop_front() {
1284            sent.push(datagram.bytes);
1285        }
1286        sent
1287    }
1288
1289    /// Process one datagram from the peer at `now`, returning what it delivered.
1290    #[must_use]
1291    pub fn on_datagram(&mut self, datagram: &[u8], now: Instant) -> Delivered {
1292        self.on_owned_datagram(datagram.to_vec(), now)
1293    }
1294
1295    /// [`Link::on_datagram`] for a datagram the host owns: a payload it delivers stays in this
1296    /// datagram's allocation (see [`Payload`]), so receiving it costs no copy.
1297    #[must_use]
1298    pub fn on_owned_datagram(&mut self, datagram: Vec<u8>, now: Instant) -> Delivered {
1299        let now_us = now.as_micros();
1300        if self.ended {
1301            return Delivered::default();
1302        }
1303        let mut batch = Batch::default();
1304        self.ingress(datagram, now_us, &mut batch);
1305        batch.finish(&mut self.ended)
1306    }
1307
1308    /// Run the timers at `now` — retransmissions, ACK/NAK, the Keep-Alive, a KMREQ resend and
1309    /// the TSBPD release — returning what it delivered.
1310    #[must_use]
1311    pub fn poll(&mut self, now: Instant) -> Delivered {
1312        let now_us = now.as_micros();
1313        if self.ended {
1314            return Delivered::default();
1315        }
1316        let mut batch = Batch::default();
1317        if now_us.saturating_sub(self.last_rx_us) >= self.read_idle_us {
1318            batch.end(LinkEnd::PeerIdle);
1319            return batch.finish(&mut self.ended);
1320        }
1321        self.tick_engines(now_us, &mut batch);
1322        batch.finish(&mut self.ended)
1323    }
1324
1325    /// The timer pass and the outbound flush a host loop runs after every wake-up: the engines at
1326    /// `now`, then every datagram due — appended to `sent` — control at once and DATA at its
1327    /// pacing slot. Returns what the timer pass delivered; a host that also keeps a delivery
1328    /// channel hands it on.
1329    #[must_use]
1330    pub fn poll_io(&mut self, now: Instant, sent: &mut Vec<Vec<u8>>) -> Delivered {
1331        let now_us = now.as_micros();
1332        if self.ended {
1333            return Delivered::default();
1334        }
1335        let mut batch = Batch::default();
1336        self.tick_engines(now_us, &mut batch);
1337        self.flush(now, sent);
1338        batch.finish(&mut self.ended)
1339    }
1340
1341    fn ingress(&mut self, datagram: Vec<u8>, now_us: u64, batch: &mut Batch) {
1342        // Any datagram from the peer — even one that fails to parse below — is evidence the peer
1343        // is still there, resetting the idle timeout.
1344        self.last_rx_us = now_us;
1345        let now = self.elapsed(now_us);
1346        let Ok(packet) = SrtPacket::parse(&datagram) else {
1347            self.counts.unparseable = self.counts.unparseable.saturating_add(1);
1348            self.report_counted(CountedCause::MalformedDatagram, 1, batch);
1349            return;
1350        };
1351        match packet {
1352            SrtPacket::Data(d) => {
1353                let (seq_number, timestamp, key_flag) = (d.seq_number, d.timestamp, d.key_flag);
1354                let Some(payload) = self.payload(datagram, seq_number, key_flag, batch) else {
1355                    return;
1356                };
1357                self.ingress_data(payload, seq_number, timestamp, now, batch);
1358            }
1359            SrtPacket::Control(c) => self.ingress_control(&c, now, now_us, batch),
1360        }
1361    }
1362
1363    fn ingress_data(
1364        &mut self,
1365        payload: Payload,
1366        seq_number: u32,
1367        timestamp: SrtTimestamp,
1368        now: Instant,
1369        batch: &mut Batch,
1370    ) {
1371        // A packet that is not ahead of the delivery cursor (a duplicate, a retransmission of what
1372        // was delivered or given up on, or a stale sequence number) has nothing left to do: it is
1373        // never staged at all.
1374        if seq_lt(seq_number, self.tsbpd.next_release()) {
1375            self.counts.late = self.counts.late.saturating_add(1);
1376            return;
1377        }
1378        let outcome = self.receiver.feed_data(seq_number, now);
1379        if outcome.out_of_window {
1380            self.report_counted(CountedCause::OutOfWindow, 1, batch);
1381            return;
1382        }
1383        if let Some(nak_bytes) = outcome.nak {
1384            self.outbound_control.push(nak_bytes);
1385        }
1386        // The staging buffer is what TSBPD releases from, in strict sequence order, waiting for a
1387        // NAK-recovered gap until the next buffered packet's play time, at which point live mode
1388        // skips an unrecoverable gap (only under TLPKTDROP, §3.2.1.1.1).
1389        if self.staged.contains_key(&seq_number) {
1390            self.counts.duplicates = self.counts.duplicates.saturating_add(1);
1391        }
1392        self.staged.entry(seq_number).or_insert(payload);
1393        let tsbpd_out = self.tsbpd.feed_data(seq_number, timestamp.value(), now);
1394        self.release(&tsbpd_out, batch);
1395    }
1396
1397    /// The DATA payload of `datagram`, decrypted when it was encrypted. `None` when it cannot be
1398    /// staged: no usable key, or a failed decryption pass, both reported once.
1399    fn payload(
1400        &mut self,
1401        mut datagram: Vec<u8>,
1402        seq_number: u32,
1403        key_flag: EncryptionKeyField,
1404        batch: &mut Batch,
1405    ) -> Option<Payload> {
1406        datagram.get(SRT_HEADER_LEN..)?;
1407        if key_flag == EncryptionKeyField::NotEncrypted {
1408            if self.refuse_cleartext && self.crypto_key_len != 0 {
1409                self.undecryptable(batch);
1410                return None;
1411            }
1412        } else {
1413            let keys = KeySet::parity_of(key_flag).and_then(|p| self.rx_keys.get(p));
1414            let Some((sek, salt)) = keys else {
1415                self.undecryptable(batch);
1416                return None;
1417            };
1418            let data = datagram.get_mut(SRT_HEADER_LEN..)?;
1419            if crate::crypto::aes_ctr_apply(sek, &salt, seq_number, data).is_err() {
1420                self.undecryptable(batch);
1421                return None;
1422            }
1423        }
1424        Some(Payload {
1425            datagram,
1426            start: SRT_HEADER_LEN,
1427        })
1428    }
1429
1430    fn undecryptable(&mut self, batch: &mut Batch) {
1431        self.counts.undecryptable = self.counts.undecryptable.saturating_add(1);
1432        self.report_counted(CountedCause::Undecryptable, 1, batch);
1433    }
1434
1435    fn ingress_control(
1436        &mut self,
1437        c: &ControlPacket<'_>,
1438        now: Instant,
1439        now_us: u64,
1440        batch: &mut Batch,
1441    ) {
1442        match c {
1443            ControlPacket::Ack(ack) => {
1444                if let Some(ackack_bytes) = self.sender.on_ack(ack, now) {
1445                    self.outbound_control.push(ackack_bytes);
1446                }
1447            }
1448            // Record the reported loss; the next timer pass drains the retransmit queue —
1449            // retransmits are queued ahead of any new first-time data (rules 5, 15, 16).
1450            ControlPacket::Nak(nak) => self.sender.on_nak(nak),
1451            ControlPacket::AckAck(ackack) => self.receiver.on_ackack(ackack, now),
1452            ControlPacket::DropReq(d) => self.handle_dropreq(d, now, batch),
1453            // A Keep-Alive only tells us the peer is alive (`last_rx_us` is already refreshed);
1454            // it is not answered.
1455            ControlPacket::KeepAlive(_) => {}
1456            ControlPacket::Shutdown(_) => batch.end(LinkEnd::PeerShutdown),
1457            ControlPacket::PeerError(p) => {
1458                self.report_counted(CountedCause::PeerError, u64::from(p.error_code), batch);
1459            }
1460            ControlPacket::UserDefined(u) => {
1461                if let Ok(km) = u.as_key_material() {
1462                    self.on_peer_key_material(u.subtype, &km, now_us);
1463                }
1464            }
1465            _ => {}
1466        }
1467    }
1468
1469    /// Handle a DROPREQ (§3.2.9): the peer announces it will never deliver sequence numbers
1470    /// `first..=last`. Tell the ARQ receiver to stop NAKing them and advance its ack point, tell
1471    /// the TSBPD scheduler to skip them, discard anything already staged inside the range, then
1472    /// drive one release pass so whatever the gap blocked becomes deliverable immediately.
1473    fn handle_dropreq(&mut self, d: &DropReqPacket, now: Instant, batch: &mut Batch) {
1474        let first = d.first_seq.value();
1475        let last = d.last_seq.value();
1476        if seq_diff(last, first) < 0 {
1477            return;
1478        }
1479        let reach = seq_diff(last, self.receiver.ack_point());
1480        if !u32::try_from(reach).is_ok_and(|ahead| ahead <= self.max_flow_window) {
1481            return;
1482        }
1483        self.receiver.skip_range(first, last);
1484        self.tsbpd.skip_range(first, last);
1485        self.staged
1486            .retain(|&s, _| !seq_in_closed_range(s, first, last));
1487        let tsbpd_out = self.tsbpd.tick(now);
1488        self.release(&tsbpd_out, batch);
1489    }
1490
1491    /// Apply one TSBPD outcome: publish the released payloads and purge anything the scheduler
1492    /// gave up on.
1493    ///
1494    /// What the scheduler gave up on (§4.6) is also skipped in the ARQ receiver: its ack point then
1495    /// moves past the dropped packets — the "fake ACK" of Too-Late Packet Drop — so it stops NAKing
1496    /// packets that can no longer be delivered. The two lists are merged on sequence number so a
1497    /// payload past a skipped gap is published only after the report naming that skip.
1498    fn release(&mut self, outcome: &TickOutcome, batch: &mut Batch) {
1499        let lost: Vec<u32> = outcome.dropped.iter().map(|p| p.seq_number).collect();
1500        self.counts.lost = self
1501            .counts
1502            .lost
1503            .saturating_add(u64::try_from(lost.len()).unwrap_or(u64::MAX));
1504        for packet in &outcome.dropped {
1505            self.staged.remove(&packet.seq_number);
1506        }
1507        for (first, last) in contiguous_runs(&lost) {
1508            self.receiver.skip_range(first, last);
1509        }
1510        let dropped = &outcome.dropped;
1511        let mut next_delivered = 0usize;
1512        let mut run_start = 0usize;
1513        while run_start < dropped.len() {
1514            let run_end = run_start
1515                + contiguous_runs(&lost[run_start..])
1516                    .first()
1517                    .copied()
1518                    .map_or(0, |(_, last)| seq_diff(last, lost[run_start]) as usize + 1);
1519            while let Some(&seq) = outcome.delivered.get(next_delivered) {
1520                if seq_lt(seq, dropped[run_start].seq_number) {
1521                    self.deliver_payload(seq, batch);
1522                    next_delivered += 1;
1523                } else {
1524                    break;
1525                }
1526            }
1527            for damage in damage_reports::reports(&dropped[run_start..run_end]) {
1528                self.report(damage, batch);
1529            }
1530            run_start = run_end;
1531        }
1532        for &seq in &outcome.delivered[next_delivered..] {
1533            self.deliver_payload(seq, batch);
1534        }
1535    }
1536
1537    /// Hand one released payload to the host, unless the caller's check refuses its format.
1538    fn deliver_payload(&mut self, seq: u32, batch: &mut Batch) {
1539        let Some(payload) = self.staged.remove(&seq) else {
1540            return;
1541        };
1542        if (self.payload_admits)(payload.as_slice()) {
1543            batch.payload(payload);
1544        } else {
1545            self.counts.refused = self.counts.refused.saturating_add(1);
1546            self.report_counted(CountedCause::PayloadRefused, 1, batch);
1547        }
1548    }
1549
1550    /// Hand one report to the caller's policy: publish it, or end the link with it when the policy
1551    /// says `Fail`.
1552    fn report(&mut self, damage: Damage, batch: &mut Batch) {
1553        match self.damage_policy.admit(damage) {
1554            Ok(damage) => batch.report(damage),
1555            Err(error) => {
1556                batch.refused = Some(error);
1557                self.ended = true;
1558            }
1559        }
1560    }
1561
1562    /// Report a loss this link only counts, once per cause.
1563    fn report_counted(&mut self, cause: CountedCause, count: u64, batch: &mut Batch) {
1564        if *self.reported.slot(cause) {
1565            return;
1566        }
1567        *self.reported.slot(cause) = true;
1568        self.report(
1569            damage_reports::dropped_before_delivery(cause.what(), count),
1570            batch,
1571        );
1572    }
1573
1574    fn tick_engines(&mut self, now_us: u64, batch: &mut Batch) {
1575        if self.ended {
1576            return;
1577        }
1578        let now = self.elapsed(now_us);
1579        if self.key_exhausted {
1580            batch.end(LinkEnd::KeyExhausted);
1581            return;
1582        }
1583        if self.counts.key_refresh_unconfirmed > 0 {
1584            self.report_counted(
1585                CountedCause::KeyRefreshUnconfirmed,
1586                self.counts.key_refresh_unconfirmed,
1587                batch,
1588            );
1589        }
1590        if self.counts.key_refresh_failed > 0 {
1591            self.report_counted(
1592                CountedCause::KeyRefreshFailed,
1593                self.counts.key_refresh_failed,
1594                batch,
1595            );
1596        }
1597
1598        // Retransmitted DATA packets first (rules 5, 15, 16, 18): they drain the NAK-populated
1599        // loss list and are queued before any first-time data, reproducing the sans-IO engine's
1600        // "loss list before first transmission" priority.
1601        let queue_cap = usize::try_from(self.max_flow_window).unwrap_or(usize::MAX);
1602        for (seq, bytes) in self.sender.tick(now) {
1603            self.livecc.on_data_packet(
1604                u64::try_from(bytes.len().saturating_sub(SRT_HEADER_LEN)).unwrap_or(u64::MAX),
1605            );
1606            // Retransmissions are capped at the negotiated flow window: a NAK naming the whole
1607            // send buffer must not turn into an unbounded queue (#2819). A dropped retransmission
1608            // stays in the sender's loss list and is offered again by a later tick.
1609            if self.outbound_data.len() < queue_cap {
1610                self.outbound_data.push_back(OutboundData {
1611                    bytes,
1612                    retransmit: Some(seq),
1613                });
1614            } else {
1615                self.sender.on_retransmit_dropped(seq);
1616            }
1617        }
1618
1619        // Keep-Alive (§3.2.3): a connection that has sent nothing for a second says so, or the
1620        // peer's own idle timeout ends it. Judged before this pass's ACK/NAK are queued: it asks
1621        // whether anything has gone out for a second, not whether something is about to.
1622        if self.outbound_control.is_empty()
1623            && self.outbound_data.is_empty()
1624            && now_us.saturating_sub(self.last_tx_us) >= micros(self.timers.cadence.keepalive)
1625        {
1626            self.queue_keepalive(now_us);
1627        }
1628
1629        self.resend_pending_km(now_us);
1630
1631        // Periodic ACK/NAK (rules 11, 12, 21, 22): control feedback, never paced.
1632        for bytes in self.receiver.tick(now) {
1633            self.outbound_control.push(bytes);
1634        }
1635
1636        let tsbpd_out = self.tsbpd.tick(now);
1637        self.release(&tsbpd_out, batch);
1638    }
1639
1640    fn queue_keepalive(&mut self, now_us: u64) {
1641        let pkt = ControlPacket::KeepAlive(KeepAlivePacket {
1642            timestamp: self.wire_now(now_us),
1643            dest_socket_id: SocketId::from_wire(self.peer_socket_id),
1644            libsrt_pad: true,
1645        });
1646        let mut buf = alloc::vec![0u8; pkt.serialized_len()];
1647        if pkt.serialize_into(&mut buf).is_ok() {
1648            self.outbound_control.push(buf);
1649        }
1650    }
1651
1652    /// Append every outbound datagram due at `now`, in order, without blocking on the pacing
1653    /// delay itself: control in full, then DATA while its pacing slot has arrived. [`Link::poll_io`]
1654    /// runs the timers first, as a host loop does after every wake-up.
1655    ///
1656    /// §5.1.2 paces DATA packets only: control feedback (ACK/NAK/ACKACK/Keep-Alive) goes out
1657    /// immediately, or loss recovery would be throttled along with the data it unblocks. DATA is
1658    /// scheduled against `next_data_send_at_us`, a token-bucket-style deadline rather than a sleep:
1659    /// the schedule advances from whichever is later of the previous slot or now, but never more
1660    /// than [`SenderBounds::pacing_burst_packets`](crate::arq::SenderBounds::pacing_burst_packets) periods of catch-up credit in one pass, so a burst after an idle
1661    /// gap sends at once while a sustained flood stays throttled.
1662    pub fn flush(&mut self, now: Instant, sent: &mut Vec<Vec<u8>>) {
1663        let now_us = now.as_micros();
1664        let mut count = self.outbound_control.len();
1665        sent.append(&mut self.outbound_control);
1666        let mut paced = 0;
1667        while !self.outbound_data.is_empty() && paced < self.pacing_burst_packets {
1668            if let Some(deadline) = self.next_data_send_at_us
1669                && now_us < deadline
1670            {
1671                break;
1672            }
1673            let Some(datagram) = self.outbound_data.pop_front() else {
1674                break;
1675            };
1676            if let Some(seq) = datagram.retransmit {
1677                self.sender.on_retransmit_sent(seq);
1678            }
1679            let period = micros(self.livecc.on_ack_received());
1680            let floor =
1681                now_us.saturating_sub(period.saturating_mul(self.pacing_burst_packets as u64));
1682            let base = self.next_data_send_at_us.map_or(now_us, |t| t.max(floor));
1683            self.next_data_send_at_us = base.checked_add(period);
1684            paced += 1;
1685            count += 1;
1686            sent.push(datagram.bytes);
1687        }
1688        // An idle connection owes nothing: drop an expired slot so the next backlog starts at
1689        // "now" instead of replaying the idle gap as credit.
1690        if self.outbound_data.is_empty() {
1691            self.next_data_send_at_us = self.next_data_send_at_us.filter(|&t| t > now_us);
1692        }
1693        if count > 0 {
1694            self.last_tx_us = now_us;
1695        }
1696    }
1697
1698    fn advance_key_refresh_step(&mut self, now_us: u64) {
1699        if let Some(parity) = self.key_refresh_retry.take() {
1700            self.announce_key(parity, now_us);
1701        }
1702        if self.tx_keys.is_empty() {
1703            return;
1704        }
1705        for ev in self.km_refresh.on_packet_sent(1) {
1706            match ev {
1707                KmRefreshEvent::PreAnnounce { next_parity } => {
1708                    self.announce_key(next_parity, now_us);
1709                }
1710                KmRefreshEvent::Switchover { .. } => {
1711                    if self.km_pending.is_some() {
1712                        self.counts.key_refresh_unconfirmed =
1713                            self.counts.key_refresh_unconfirmed.saturating_add(1);
1714                    }
1715                }
1716                KmRefreshEvent::Decommission { retired } => self.retire_deferred = Some(retired),
1717            }
1718        }
1719        if self.km_pending.is_none() {
1720            let active = self.km_refresh.active_parity();
1721            if active != self.tx_parity {
1722                self.tx_parity = active;
1723                self.tx_key_sent = 0;
1724            }
1725        }
1726        if let Some(retired) = self.retire_deferred
1727            && retired != self.tx_parity
1728        {
1729            self.tx_keys.clear(retired);
1730            self.retire_deferred = None;
1731        }
1732    }
1733
1734    fn key_refresh_failed(&mut self, parity: KeyParity) {
1735        self.counts.key_refresh_failed = self.counts.key_refresh_failed.saturating_add(1);
1736        self.key_refresh_retry = Some(parity);
1737    }
1738
1739    fn announce_key(&mut self, parity: KeyParity, now_us: u64) {
1740        if self.km_pending.is_some() {
1741            return;
1742        }
1743        let key_len = if self.crypto_key_len == 0 {
1744            DEFAULT_SEK_LEN
1745        } else {
1746            self.crypto_key_len
1747        };
1748        if self.key_refresh_seed.len() < MIN_KEY_REFRESH_SEED_LEN || key_len > KEY_LEN {
1749            self.key_refresh_failed(parity);
1750            return;
1751        }
1752        let draw = self.key_refresh_counter;
1753        self.key_refresh_counter = draw.saturating_add(1);
1754        let mut salt = [0u8; crate::crypto::SALT_LEN];
1755        salt.copy_from_slice(
1756            &derive(&self.key_refresh_seed, LABEL_REFRESH_SALT, draw)[..crate::crypto::SALT_LEN],
1757        );
1758        let sek = derive(&self.key_refresh_seed, LABEL_REFRESH_SEK, draw)[..key_len].to_vec();
1759        let Ok(kek) = crate::crypto::derive_kek(&self.crypto_passphrase, &salt, key_len) else {
1760            self.key_refresh_failed(parity);
1761            return;
1762        };
1763        let Ok((icv, wrapped)) = crate::crypto::wrap_sek(&kek, &sek) else {
1764            self.key_refresh_failed(parity);
1765            return;
1766        };
1767        let km = KeyMaterial {
1768            kk: match parity {
1769                KeyParity::Even => KmKeyFlag::Even,
1770                KeyParity::Odd => KmKeyFlag::Odd,
1771            },
1772            keki: 0,
1773            cipher: crate::packet::Cipher::AesCtr,
1774            auth: crate::packet::KmAuth::None,
1775            se: crate::packet::StreamEncapsulation::MpegTsSrt,
1776            salt: &salt,
1777            icv,
1778            x_sek: &wrapped,
1779            o_sek: None,
1780        };
1781        let Some(datagram) = self.key_material_datagram(EXT_TYPE_KMREQ, &km, now_us) else {
1782            self.key_refresh_failed(parity);
1783            return;
1784        };
1785        self.tx_keys.install(parity, sek, salt);
1786        self.outbound_control.push(datagram.clone());
1787        self.km_pending = Some(PendingKm {
1788            parity,
1789            salt,
1790            datagram,
1791            resend_at_us: now_us.checked_add(micros(self.timers.cadence.km_resend)),
1792        });
1793    }
1794
1795    fn key_material_datagram(
1796        &self,
1797        subtype: u16,
1798        km: &KeyMaterial<'_>,
1799        now_us: u64,
1800    ) -> Option<Vec<u8>> {
1801        let mut cif = alloc::vec![0u8; km.serialized_len()];
1802        km.serialize_into(&mut cif).ok()?;
1803        let ud = ControlPacket::UserDefined(crate::packet::UserDefinedPacket {
1804            control_type: crate::packet::ControlType::UserDefined.to_bits(),
1805            subtype,
1806            type_specific_info: 0,
1807            timestamp: self.wire_now(now_us),
1808            dest_socket_id: SocketId::from_wire(self.peer_socket_id),
1809            cif: &cif,
1810        });
1811        let mut out = alloc::vec![0u8; ud.serialized_len()];
1812        ud.serialize_into(&mut out).ok()?;
1813        Some(out)
1814    }
1815
1816    fn resend_pending_km(&mut self, now_us: u64) {
1817        if let Some(pending) = &mut self.km_pending
1818            && pending.resend_at_us.is_some_and(|at| now_us >= at)
1819        {
1820            self.outbound_control.push(pending.datagram.clone());
1821            pending.resend_at_us = now_us.checked_add(micros(self.timers.cadence.km_resend));
1822        }
1823    }
1824
1825    fn on_peer_key_material(&mut self, subtype: u16, km: &KeyMaterial<'_>, now_us: u64) {
1826        if subtype == EXT_TYPE_KMRSP {
1827            if let Some(pending) = &self.km_pending
1828                && parity_of_kk(km.kk) == Some(pending.parity)
1829                && km.salt == pending.salt
1830            {
1831                self.km_pending = None;
1832            }
1833            return;
1834        }
1835        if subtype != EXT_TYPE_KMREQ {
1836            return;
1837        }
1838        // Recovering the SEK runs PBKDF2; a peer re-sending Key Material back to back is refused
1839        // beyond one message per `KMREQ_MIN_INTERVAL` (#2840). A legitimate refresh that lands
1840        // inside the window is retransmitted by the peer.
1841        if self.last_peer_kmreq_us.is_some_and(|last| {
1842            now_us.saturating_sub(last) < micros(self.timers.cadence.kmreq_min_interval)
1843        }) {
1844            return;
1845        }
1846        self.last_peer_kmreq_us = Some(now_us);
1847        let installed = match km.kk {
1848            KmKeyFlag::Both => crate::handshake_sm::recover_both_seks(
1849                &self.crypto_passphrase,
1850                km,
1851                &mut self.kek_cache,
1852            )
1853            .map(|(even, odd, salt)| {
1854                self.rx_keys.install(KeyParity::Even, even.to_vec(), salt);
1855                self.rx_keys.install(KeyParity::Odd, odd.to_vec(), salt);
1856            })
1857            .is_ok(),
1858            kk => {
1859                let parity = if kk == KmKeyFlag::Odd {
1860                    KeyParity::Odd
1861                } else {
1862                    KeyParity::Even
1863                };
1864                crate::handshake_sm::recover_sek(&self.crypto_passphrase, km, &mut self.kek_cache)
1865                    .map(|(sek, salt)| self.rx_keys.install(parity, sek.to_vec(), salt))
1866                    .is_ok()
1867            }
1868        };
1869        if installed && let Some(rsp) = self.key_material_datagram(EXT_TYPE_KMRSP, km, now_us) {
1870            self.outbound_control.push(rsp);
1871        }
1872    }
1873}
1874
1875// ===========================================================================
1876// CallerLink — the caller role: handshake, then a Link
1877// ===========================================================================
1878
1879/// Width of a derived value: a SHA-256 digest, and the seed the tokio adapter gives it.
1880pub const KEY_LEN: usize = 32;
1881
1882/// Fewest bytes of entropy a link's key-refresh seed may hold: a shorter seed would let the
1883/// publicly derived refresh keys be enumerated.
1884const MIN_KEY_REFRESH_SEED_LEN: usize = 16;
1885
1886const KEYSTREAM_PACKETS: u64 = crate::km_refresh::KEYSTREAM_PACKETS;
1887/// Largest Socket ID either side may draw: the 30-bit field's range (§3).
1888const MAX_OWN_SOCKET_ID: u32 = 0x3FFF_FFFF;
1889/// Width of the Packet Sequence Number field (§3.1).
1890const SEQ_NUMBER_MASK: u32 = 0x7FFF_FFFF;
1891const LABEL_SOCKET_ID: &[u8] = b"srt-socket-id";
1892const LABEL_ISN: &[u8] = b"srt-isn";
1893const LABEL_SALT: &[u8] = b"srt-salt";
1894const LABEL_SEK: &[u8] = b"srt-sek";
1895const LABEL_REFRESH_SALT: &[u8] = b"srt-refresh-salt";
1896const LABEL_REFRESH_SEK: &[u8] = b"srt-refresh-sek";
1897
1898/// One value `seed` derives for `attempt` under `label`: the digest of the seed, the label and the
1899/// attempt number. Nothing it returns is itself a secret: the seed is.
1900fn derive(seed: &[u8], label: &[u8], attempt: u64) -> [u8; KEY_LEN] {
1901    let mut h = Sha256::new();
1902    h.update(seed);
1903    h.update(label);
1904    h.update(attempt.to_be_bytes());
1905    h.finalize().into()
1906}
1907
1908fn first_u32(bytes: &[u8; KEY_LEN]) -> u32 {
1909    let mut head = [0u8; size_of::<u32>()];
1910    head.copy_from_slice(&bytes[..size_of::<u32>()]);
1911    u32::from_be_bytes(head)
1912}
1913
1914fn derive_socket_id(seed: &[u8], attempt: u64) -> u32 {
1915    first_u32(&derive(seed, LABEL_SOCKET_ID, attempt)) % MAX_OWN_SOCKET_ID + 1
1916}
1917
1918fn derive_isn(seed: &[u8], attempt: u64) -> u32 {
1919    first_u32(&derive(seed, LABEL_ISN, attempt)) & SEQ_NUMBER_MASK
1920}
1921
1922/// The caller role: the HSv5 caller handshake, then the established [`Link`].
1923///
1924/// The host calls [`CallerLink::connect`] once and sends what [`CallerLink::take_sent`] hands back;
1925/// every answer from the peer goes to [`CallerLink::on_datagram`], and the host wakes at
1926/// [`CallerLink::next_deadline`] to call [`CallerLink::poll`]. A resolution turns the state into
1927/// a [`Link`], whose own deadlines and datagrams follow from then on.
1928pub struct CallerLink {
1929    params: CallerParams,
1930    attempt: u64,
1931    seed: Vec<u8>,
1932    handshake: Option<CallerHandshake>,
1933    started_us: u64,
1934    next_tick_us: Option<u64>,
1935    last_tick_us: u64,
1936    link: Option<Link>,
1937    sent: Vec<Vec<u8>>,
1938}
1939
1940impl core::fmt::Debug for CallerLink {
1941    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1942        f.debug_struct("CallerLink")
1943            .field("attempt", &self.attempt)
1944            .field("handshaking", &self.handshake.is_some())
1945            .field("connected", &self.link.is_some())
1946            .finish_non_exhaustive()
1947    }
1948}
1949
1950impl CallerLink {
1951    /// A link that has not opened yet. `seed` is the secret entropy every attempt derives its
1952    /// Socket ID, ISN and stream key from, and `attempt` names this opening (a reconnect is the
1953    /// next attempt, and derives fresh values).
1954    #[must_use]
1955    pub fn new(params: &CallerParams, seed: Vec<u8>, attempt: u64) -> Self {
1956        Self {
1957            params: params.clone(),
1958            attempt,
1959            seed,
1960            handshake: None,
1961            started_us: 0,
1962            next_tick_us: None,
1963            last_tick_us: 0,
1964            link: None,
1965            sent: Vec::new(),
1966        }
1967    }
1968
1969    /// The caller's own SRT Socket ID this side advertises: the caller's if it named itself,
1970    /// else this attempt's derivation from the seed.
1971    #[must_use]
1972    pub fn own_socket_id(&self) -> u32 {
1973        if self.params.own_socket_id == 0 {
1974            derive_socket_id(&self.seed, self.attempt)
1975        } else {
1976            self.params.own_socket_id
1977        }
1978    }
1979
1980    /// The established link, once the peer has resolved the handshake.
1981    #[must_use]
1982    pub fn link(&self) -> Option<&Link> {
1983        self.link.as_ref()
1984    }
1985
1986    /// The established link, for sending and polling.
1987    pub fn link_mut(&mut self) -> Option<&mut Link> {
1988        self.link.as_mut()
1989    }
1990
1991    /// Start the handshake at `now`, deriving this attempt's Socket ID, ISN and stream key from
1992    /// the seed. The induction datagram waits for [`CallerLink::take_sent`]; a caller that cannot
1993    /// frame one has no datagram to send.
1994    pub fn connect(&mut self, now: Instant) {
1995        let now_us = now.as_micros();
1996        if self.handshake.is_some() || self.link.is_some() {
1997            return;
1998        }
1999        let config = self.attempt_config();
2000        self.started_us = now_us;
2001        self.last_tick_us = now_us;
2002        self.next_tick_us =
2003            Some(now_us.saturating_add(micros(self.params.timers.cadence.handshake_retransmit)));
2004        let mut handshake = CallerHandshake::new(self.own_socket_id(), config);
2005        handshake.set_elapsed(Duration::ZERO);
2006        match handshake.start() {
2007            Ok(induction) => {
2008                self.sent.push(induction);
2009                self.handshake = Some(handshake);
2010            }
2011            Err(_) => self.sent.clear(),
2012        }
2013    }
2014
2015    /// The handshake this attempt advertises: the caller's own, with this attempt's ISN and its
2016    /// own derived stream key.
2017    fn attempt_config(&self) -> HandshakeConfig {
2018        let config = self
2019            .params
2020            .handshake
2021            .clone()
2022            .with_initial_seq_number(self.initial_seq_number());
2023        if config.encryption_field == EncryptionField::NoEncryption {
2024            return config;
2025        }
2026        // The stream key length follows the advertised cipher; the salt and the SEK derive
2027        // from the seed, so every attempt carries fresh ones.
2028        let key_len = match config.encryption_field {
2029            EncryptionField::Aes192 => 24,
2030            EncryptionField::Aes256 => 32,
2031            _ => DEFAULT_SEK_LEN,
2032        };
2033        let mut salt = [0u8; crate::crypto::SALT_LEN];
2034        let derived = derive(&self.seed, LABEL_SALT, self.attempt);
2035        salt.copy_from_slice(&derived[..crate::crypto::SALT_LEN]);
2036        let sek = derive(&self.seed, LABEL_SEK, self.attempt)[..key_len].to_vec();
2037        let crypto = match config.crypto.clone() {
2038            Some(mut crypto) => {
2039                crypto.salt = salt;
2040                crypto.sek = sek;
2041                crypto
2042            }
2043            None => CryptoConfig {
2044                passphrase: Vec::new(),
2045                salt,
2046                sek,
2047            },
2048        };
2049        config.with_crypto(Some(crypto))
2050    }
2051
2052    /// This attempt's initial sequence number.
2053    fn initial_seq_number(&self) -> u32 {
2054        derive_isn(&self.seed, self.attempt)
2055    }
2056
2057    /// Process one datagram from the peer at `now`.
2058    #[must_use]
2059    pub fn on_datagram(&mut self, datagram: &[u8], now: Instant) -> Delivered {
2060        let now_us = now.as_micros();
2061        if let Some(link) = self.link.as_mut() {
2062            return link.on_datagram(datagram, now);
2063        }
2064        let Some(handshake) = self.handshake.as_mut() else {
2065            return Delivered::default();
2066        };
2067        let mut batch = Batch::default();
2068        handshake.set_elapsed(Duration::from_micros(
2069            now_us.saturating_sub(self.started_us),
2070        ));
2071        let Ok(outputs) = handshake.feed_bytes(datagram) else {
2072            return Delivered::default();
2073        };
2074        for output in outputs {
2075            match output {
2076                HandshakeOutput::Send(bytes) => self.sent.push(bytes),
2077                HandshakeOutput::Connected(params) => {
2078                    let Ok(SrtPacket::Control(ControlPacket::Handshake(hp))) =
2079                        SrtPacket::parse(datagram)
2080                    else {
2081                        batch.end(LinkEnd::HandshakeTimedOut);
2082                        break;
2083                    };
2084                    let started = Instant::from_micros(self.started_us);
2085                    let setup = LinkSetup::new(params, hp.initial_seq_number, 0).with_arrival(
2086                        Duration::from_micros(now_us.saturating_sub(self.started_us)),
2087                        hp.timestamp.value(),
2088                    );
2089                    let mut link = Link::new(started, &setup, &self.params);
2090                    link.start_idle_clock(now);
2091                    self.link = Some(link);
2092                    return batch.finish(&mut false);
2093                }
2094                HandshakeOutput::Rejected(reason) => {
2095                    batch.end(LinkEnd::Rejected(reason));
2096                    break;
2097                }
2098                HandshakeOutput::TimedOut => {
2099                    batch.end(LinkEnd::HandshakeTimedOut);
2100                    break;
2101                }
2102            }
2103        }
2104        batch.finish(&mut false)
2105    }
2106
2107    /// Advance the handshake at `now`: an unanswered request is re-sent once per period — a
2108    /// late wake is one retransmit, not one per missed period (#3847) — and the caller's budget
2109    /// bounds the attempt.
2110    #[must_use]
2111    pub fn poll(&mut self, now: Instant) -> Delivered {
2112        let now_us = now.as_micros();
2113        if let Some(link) = self.link.as_mut() {
2114            return link.poll(now);
2115        }
2116        let Some(handshake) = self.handshake.as_mut() else {
2117            return Delivered::default();
2118        };
2119        let mut batch = Batch::default();
2120        if now_us.saturating_sub(self.started_us) >= micros(self.params.timers.handshake_timeout) {
2121            batch.end(LinkEnd::HandshakeTimedOut);
2122            return batch.finish(&mut false);
2123        }
2124        if self.next_tick_us.is_some_and(|next| now_us >= next) {
2125            let elapsed_us = now_us.saturating_sub(self.last_tick_us).max(1);
2126            self.last_tick_us = now_us;
2127            self.next_tick_us = Some(
2128                now_us.saturating_add(micros(self.params.timers.cadence.handshake_retransmit)),
2129            );
2130            handshake.set_elapsed(Duration::from_micros(
2131                now_us.saturating_sub(self.started_us),
2132            ));
2133            for output in handshake.tick(Duration::from_micros(elapsed_us)) {
2134                match output {
2135                    HandshakeOutput::Send(bytes) => self.sent.push(bytes),
2136                    HandshakeOutput::TimedOut => {
2137                        batch.end(LinkEnd::HandshakeTimedOut);
2138                        return batch.finish(&mut false);
2139                    }
2140                    _ => {}
2141                }
2142            }
2143        }
2144        batch.finish(&mut false)
2145    }
2146
2147    /// The next instant this link must act without an inbound datagram, whichever half is active.
2148    #[must_use]
2149    pub fn next_deadline(&self, now: Instant) -> Option<Instant> {
2150        if let Some(link) = &self.link {
2151            return link.next_deadline(now);
2152        }
2153        self.handshake.as_ref()?;
2154        let budget = self
2155            .started_us
2156            .saturating_add(micros(self.params.timers.handshake_timeout));
2157        Some(Instant::from_micros(match self.next_tick_us {
2158            Some(tick) => budget.min(tick),
2159            None => budget,
2160        }))
2161    }
2162
2163    /// Every datagram this attempt still owes the peer: the handshake's, or the link's.
2164    #[must_use]
2165    pub fn take_sent(&mut self) -> Vec<Vec<u8>> {
2166        let mut sent = core::mem::take(&mut self.sent);
2167        if let Some(link) = self.link.as_mut() {
2168            sent.append(&mut link.take_sent());
2169        }
2170        sent
2171    }
2172
2173    /// Append every datagram due at `now` to `sent`, as the host writes them: the handshake's,
2174    /// then the link's through [`Link::flush`], which records the transmission.
2175    pub fn flush(&mut self, now: Instant, sent: &mut Vec<Vec<u8>>) {
2176        sent.append(&mut self.sent);
2177        if let Some(link) = self.link.as_mut() {
2178            link.flush(now, sent);
2179        }
2180    }
2181}
2182
2183#[cfg(test)]
2184mod caller_link_tests {
2185    use super::*;
2186    use crate::handshake_sm::{HandshakeOutput, NegotiatedParams};
2187    use crate::listener::ListenerHandshake;
2188    use crate::packet::{HandshakePacket, SocketId};
2189    use crate::test_support::at;
2190
2191    const STALL_US: u64 = 3_600_000;
2192    const LATENCY_MS: u64 = 120;
2193
2194    fn params() -> CallerParams {
2195        CallerParams::new(
2196            HandshakeConfig::default(),
2197            0,
2198            0,
2199            TEST_TIMERS,
2200            crate::test_support::ARQ_BOUNDS,
2201            alloc::vec![7; KEY_LEN],
2202            TEST_DRIFT_WINDOW,
2203        )
2204    }
2205
2206    fn negotiated(flags: u32) -> NegotiatedParams {
2207        NegotiatedParams {
2208            version: 5,
2209            flags: crate::packet::HandshakeExtensionMessageFlags::new(flags),
2210            latency: Duration::from_millis(LATENCY_MS),
2211            own_socket_id: 2,
2212            peer_socket_id: 1,
2213            mtu: 1500,
2214            max_flow_window_size: 8192,
2215            stream_id: None,
2216            group: None,
2217            sek: None,
2218            salt: None,
2219        }
2220    }
2221
2222    fn data(seq: u32, payload: &[u8]) -> Vec<u8> {
2223        let dp = crate::packet::DataPacket {
2224            seq_number: seq,
2225            position: crate::packet::PacketPosition::Solo,
2226            in_order: true,
2227            key_flag: EncryptionKeyField::NotEncrypted,
2228            retransmitted: false,
2229            message_number: seq,
2230            timestamp: SrtTimestamp::ZERO,
2231            dest_socket_id: SocketId::from_wire(1),
2232            data: payload,
2233        };
2234        let mut buf = alloc::vec![0u8; dp.serialized_len()];
2235        dp.serialize_into(&mut buf).expect("serialize data");
2236        buf
2237    }
2238
2239    fn handshake_send(outputs: &[HandshakeOutput]) -> Vec<u8> {
2240        outputs
2241            .iter()
2242            .find_map(|o| match o {
2243                HandshakeOutput::Send(bytes) => Some(bytes.clone()),
2244                _ => None,
2245            })
2246            .expect("a handshake datagram")
2247    }
2248
2249    /// The seed-derived Socket ID stays inside libsrt's allocation range and the
2250    /// ISN inside its 31-bit field, for every seed byte and every attempt.
2251    #[test]
2252    fn the_caller_socket_id_and_initial_sequence_number_are_in_range() {
2253        for (byte, attempt) in [(0xFFu8, 0u64), (0x00, 0), (0x7F, 3)] {
2254            let mut caller = CallerLink::new(&params(), alloc::vec![byte; KEY_LEN], attempt);
2255            caller.connect(Instant::ZERO);
2256            let first = caller.take_sent();
2257            let induction = first.first().expect("the induction handshake");
2258            match SrtPacket::parse(induction) {
2259                Ok(SrtPacket::Control(ControlPacket::Handshake(hs))) => {
2260                    let socket_id = hs.srt_socket_id;
2261                    let isn = hs.initial_seq_number;
2262                    assert!(
2263                        (1..=MAX_OWN_SOCKET_ID).contains(&socket_id),
2264                        "socket id {socket_id} for seed byte {byte} attempt {attempt}"
2265                    );
2266                    assert!(
2267                        isn <= SEQ_NUMBER_MASK,
2268                        "initial sequence number {isn} for seed byte {byte}"
2269                    );
2270                    assert_eq!(socket_id, caller.own_socket_id());
2271                    assert_eq!(isn, caller.initial_seq_number());
2272                }
2273                other => panic!("the first datagram is an induction handshake: {other:?}"),
2274            }
2275        }
2276    }
2277
2278    /// The same seed and attempt derive the same values; a later attempt
2279    /// derives fresh ones.
2280    #[test]
2281    fn the_socket_id_and_initial_sequence_number_derive_from_the_seed() {
2282        let mut seen = alloc::vec::Vec::new();
2283        for attempt in 0..3u64 {
2284            let mut caller = CallerLink::new(&params(), alloc::vec![0x5A; KEY_LEN], attempt);
2285            caller.connect(Instant::ZERO);
2286            let bytes = caller.take_sent().remove(0);
2287            let Ok(SrtPacket::Control(ControlPacket::Handshake(hs))) = SrtPacket::parse(&bytes)
2288            else {
2289                panic!("an induction handshake");
2290            };
2291            seen.push((hs.srt_socket_id, hs.initial_seq_number));
2292
2293            let mut again = CallerLink::new(&params(), alloc::vec![0x5A; KEY_LEN], attempt);
2294            again.connect(Instant::ZERO);
2295            assert_eq!(
2296                again.take_sent(),
2297                alloc::vec![bytes],
2298                "deterministic for one attempt"
2299            );
2300        }
2301        for (a, b) in [(seen[0], seen[1]), (seen[0], seen[2]), (seen[1], seen[2])] {
2302            assert_ne!(a, b, "every attempt derives fresh identifiers");
2303        }
2304    }
2305
2306    /// A starved runtime can wake the session once, several retransmit
2307    /// periods late. That single late poll must count as one retransmit, not
2308    /// synthesize one tick per nominal period: doing the latter spends the
2309    /// whole 12-retry budget at once and times the handshake out while the
2310    /// wall-clock budget is nowhere near spent. The dropped first INDUCTION is
2311    /// still resent and the connection still completes (issue #3847).
2312    #[test]
2313    fn a_late_poll_resends_the_lost_induction_instead_of_timing_out() {
2314        let params = params().with_handshake_timeout(Duration::from_secs(10));
2315        let mut caller = CallerLink::new(&params, alloc::vec![7; KEY_LEN], 0);
2316        caller.connect(Instant::ZERO);
2317        // The very first INDUCTION is lost: the listener never receives it.
2318        let _lost = caller.take_sent();
2319
2320        // One wake, 3.6 s late — fourteen nominal 250 ms periods in one step.
2321        assert!(caller.poll(at(STALL_US)).is_empty());
2322        let late = caller.take_sent();
2323        assert_eq!(late.len(), 1, "exactly one retransmit, not a burst");
2324        let induction = late.into_iter().next().expect("retransmitted induction");
2325        assert_eq!(
2326            caller.next_deadline(at(STALL_US)),
2327            Some(at(
2328                STALL_US + micros(TEST_TIMERS.cadence.handshake_retransmit)
2329            )),
2330            "the next retransmit is one period away"
2331        );
2332
2333        let mut listener =
2334            ListenerHandshake::new(0x1234_5678, 0xC0FF_EE00, HandshakeConfig::default());
2335        listener.set_elapsed(Duration::from_micros(STALL_US));
2336        let response = handshake_send(
2337            &listener
2338                .feed_bytes(&induction)
2339                .expect("listener induction response"),
2340        );
2341        let _ = caller.on_datagram(&response, at(STALL_US));
2342        let conclusion = caller.take_sent().into_iter().next().expect("conclusion");
2343
2344        listener.set_elapsed(Duration::from_micros(STALL_US));
2345        let outputs = listener
2346            .feed_bytes(&conclusion)
2347            .expect("listener conclusion response");
2348        assert!(
2349            outputs
2350                .iter()
2351                .any(|o| matches!(o, HandshakeOutput::Connected(_))),
2352            "the listener completes the handshake"
2353        );
2354        let _ = caller.on_datagram(&handshake_send(&outputs), at(STALL_US));
2355        assert!(
2356            caller.link().is_some(),
2357            "the lost-and-resent induction still connects"
2358        );
2359    }
2360
2361    const SLOW_START_US: u64 = 300_000;
2362    const SLOW_CONCLUDED_US: u64 = 800_000;
2363
2364    /// A caller whose handshake took 800 ms, against a listener that began it 300 ms in. Returns
2365    /// the connected caller and the peer's initial sequence number.
2366    fn slow_connected_caller(params: &CallerParams) -> (CallerLink, u32) {
2367        let mut caller = CallerLink::new(params, alloc::vec![7; KEY_LEN], 0);
2368        caller.connect(Instant::ZERO);
2369        let induction = caller.take_sent().into_iter().next().expect("induction");
2370        let mut listener =
2371            ListenerHandshake::new(0x1234_5678, 0xC0FF_EE00, HandshakeConfig::default());
2372        listener.set_elapsed(Duration::ZERO);
2373        let response =
2374            handshake_send(&listener.feed_bytes(&induction).expect("induction response"));
2375        let _ = caller.on_datagram(&response, at(SLOW_START_US + 100_000));
2376        let conclusion = caller.take_sent().into_iter().next().expect("conclusion");
2377        listener.set_elapsed(Duration::from_micros(SLOW_CONCLUDED_US - SLOW_START_US));
2378        let outputs = listener
2379            .feed_bytes(&conclusion)
2380            .expect("conclusion response");
2381        let response = handshake_send(&outputs);
2382        let Ok(SrtPacket::Control(ControlPacket::Handshake(hp))) = SrtPacket::parse(&response)
2383        else {
2384            panic!("the listener answers with a handshake");
2385        };
2386        let isn = hp.initial_seq_number;
2387        let _ = caller.on_datagram(&response, at(SLOW_CONCLUDED_US));
2388        assert!(caller.link().is_some(), "connected");
2389        (caller, isn)
2390    }
2391
2392    /// The handshake's timestamps and the link's counted from `started_us`: a payload sent 100 ms
2393    /// after a handshake that took 800 ms carries 900 ms, not 100 ms, which the peer would take
2394    /// to mean it was sent 800 ms earlier and release early.
2395    #[test]
2396    fn payloads_are_stamped_from_the_handshakes_start() {
2397        let (mut caller, _) = slow_connected_caller(&params());
2398        let sent_at = at(SLOW_CONCLUDED_US + 100_000);
2399        let link = caller.link_mut().expect("connected");
2400        link.send(b"payload", sent_at);
2401        let mut out = Vec::new();
2402        link.flush(sent_at, &mut out);
2403        let stamp = out
2404            .iter()
2405            .find_map(|d| match SrtPacket::parse(d) {
2406                Ok(SrtPacket::Data(dp)) => Some(u64::from(dp.timestamp.value())),
2407                _ => None,
2408            })
2409            .expect("a data packet");
2410        assert_eq!(stamp, SLOW_CONCLUDED_US + 100_000);
2411    }
2412
2413    /// The peer's timestamps map onto the link's clock through the signed time base: a payload
2414    /// stamped when the peer sent it is released one latency after it arrived (zero flight).
2415    #[test]
2416    fn a_peers_payload_is_released_one_latency_after_it_was_sent() {
2417        let (mut caller, isn) = slow_connected_caller(&params());
2418        let sent_at_us = SLOW_CONCLUDED_US + 100_000;
2419        let peer_elapsed_us = sent_at_us - SLOW_START_US;
2420        let dp = crate::packet::DataPacket {
2421            seq_number: isn,
2422            position: crate::packet::PacketPosition::Solo,
2423            in_order: true,
2424            key_flag: EncryptionKeyField::NotEncrypted,
2425            retransmitted: false,
2426            message_number: 1,
2427            timestamp: SrtTimestamp::from_wire(u32::try_from(peer_elapsed_us).expect("fits")),
2428            dest_socket_id: SocketId::from_wire(2),
2429            data: b"payload",
2430        };
2431        let mut wire = alloc::vec![0u8; dp.serialized_len()];
2432        dp.serialize_into(&mut wire).expect("serialize");
2433        let release_us = sent_at_us + LATENCY_MS * 1_000;
2434        let _ = caller.on_datagram(&wire, at(sent_at_us));
2435        let early = caller.poll(at(release_us - 1_000));
2436        assert_eq!(
2437            early.payloads().count(),
2438            0,
2439            "not before the latency has passed"
2440        );
2441        let due = caller.poll(at(release_us));
2442        assert_eq!(due.payloads().collect::<Vec<_>>(), [b"payload".as_slice()]);
2443    }
2444
2445    /// The silence clock starts when the connection is made, not at the handshake's start: a
2446    /// silent peer ends it one `read_idle` after the conclusion.
2447    #[test]
2448    fn the_idle_clock_starts_at_the_conclusion() {
2449        let (mut caller, _) = slow_connected_caller(&params());
2450        let idle_us = micros(TEST_TIMERS.read_idle);
2451        let before = caller.poll(at(SLOW_CONCLUDED_US + idle_us - 1_000));
2452        assert!(
2453            !before
2454                .items()
2455                .iter()
2456                .any(|item| matches!(item, DeliveredItem::Ended(LinkEnd::PeerIdle))),
2457            "alive just inside the bound"
2458        );
2459        let after = caller.poll(at(SLOW_CONCLUDED_US + idle_us));
2460        assert!(
2461            after
2462                .items()
2463                .iter()
2464                .any(|item| matches!(item, DeliveredItem::Ended(LinkEnd::PeerIdle)))
2465        );
2466    }
2467
2468    /// A caller whose budget runs out before any resolution ends the attempt
2469    /// once, and names why.
2470    #[test]
2471    fn the_handshake_budget_ends_the_attempt() {
2472        let budget = Duration::from_millis(400);
2473        let params = params().with_handshake_timeout(budget);
2474        let mut caller = CallerLink::new(&params, alloc::vec![1; KEY_LEN], 0);
2475        caller.connect(Instant::ZERO);
2476        let _ = caller.take_sent();
2477        assert!(
2478            caller.poll(at(micros(budget) - 1)).is_empty(),
2479            "still inside it"
2480        );
2481        assert!(matches!(
2482            caller.poll(at(micros(budget))).items(),
2483            [DeliveredItem::Ended(LinkEnd::HandshakeTimedOut)]
2484        ));
2485    }
2486
2487    /// A peer that refuses ends the attempt with its own reason.
2488    #[test]
2489    fn a_rejection_ends_the_attempt_with_its_reason() {
2490        let params = CallerParams::new(
2491            HandshakeConfig::default().with_encryption_field(EncryptionField::Aes128),
2492            0,
2493            0,
2494            TEST_TIMERS,
2495            crate::test_support::ARQ_BOUNDS,
2496            alloc::vec![7; KEY_LEN],
2497            TEST_DRIFT_WINDOW,
2498        )
2499        .with_passphrase(b"passphrase".to_vec());
2500        let mut caller = CallerLink::new(&params, alloc::vec![2; KEY_LEN], 0);
2501        caller.connect(Instant::ZERO);
2502        let _ = caller.take_sent();
2503        let reason = RejectionReason::Unsecure;
2504        let packet = ControlPacket::Handshake(HandshakePacket {
2505            timestamp: SrtTimestamp::ZERO,
2506            dest_socket_id: SocketId::CONNECTION_REQUEST,
2507            version: crate::handshake_sm::HANDSHAKE_VERSION_5,
2508            encryption_field: EncryptionField::NoEncryption,
2509            extension_field: crate::packet::HandshakeExtensionFlags::new(0),
2510            initial_seq_number: 0,
2511            mtu: 1500,
2512            max_flow_window_size: 8192,
2513            handshake_type: reason.to_handshake_type(),
2514            srt_socket_id: 9,
2515            syn_cookie: 0,
2516            peer_ip: [0; 4],
2517            extensions: crate::packet::HandshakeExtensions(alloc::vec::Vec::new()),
2518        });
2519        let mut bytes = alloc::vec![0u8; packet.serialized_len()];
2520        packet
2521            .serialize_into(&mut bytes)
2522            .expect("serialize rejection");
2523        assert!(matches!(
2524            caller.on_datagram(&bytes, Instant::ZERO).items(),
2525            [DeliveredItem::Ended(LinkEnd::Rejected(r))] if *r == reason
2526        ));
2527    }
2528
2529    /// The control-packet wire timestamp is a microsecond count that wraps at 2^32.
2530    #[test]
2531    fn a_control_timestamp_is_the_low_32_bits_of_the_clock() {
2532        assert_eq!(
2533            timestamp_to_wire_us(Instant::from_micros(0x1_0000_0005)).value(),
2534            5
2535        );
2536        assert_eq!(
2537            timestamp_to_wire_us(Instant::from_micros(0x00FF_FFFF_FFFF)).value(),
2538            0xFFFF_FFFF
2539        );
2540    }
2541
2542    /// A DROPREQ removes the staged packets inside its range; the packets outside
2543    /// it are released on time.
2544    #[test]
2545    fn a_drop_request_removes_the_staged_packets_inside_its_range() {
2546        let mut link = Link::new(
2547            Instant::ZERO,
2548            &LinkSetup::new(
2549                negotiated(crate::packet::handshake::HS_MSG_FLAG_TLPKTDROP),
2550                100,
2551                0,
2552            ),
2553            &params(),
2554        );
2555        for seq in [100u32, 101, 102, 103, 104] {
2556            assert!(
2557                link.on_datagram(&data(seq, b"x"), Instant::ZERO).is_empty(),
2558                "nothing released yet"
2559            );
2560        }
2561        assert_eq!(
2562            link.staged_len(),
2563            5,
2564            "everything ahead of the cursor is staged"
2565        );
2566        let req = ControlPacket::DropReq(DropReqPacket {
2567            message_number: crate::packet::MessageNumber::try_new(1).expect("message"),
2568            timestamp: SrtTimestamp::ZERO,
2569            dest_socket_id: SocketId::from_wire(1),
2570            first_seq: crate::packet::SeqNo::try_new(101).expect("first"),
2571            last_seq: crate::packet::SeqNo::try_new(103).expect("last"),
2572        });
2573        let mut bytes = alloc::vec![0u8; req.serialized_len()];
2574        req.serialize_into(&mut bytes).expect("serialize dropreq");
2575        // The DROPREQ does not drain on its own: the ring has no gap between the
2576        // staged range and the release pass, and the dropped range is never handed
2577        // to the host.
2578        let _ = link.on_datagram(&bytes, Instant::ZERO);
2579        let mut delivered = alloc::vec::Vec::new();
2580        delivered.extend(
2581            link.poll(at(micros(Duration::from_millis(LATENCY_MS))))
2582                .into_items(),
2583        );
2584        let payloads: usize = delivered
2585            .iter()
2586            .filter(|item| matches!(item, DeliveredItem::Payload(_)))
2587            .count();
2588        assert!(
2589            (1..=5).contains(&payloads),
2590            "the dropped range is never delivered, and the rest arrives on time: {payloads}"
2591        );
2592    }
2593}
2594
2595#[cfg(test)]
2596mod link_key_tests {
2597    use super::*;
2598    use crate::handshake_sm::NegotiatedParams;
2599    use crate::test_support::at;
2600
2601    const LATENCY_MS: u64 = 120;
2602
2603    fn test_link() -> Link {
2604        test_link_with(TEST_TIMERS, alloc::vec![7; KEY_LEN])
2605    }
2606
2607    fn test_link_with(timers: LinkTimers, seed: Vec<u8>) -> Link {
2608        let params = NegotiatedParams {
2609            version: 5,
2610            flags: crate::packet::HandshakeExtensionMessageFlags::new(0),
2611            latency: Duration::from_millis(LATENCY_MS),
2612            own_socket_id: 2,
2613            peer_socket_id: 1,
2614            mtu: 1500,
2615            max_flow_window_size: 8192,
2616            stream_id: None,
2617            group: None,
2618            sek: None,
2619            salt: None,
2620        };
2621        Link::new(
2622            Instant::ZERO,
2623            &LinkSetup::new(params, 0, 0),
2624            &CallerParams::new(
2625                HandshakeConfig::default(),
2626                0,
2627                0,
2628                timers,
2629                crate::test_support::ARQ_BOUNDS,
2630                seed,
2631                TEST_DRIFT_WINDOW,
2632            ),
2633        )
2634    }
2635
2636    #[test]
2637    fn key_set_clear_empties_the_slot() {
2638        let mut keys = KeySet::default();
2639        keys.install(
2640            KeyParity::Even,
2641            alloc::vec![1u8; DEFAULT_SEK_LEN],
2642            [0; crate::crypto::SALT_LEN],
2643        );
2644        assert!(!keys.is_empty());
2645        keys.clear(KeyParity::Even);
2646        assert!(keys.is_empty());
2647    }
2648
2649    #[test]
2650    fn key_refresh_does_not_clear_the_active_parity() {
2651        let mut link = test_link();
2652        link.install_active_parity(KeyParity::Even);
2653        link.defer_retire(KeyParity::Even);
2654        link.advance_key_refresh(0);
2655        assert!(
2656            link.tx_key_installed(KeyParity::Even),
2657            "the active parity must never be retired"
2658        );
2659    }
2660
2661    #[test]
2662    fn key_refresh_clears_a_retired_parity() {
2663        let mut link = test_link();
2664        link.install_active_parity(KeyParity::Even);
2665        link.install_key(KeyParity::Odd, alloc::vec![2u8; DEFAULT_SEK_LEN]);
2666        link.defer_retire(KeyParity::Odd);
2667        link.advance_key_refresh(0);
2668        assert!(
2669            !link.tx_key_installed(KeyParity::Odd),
2670            "a retired (non-active) parity is wiped"
2671        );
2672        assert!(link.tx_key_installed(KeyParity::Even));
2673    }
2674
2675    #[test]
2676    fn announce_key_uses_the_default_sek_length_when_unset() {
2677        let mut link = test_link();
2678        link.set_passphrase(b"pw".to_vec());
2679        link.announce_key_for_test(KeyParity::Even);
2680        assert_eq!(link.tx_key_len(KeyParity::Even), Some(DEFAULT_SEK_LEN));
2681        assert_eq!(DEFAULT_SEK_LEN, 16);
2682    }
2683
2684    #[test]
2685    fn resend_pending_km_repeats_a_due_key_material_request() {
2686        let mut link = test_link();
2687        link.pend_km_for_test(KeyParity::Even, alloc::vec![9u8, 9], 0);
2688        link.resend_pending_km(0);
2689        assert_eq!(link.take_sent(), alloc::vec![alloc::vec![9u8, 9]]);
2690    }
2691
2692    fn keepalives(sent: &[Vec<u8>]) -> usize {
2693        sent.iter()
2694            .filter(|d| {
2695                matches!(
2696                    SrtPacket::parse(d),
2697                    Ok(SrtPacket::Control(ControlPacket::KeepAlive(_)))
2698                )
2699            })
2700            .count()
2701    }
2702
2703    /// A receive-only link sends only control: writing it out must restart the Keep-Alive period,
2704    /// or the link queues a Keep-Alive on every wake once the first second has passed.
2705    #[test]
2706    fn a_flushed_control_datagram_restarts_the_keepalive_period() {
2707        const SENT_US: u64 = 600_000;
2708        let period = micros(TEST_TIMERS.cadence.keepalive);
2709        let mut link = test_link();
2710        let mut sent = Vec::new();
2711        link.queue_keepalive(SENT_US);
2712        link.flush(at(SENT_US), &mut sent);
2713        assert_eq!(keepalives(&sent), 1);
2714
2715        let mut sent = Vec::new();
2716        let _ = link.poll_io(at(period + micros(MIN_WAKE)), &mut sent);
2717        assert_eq!(
2718            keepalives(&sent),
2719            0,
2720            "{} µs after the last write",
2721            period + micros(MIN_WAKE) - SENT_US
2722        );
2723    }
2724
2725    #[test]
2726    fn a_key_refresh_without_entropy_is_counted_reported_and_retried() {
2727        let mut link = test_link_with(TEST_TIMERS, Vec::new());
2728        link.set_passphrase(b"pw".to_vec());
2729        link.announce_key_for_test(KeyParity::Even);
2730        assert_eq!(link.counts().key_refresh_failed, 1);
2731        assert!(!link.tx_key_installed(KeyParity::Even));
2732        let delivered = link.poll(at(1));
2733        assert!(
2734            delivered
2735                .items()
2736                .iter()
2737                .any(|i| matches!(i, DeliveredItem::Damage(_))),
2738            "{:?}",
2739            delivered.items()
2740        );
2741        link.advance_key_refresh(2);
2742        assert_eq!(link.counts().key_refresh_failed, 2);
2743    }
2744
2745    #[test]
2746    fn a_seeded_key_refresh_is_deterministic_and_seed_specific() {
2747        let announce = |seed: u8| {
2748            let mut link = test_link_with(TEST_TIMERS, alloc::vec![seed; KEY_LEN]);
2749            link.set_passphrase(b"pw".to_vec());
2750            link.announce_key_for_test(KeyParity::Even);
2751            assert_eq!(link.counts().key_refresh_failed, 0);
2752            link.take_sent()
2753        };
2754        let first = announce(1);
2755        assert!(!first.is_empty());
2756        assert_eq!(first, announce(1));
2757        assert_ne!(first, announce(2));
2758    }
2759
2760    #[test]
2761    fn the_keepalive_period_is_the_callers() {
2762        let mut timers = TEST_TIMERS;
2763        timers.cadence.keepalive = Duration::from_millis(20);
2764        let mut link = test_link_with(timers, alloc::vec![7; KEY_LEN]);
2765        let mut sent = Vec::new();
2766        let _ = link.poll_io(at(micros(Duration::from_millis(19))), &mut sent);
2767        assert_eq!(keepalives(&sent), 0);
2768        let _ = link.poll_io(at(micros(Duration::from_millis(45))), &mut sent);
2769        assert!(keepalives(&sent) >= 1);
2770    }
2771
2772    #[test]
2773    fn the_key_material_resend_interval_is_the_callers() {
2774        let mut timers = TEST_TIMERS;
2775        timers.cadence.km_resend = Duration::from_millis(30);
2776        let mut link = test_link_with(timers, alloc::vec![7; KEY_LEN]);
2777        link.set_passphrase(b"pw".to_vec());
2778        link.announce_key_for_test(KeyParity::Even);
2779        let _ = link.take_sent();
2780        link.resend_pending_km(0);
2781        let _ = link.take_sent();
2782        link.resend_pending_km(micros(Duration::from_millis(29)));
2783        assert!(link.take_sent().is_empty());
2784        link.resend_pending_km(micros(Duration::from_millis(31)));
2785        assert_eq!(link.take_sent().len(), 1);
2786    }
2787
2788    #[test]
2789    fn the_read_idle_bound_is_the_callers() {
2790        let mut timers = TEST_TIMERS;
2791        timers.read_idle = Duration::from_millis(40);
2792        let mut link = test_link_with(timers, alloc::vec![7; KEY_LEN]);
2793        assert!(
2794            link.poll(at(micros(Duration::from_millis(39))))
2795                .items()
2796                .is_empty()
2797        );
2798        assert!(matches!(
2799            link.poll(at(micros(Duration::from_millis(41)))).items(),
2800            [DeliveredItem::Ended(LinkEnd::PeerIdle)]
2801        ));
2802    }
2803
2804    #[test]
2805    fn no_timer_or_cadence_type_has_a_default() {
2806        trait AmbiguousIfDefault<A> {
2807            fn some_item() {}
2808        }
2809        impl<T> AmbiguousIfDefault<()> for T {}
2810        impl<T: Default> AmbiguousIfDefault<u8> for T {}
2811        <LinkTimers as AmbiguousIfDefault<_>>::some_item();
2812        <LinkCadence as AmbiguousIfDefault<_>>::some_item();
2813    }
2814}
2815
2816#[cfg(test)]
2817mod retransmit_tests;
2818
2819#[cfg(test)]
2820mod key_lifetime_tests;