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(any(test, feature = "tokio"))]
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            .and_then(|t| self.epoch_us.checked_add(t.as_micros()))
944            .map(Instant::from_micros)
945    }
946
947    /// The pacing period one DATA packet's slot advances by under the current policy.
948    #[must_use]
949    pub fn pacing_period(&self) -> Duration {
950        self.livecc.on_ack_received()
951    }
952
953    /// How many DATA and control datagrams are still queued for the wire.
954    #[must_use]
955    pub fn queued_len(&self) -> usize {
956        self.outbound_data.len() + self.outbound_control.len()
957    }
958
959    /// How many sent DATA packets are still unacknowledged. A closing sender drains these before
960    /// sending SHUTDOWN so the tail of a stream is not lost to an unheard retransmission.
961    #[must_use]
962    pub fn buffered_count(&self) -> usize {
963        self.sender.buffered_count()
964    }
965
966    /// How many sequence numbers are waiting to be retransmitted.
967    #[must_use]
968    pub fn pending_retransmit_count(&self) -> usize {
969        self.sender.pending_retransmit_count()
970    }
971
972    /// The mean DATA payload size LiveCC paces from.
973    #[must_use]
974    pub fn average_payload_size(&self) -> u64 {
975        self.livecc.avg_payload_size()
976    }
977
978    /// How many received packets are staged, waiting for TSBPD to release them.
979    #[must_use]
980    pub fn staged_len(&self) -> usize {
981        self.staged.len()
982    }
983
984    /// The cumulative ACK point of the receive direction: every sequence number
985    /// below it is accounted for, delivered or given up on.
986    #[must_use]
987    pub fn ack_point(&self) -> u32 {
988        self.receiver.ack_point()
989    }
990
991    /// How many received packets are missing between the delivery cursor and the
992    /// highest one seen.
993    #[must_use]
994    pub fn loss_list_len(&self) -> usize {
995        self.receiver.loss_list_len()
996    }
997
998    /// The receive direction's round-trip estimate (rule 33).
999    #[must_use]
1000    pub fn rtt(&self) -> Duration {
1001        self.receiver.rtt()
1002    }
1003
1004    #[cfg(test)]
1005    /// The count-based drops this link has already reported, one flag per cause:
1006    /// a refused payload, an out-of-window packet, an undecryptable packet, a
1007    /// peer error, an unparseable datagram.
1008    #[must_use]
1009    pub fn reported_causes(&self) -> [bool; COUNTED_CAUSES] {
1010        self.reported.reported
1011    }
1012
1013    /// What this link has counted about the DATA it received.
1014    #[must_use]
1015    pub fn counts(&self) -> LinkCounts {
1016        self.counts
1017    }
1018
1019    #[cfg(test)]
1020    /// The reason a count-based report names for the cause at `index` of
1021    /// [`Link::reported_causes`].
1022    #[must_use]
1023    pub fn counted_cause_what(index: usize) -> Option<&'static str> {
1024        COUNTED_BY_SLOT.get(index).copied().map(CountedCause::what)
1025    }
1026
1027    /// The sequence number the next first transmission carries.
1028    #[must_use]
1029    pub fn next_send_seq(&self) -> u32 {
1030        self.next_send_seq
1031    }
1032
1033    /// The message number the next first transmission carries.
1034    #[must_use]
1035    pub fn next_message_number(&self) -> u32 {
1036        self.next_message_number
1037    }
1038
1039    #[cfg(test)]
1040    /// Put the next message number where `next` is, so a host can start a
1041    /// connection from an arbitrary point of the wrapping space.
1042    pub fn set_next_message_number(&mut self, next: u32) {
1043        self.next_message_number = next;
1044    }
1045
1046    #[cfg(test)]
1047    /// Set the §6 passphrase a peer's Key Material is recovered with.
1048    pub fn set_passphrase(&mut self, passphrase: Vec<u8>) {
1049        self.crypto_passphrase = Zeroizing::new(passphrase);
1050    }
1051
1052    #[cfg(test)]
1053    /// Whether both direction keys are installed (a `KK = Both` exchange).
1054    #[must_use]
1055    pub fn rx_keys_installed(&self) -> bool {
1056        self.rx_keys.get(KeyParity::Even).is_some() && self.rx_keys.get(KeyParity::Odd).is_some()
1057    }
1058
1059    #[cfg(test)]
1060    /// How many Key Material messages this connection has derived a KEK for.
1061    #[must_use]
1062    pub fn kek_derivations(&self) -> u64 {
1063        self.kek_cache.derivations()
1064    }
1065
1066    #[cfg(test)]
1067    /// Which of the two keys new outgoing packets are encrypted under.
1068    #[must_use]
1069    pub fn tx_parity_name(&self) -> &'static str {
1070        self.tx_parity.name()
1071    }
1072
1073    #[cfg(test)]
1074    /// Whether a refreshed SEK is still waiting for the peer's confirmation.
1075    #[must_use]
1076    pub fn refresh_pending(&self) -> bool {
1077        self.km_pending.is_some()
1078    }
1079
1080    #[cfg(test)]
1081    /// Put `sek` in the send direction under `parity`, without touching the active one.
1082    fn install_key(&mut self, parity: KeyParity, sek: Vec<u8>) {
1083        self.tx_keys
1084            .install(parity, sek, [0; crate::crypto::SALT_LEN]);
1085    }
1086
1087    #[cfg(test)]
1088    /// Put a key under `parity` and make that parity the send direction's active one.
1089    pub fn install_active_parity(&mut self, parity: KeyParity) {
1090        self.tx_keys.install(
1091            parity,
1092            alloc::vec![3u8; DEFAULT_SEK_LEN],
1093            [0; crate::crypto::SALT_LEN],
1094        );
1095        self.tx_parity = parity;
1096        self.km_refresh = KmRefreshDriver::new(self.km_refresh_thresholds, parity);
1097    }
1098
1099    #[cfg(test)]
1100    /// Mark `parity` for retirement at the next key refresh.
1101    pub fn defer_retire(&mut self, parity: KeyParity) {
1102        self.retire_deferred = Some(parity);
1103    }
1104
1105    #[cfg(test)]
1106    /// Whether the send direction holds a key under `parity`.
1107    #[must_use]
1108    pub fn tx_key_installed(&self, parity: KeyParity) -> bool {
1109        self.tx_keys.get(parity).is_some()
1110    }
1111
1112    #[cfg(test)]
1113    /// The length of the send direction's key under `parity`.
1114    #[must_use]
1115    pub fn tx_key_len(&self, parity: KeyParity) -> Option<usize> {
1116        self.tx_keys.get(parity).map(|(sek, _)| sek.len())
1117    }
1118
1119    #[cfg(test)]
1120    /// Run one key-refresh step at `now`.
1121    pub fn advance_key_refresh(&mut self, now_us: u64) {
1122        self.advance_key_refresh_step(now_us);
1123    }
1124
1125    #[cfg(test)]
1126    /// Announce a refreshed key for `parity` at `now`.
1127    pub fn announce_key_for_test(&mut self, parity: KeyParity) {
1128        self.announce_key(parity, 0);
1129    }
1130
1131    #[cfg(test)]
1132    /// Replace the pending KMREQ with a fixed datagram due at `resend_at_us`.
1133    fn pend_km_for_test(&mut self, parity: KeyParity, datagram: Vec<u8>, resend_at_us: u64) {
1134        self.km_pending = Some(PendingKm {
1135            parity,
1136            salt: [0; crate::crypto::SALT_LEN],
1137            datagram,
1138            resend_at_us: Some(resend_at_us),
1139        });
1140    }
1141
1142    #[cfg(test)]
1143    /// Install `sek` under both directions for `passphrase`, with KM Refresh at
1144    /// `thresholds` — the state a test starts a refresh from.
1145    pub fn install_refresh_test_keys(
1146        &mut self,
1147        passphrase: &[u8],
1148        sek: &[u8],
1149        salt: [u8; crate::crypto::SALT_LEN],
1150        thresholds: KmRefreshThresholds,
1151    ) {
1152        self.set_passphrase(passphrase.to_vec());
1153        self.crypto_key_len = sek.len();
1154        for keys in [&mut self.tx_keys, &mut self.rx_keys] {
1155            keys.install(KeyParity::Even, sek.to_vec(), salt);
1156        }
1157        self.km_refresh = KmRefreshDriver::new(thresholds, KeyParity::Even);
1158        self.km_refresh_thresholds = thresholds;
1159    }
1160
1161    /// The next instant this link must act without any inbound event: the next Full ACK / NAK, the
1162    /// next TSBPD release, the Keep-Alive when idle, the peer-idle expiry, a pending KMREQ resend
1163    /// and the next pacing slot. A deadline the clock cannot name is no deadline; the others still
1164    /// bind. `None` once the link has ended.
1165    #[must_use]
1166    pub fn next_deadline(&self, now: Instant) -> Option<Instant> {
1167        self.next_deadline_micros(now.as_micros())
1168            .map(Instant::from_micros)
1169    }
1170
1171    fn next_deadline_micros(&self, now_us: u64) -> Option<u64> {
1172        if self.ended {
1173            return None;
1174        }
1175        let fold = |at: Option<u64>, candidate: Option<u64>| match (at, candidate) {
1176            (Some(a), Some(c)) => Some(a.min(c)),
1177            (Some(a), None) => Some(a),
1178            (None, c) => c,
1179        };
1180        // Every span here can pass the end of the clock, which the host cannot
1181        // represent: such a term never fires.
1182        let span = |from: u64, len: u64| from.checked_add(len);
1183        let mut at = self
1184            .receiver
1185            .next_deadline()
1186            .and_then(|t| span(self.epoch_us, t.as_micros()));
1187        if let Some(t) = self.tsbpd.next_release_after(self.elapsed(now_us)) {
1188            at = fold(at, span(self.epoch_us, micros(t)));
1189        }
1190        if self.outbound_control.is_empty() && self.outbound_data.is_empty() {
1191            at = fold(
1192                at,
1193                span(self.last_tx_us, micros(self.timers.cadence.keepalive)),
1194            );
1195        }
1196        at = fold(at, span(self.last_rx_us, self.read_idle_us));
1197        if let Some(pending) = &self.km_pending {
1198            at = fold(at, pending.resend_at_us);
1199        }
1200        if !self.outbound_data.is_empty() {
1201            at = fold(at, self.next_data_send_at_us);
1202        }
1203        // Never a deadline already past, and never a spin: the same 1 ms floor every hosted
1204        // adapter of this crate keeps.
1205        at.map(|at| at.max(now_us.saturating_add(micros(MIN_WAKE))))
1206    }
1207
1208    /// How long until the DATA packet at the front of the queue may go out: `None`
1209    /// when the queue is empty or its slot has already arrived.
1210    #[must_use]
1211    pub fn next_paced_send_wait(&self, now: Instant) -> Option<Duration> {
1212        if self.outbound_data.is_empty() {
1213            return None;
1214        }
1215        let deadline = self.next_data_send_at_us?;
1216        Some(Duration::from_micros(
1217            deadline.saturating_sub(now.as_micros()),
1218        ))
1219    }
1220
1221    /// Feed one application payload for first transmission at `now`. It is encrypted (§6) when
1222    /// the connection negotiated it, queued behind any retransmission, and sent by the next
1223    /// [`Link::poll`] or [`Link::poll_io`].
1224    pub fn send(&mut self, payload: &[u8], now: Instant) {
1225        let now_us = now.as_micros();
1226        if self.ended || self.key_exhausted {
1227            return;
1228        }
1229        self.livecc
1230            .on_data_packet(u64::try_from(payload.len()).unwrap_or(u64::MAX));
1231
1232        self.advance_key_refresh_step(now_us);
1233
1234        if self.tx_keys.get(self.tx_parity).is_some() {
1235            if self.tx_key_sent >= self.tx_key_limit {
1236                self.key_exhausted = true;
1237                return;
1238            }
1239            self.tx_key_sent = self.tx_key_sent.saturating_add(1);
1240        }
1241        let encrypted: Option<Vec<u8>> = match self.tx_keys.get(self.tx_parity) {
1242            Some((sek, salt)) => {
1243                let mut enc = payload.to_vec();
1244                if crate::crypto::aes_ctr_apply(sek, &salt, self.next_send_seq, &mut enc).is_err() {
1245                    return;
1246                }
1247                Some(enc)
1248            }
1249            None => None,
1250        };
1251        let key_flag = if encrypted.is_some() {
1252            key_field_of(self.tx_parity)
1253        } else {
1254            EncryptionKeyField::NotEncrypted
1255        };
1256        let payload = encrypted.as_deref().unwrap_or(payload);
1257
1258        // The counters are kept within their wire widths, so framing them cannot fail; if it ever
1259        // did, the payload is dropped, not the link.
1260        let Ok(bytes) = self.sender.on_data_keyed(
1261            self.next_send_seq,
1262            self.next_message_number,
1263            payload,
1264            key_flag,
1265            self.elapsed(now_us),
1266        ) else {
1267            return;
1268        };
1269        self.next_send_seq = seq_next(self.next_send_seq);
1270        self.next_message_number = next_message_number(self.next_message_number);
1271        self.outbound_data.push_back(OutboundData {
1272            bytes,
1273            retransmit: None,
1274        });
1275    }
1276
1277    /// Take the datagrams queued for the peer since the last call, in send order: first
1278    /// transmissions, retransmissions and control feedback alike. They may leave at once — a host
1279    /// that writes them calls [`Link::flush`] instead, which applies the pacing slot and records the
1280    /// transmission the Keep-Alive period counts from.
1281    #[must_use]
1282    pub fn take_sent(&mut self) -> Vec<Vec<u8>> {
1283        let mut sent = core::mem::take(&mut self.outbound_control);
1284        sent.reserve(self.outbound_data.len());
1285        while let Some(datagram) = self.outbound_data.pop_front() {
1286            sent.push(datagram.bytes);
1287        }
1288        sent
1289    }
1290
1291    /// Process one datagram from the peer at `now`, returning what it delivered.
1292    #[must_use]
1293    pub fn on_datagram(&mut self, datagram: &[u8], now: Instant) -> Delivered {
1294        self.on_owned_datagram(datagram.to_vec(), now)
1295    }
1296
1297    /// [`Link::on_datagram`] for a datagram the host owns: a payload it delivers stays in this
1298    /// datagram's allocation (see [`Payload`]), so receiving it costs no copy.
1299    #[must_use]
1300    pub fn on_owned_datagram(&mut self, datagram: Vec<u8>, now: Instant) -> Delivered {
1301        let now_us = now.as_micros();
1302        if self.ended {
1303            return Delivered::default();
1304        }
1305        let mut batch = Batch::default();
1306        self.ingress(datagram, now_us, &mut batch);
1307        batch.finish(&mut self.ended)
1308    }
1309
1310    /// Run the timers at `now` — retransmissions, ACK/NAK, the Keep-Alive, a KMREQ resend and
1311    /// the TSBPD release — returning what it delivered.
1312    #[must_use]
1313    pub fn poll(&mut self, now: Instant) -> Delivered {
1314        let now_us = now.as_micros();
1315        if self.ended {
1316            return Delivered::default();
1317        }
1318        let mut batch = Batch::default();
1319        if now_us.saturating_sub(self.last_rx_us) >= self.read_idle_us {
1320            batch.end(LinkEnd::PeerIdle);
1321            return batch.finish(&mut self.ended);
1322        }
1323        self.tick_engines(now_us, &mut batch);
1324        batch.finish(&mut self.ended)
1325    }
1326
1327    /// The timer pass and the outbound flush a host loop runs after every wake-up: the engines at
1328    /// `now`, then every datagram due — appended to `sent` — control at once and DATA at its
1329    /// pacing slot. Returns what the timer pass delivered; a host that also keeps a delivery
1330    /// channel hands it on.
1331    #[must_use]
1332    pub fn poll_io(&mut self, now: Instant, sent: &mut Vec<Vec<u8>>) -> Delivered {
1333        let now_us = now.as_micros();
1334        if self.ended {
1335            return Delivered::default();
1336        }
1337        let mut batch = Batch::default();
1338        self.tick_engines(now_us, &mut batch);
1339        self.flush(now, sent);
1340        batch.finish(&mut self.ended)
1341    }
1342
1343    fn ingress(&mut self, datagram: Vec<u8>, now_us: u64, batch: &mut Batch) {
1344        // Any datagram from the peer — even one that fails to parse below — is evidence the peer
1345        // is still there, resetting the idle timeout.
1346        self.last_rx_us = now_us;
1347        let now = self.elapsed(now_us);
1348        let Ok(packet) = SrtPacket::parse(&datagram) else {
1349            self.counts.unparseable = self.counts.unparseable.saturating_add(1);
1350            self.report_counted(CountedCause::MalformedDatagram, 1, batch);
1351            return;
1352        };
1353        match packet {
1354            SrtPacket::Data(d) => {
1355                let (seq_number, timestamp, key_flag) = (d.seq_number, d.timestamp, d.key_flag);
1356                let Some(payload) = self.payload(datagram, seq_number, key_flag, batch) else {
1357                    return;
1358                };
1359                self.ingress_data(payload, seq_number, timestamp, now, batch);
1360            }
1361            SrtPacket::Control(c) => self.ingress_control(&c, now, now_us, batch),
1362        }
1363    }
1364
1365    fn ingress_data(
1366        &mut self,
1367        payload: Payload,
1368        seq_number: u32,
1369        timestamp: SrtTimestamp,
1370        now: Instant,
1371        batch: &mut Batch,
1372    ) {
1373        // A packet that is not ahead of the delivery cursor (a duplicate, a retransmission of what
1374        // was delivered or given up on, or a stale sequence number) has nothing left to do: it is
1375        // never staged at all.
1376        if seq_lt(seq_number, self.tsbpd.next_release()) {
1377            self.counts.late = self.counts.late.saturating_add(1);
1378            return;
1379        }
1380        let outcome = self.receiver.feed_data(seq_number, now);
1381        if outcome.out_of_window {
1382            self.report_counted(CountedCause::OutOfWindow, 1, batch);
1383            return;
1384        }
1385        if let Some(nak_bytes) = outcome.nak {
1386            self.outbound_control.push(nak_bytes);
1387        }
1388        // The staging buffer is what TSBPD releases from, in strict sequence order, waiting for a
1389        // NAK-recovered gap until the next buffered packet's play time, at which point live mode
1390        // skips an unrecoverable gap (only under TLPKTDROP, §3.2.1.1.1).
1391        if self.staged.contains_key(&seq_number) {
1392            self.counts.duplicates = self.counts.duplicates.saturating_add(1);
1393        }
1394        self.staged.entry(seq_number).or_insert(payload);
1395        let tsbpd_out = self.tsbpd.feed_data(seq_number, timestamp.value(), now);
1396        self.release(&tsbpd_out, batch);
1397    }
1398
1399    /// The DATA payload of `datagram`, decrypted when it was encrypted. `None` when it cannot be
1400    /// staged: no usable key, or a failed decryption pass, both reported once.
1401    fn payload(
1402        &mut self,
1403        mut datagram: Vec<u8>,
1404        seq_number: u32,
1405        key_flag: EncryptionKeyField,
1406        batch: &mut Batch,
1407    ) -> Option<Payload> {
1408        datagram.get(SRT_HEADER_LEN..)?;
1409        if key_flag == EncryptionKeyField::NotEncrypted {
1410            if self.refuse_cleartext && self.crypto_key_len != 0 {
1411                self.undecryptable(batch);
1412                return None;
1413            }
1414        } else {
1415            let keys = KeySet::parity_of(key_flag).and_then(|p| self.rx_keys.get(p));
1416            let Some((sek, salt)) = keys else {
1417                self.undecryptable(batch);
1418                return None;
1419            };
1420            let data = datagram.get_mut(SRT_HEADER_LEN..)?;
1421            if crate::crypto::aes_ctr_apply(sek, &salt, seq_number, data).is_err() {
1422                self.undecryptable(batch);
1423                return None;
1424            }
1425        }
1426        Some(Payload {
1427            datagram,
1428            start: SRT_HEADER_LEN,
1429        })
1430    }
1431
1432    fn undecryptable(&mut self, batch: &mut Batch) {
1433        self.counts.undecryptable = self.counts.undecryptable.saturating_add(1);
1434        self.report_counted(CountedCause::Undecryptable, 1, batch);
1435    }
1436
1437    fn ingress_control(
1438        &mut self,
1439        c: &ControlPacket<'_>,
1440        now: Instant,
1441        now_us: u64,
1442        batch: &mut Batch,
1443    ) {
1444        match c {
1445            ControlPacket::Ack(ack) => {
1446                if let Some(ackack_bytes) = self.sender.on_ack(ack, now) {
1447                    self.outbound_control.push(ackack_bytes);
1448                }
1449            }
1450            // Record the reported loss; the next timer pass drains the retransmit queue —
1451            // retransmits are queued ahead of any new first-time data (rules 5, 15, 16).
1452            ControlPacket::Nak(nak) => self.sender.on_nak(nak),
1453            ControlPacket::AckAck(ackack) => self.receiver.on_ackack(ackack, now),
1454            ControlPacket::DropReq(d) => self.handle_dropreq(d, now, batch),
1455            // A Keep-Alive only tells us the peer is alive (`last_rx_us` is already refreshed);
1456            // it is not answered.
1457            ControlPacket::KeepAlive(_) => {}
1458            ControlPacket::Shutdown(_) => batch.end(LinkEnd::PeerShutdown),
1459            ControlPacket::PeerError(p) => {
1460                self.report_counted(CountedCause::PeerError, u64::from(p.error_code), batch);
1461            }
1462            ControlPacket::UserDefined(u) => {
1463                if let Ok(km) = u.as_key_material() {
1464                    self.on_peer_key_material(u.subtype, &km, now_us);
1465                }
1466            }
1467            _ => {}
1468        }
1469    }
1470
1471    /// Handle a DROPREQ (§3.2.9): the peer announces it will never deliver sequence numbers
1472    /// `first..=last`. Tell the ARQ receiver to stop NAKing them and advance its ack point, tell
1473    /// the TSBPD scheduler to skip them, discard anything already staged inside the range, then
1474    /// drive one release pass so whatever the gap blocked becomes deliverable immediately.
1475    fn handle_dropreq(&mut self, d: &DropReqPacket, now: Instant, batch: &mut Batch) {
1476        let first = d.first_seq.value();
1477        let last = d.last_seq.value();
1478        if seq_diff(last, first) < 0 {
1479            return;
1480        }
1481        let reach = seq_diff(last, self.receiver.ack_point());
1482        if !u32::try_from(reach).is_ok_and(|ahead| ahead <= self.max_flow_window) {
1483            return;
1484        }
1485        self.receiver.skip_range(first, last);
1486        self.tsbpd.skip_range(first, last);
1487        self.staged
1488            .retain(|&s, _| !seq_in_closed_range(s, first, last));
1489        let tsbpd_out = self.tsbpd.tick(now);
1490        self.release(&tsbpd_out, batch);
1491    }
1492
1493    /// Apply one TSBPD outcome: publish the released payloads and purge anything the scheduler
1494    /// gave up on.
1495    ///
1496    /// What the scheduler gave up on (§4.6) is also skipped in the ARQ receiver: its ack point then
1497    /// moves past the dropped packets — the "fake ACK" of Too-Late Packet Drop — so it stops NAKing
1498    /// packets that can no longer be delivered. The two lists are merged on sequence number so a
1499    /// payload past a skipped gap is published only after the report naming that skip.
1500    fn release(&mut self, outcome: &TickOutcome, batch: &mut Batch) {
1501        let lost: Vec<u32> = outcome.dropped.iter().map(|p| p.seq_number).collect();
1502        self.counts.lost = self
1503            .counts
1504            .lost
1505            .saturating_add(u64::try_from(lost.len()).unwrap_or(u64::MAX));
1506        for packet in &outcome.dropped {
1507            self.staged.remove(&packet.seq_number);
1508        }
1509        for (first, last) in contiguous_runs(&lost) {
1510            self.receiver.skip_range(first, last);
1511        }
1512        let dropped = &outcome.dropped;
1513        let mut next_delivered = 0usize;
1514        let mut run_start = 0usize;
1515        while run_start < dropped.len() {
1516            let run_end = run_start
1517                + contiguous_runs(&lost[run_start..])
1518                    .first()
1519                    .copied()
1520                    .map_or(0, |(_, last)| seq_diff(last, lost[run_start]) as usize + 1);
1521            while let Some(&seq) = outcome.delivered.get(next_delivered) {
1522                if seq_lt(seq, dropped[run_start].seq_number) {
1523                    self.deliver_payload(seq, batch);
1524                    next_delivered += 1;
1525                } else {
1526                    break;
1527                }
1528            }
1529            for damage in damage_reports::reports(&dropped[run_start..run_end]) {
1530                self.report(damage, batch);
1531            }
1532            run_start = run_end;
1533        }
1534        for &seq in &outcome.delivered[next_delivered..] {
1535            self.deliver_payload(seq, batch);
1536        }
1537    }
1538
1539    /// Hand one released payload to the host, unless the caller's check refuses its format.
1540    fn deliver_payload(&mut self, seq: u32, batch: &mut Batch) {
1541        let Some(payload) = self.staged.remove(&seq) else {
1542            return;
1543        };
1544        if (self.payload_admits)(payload.as_slice()) {
1545            batch.payload(payload);
1546        } else {
1547            self.counts.refused = self.counts.refused.saturating_add(1);
1548            self.report_counted(CountedCause::PayloadRefused, 1, batch);
1549        }
1550    }
1551
1552    /// Hand one report to the caller's policy: publish it, or end the link with it when the policy
1553    /// says `Fail`.
1554    fn report(&mut self, damage: Damage, batch: &mut Batch) {
1555        match self.damage_policy.admit(damage) {
1556            Ok(damage) => batch.report(damage),
1557            Err(error) => {
1558                batch.refused = Some(error);
1559                self.ended = true;
1560            }
1561        }
1562    }
1563
1564    /// Report a loss this link only counts, once per cause.
1565    fn report_counted(&mut self, cause: CountedCause, count: u64, batch: &mut Batch) {
1566        if *self.reported.slot(cause) {
1567            return;
1568        }
1569        *self.reported.slot(cause) = true;
1570        self.report(
1571            damage_reports::dropped_before_delivery(cause.what(), count),
1572            batch,
1573        );
1574    }
1575
1576    fn tick_engines(&mut self, now_us: u64, batch: &mut Batch) {
1577        if self.ended {
1578            return;
1579        }
1580        let now = self.elapsed(now_us);
1581        if self.key_exhausted {
1582            batch.end(LinkEnd::KeyExhausted);
1583            return;
1584        }
1585        if self.counts.key_refresh_unconfirmed > 0 {
1586            self.report_counted(
1587                CountedCause::KeyRefreshUnconfirmed,
1588                self.counts.key_refresh_unconfirmed,
1589                batch,
1590            );
1591        }
1592        if self.counts.key_refresh_failed > 0 {
1593            self.report_counted(
1594                CountedCause::KeyRefreshFailed,
1595                self.counts.key_refresh_failed,
1596                batch,
1597            );
1598        }
1599
1600        // Retransmitted DATA packets first (rules 5, 15, 16, 18): they drain the NAK-populated
1601        // loss list and are queued before any first-time data, reproducing the sans-IO engine's
1602        // "loss list before first transmission" priority.
1603        let queue_cap = usize::try_from(self.max_flow_window).unwrap_or(usize::MAX);
1604        for (seq, bytes) in self.sender.tick(now) {
1605            self.livecc.on_data_packet(
1606                u64::try_from(bytes.len().saturating_sub(SRT_HEADER_LEN)).unwrap_or(u64::MAX),
1607            );
1608            // Retransmissions are capped at the negotiated flow window: a NAK naming the whole
1609            // send buffer must not turn into an unbounded queue (#2819). A dropped retransmission
1610            // stays in the sender's loss list and is offered again by a later tick.
1611            if self.outbound_data.len() < queue_cap {
1612                self.outbound_data.push_back(OutboundData {
1613                    bytes,
1614                    retransmit: Some(seq),
1615                });
1616            } else {
1617                self.sender.on_retransmit_dropped(seq);
1618            }
1619        }
1620
1621        // Keep-Alive (§3.2.3): a connection that has sent nothing for a second says so, or the
1622        // peer's own idle timeout ends it. Judged before this pass's ACK/NAK are queued: it asks
1623        // whether anything has gone out for a second, not whether something is about to.
1624        if self.outbound_control.is_empty()
1625            && self.outbound_data.is_empty()
1626            && now_us.saturating_sub(self.last_tx_us) >= micros(self.timers.cadence.keepalive)
1627        {
1628            self.queue_keepalive(now_us);
1629        }
1630
1631        self.resend_pending_km(now_us);
1632
1633        // Periodic ACK/NAK (rules 11, 12, 21, 22): control feedback, never paced.
1634        for bytes in self.receiver.tick(now) {
1635            self.outbound_control.push(bytes);
1636        }
1637
1638        let tsbpd_out = self.tsbpd.tick(now);
1639        self.release(&tsbpd_out, batch);
1640    }
1641
1642    fn queue_keepalive(&mut self, now_us: u64) {
1643        let pkt = ControlPacket::KeepAlive(KeepAlivePacket {
1644            timestamp: self.wire_now(now_us),
1645            dest_socket_id: SocketId::from_wire(self.peer_socket_id),
1646            libsrt_pad: true,
1647        });
1648        let mut buf = alloc::vec![0u8; pkt.serialized_len()];
1649        if pkt.serialize_into(&mut buf).is_ok() {
1650            self.outbound_control.push(buf);
1651        }
1652    }
1653
1654    /// Append every outbound datagram due at `now`, in order, without blocking on the pacing
1655    /// delay itself: control in full, then DATA while its pacing slot has arrived. [`Link::poll_io`]
1656    /// runs the timers first, as a host loop does after every wake-up.
1657    ///
1658    /// §5.1.2 paces DATA packets only: control feedback (ACK/NAK/ACKACK/Keep-Alive) goes out
1659    /// immediately, or loss recovery would be throttled along with the data it unblocks. DATA is
1660    /// scheduled against `next_data_send_at_us`, a token-bucket-style deadline rather than a sleep:
1661    /// the schedule advances from whichever is later of the previous slot or now, but never more
1662    /// 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
1663    /// gap sends at once while a sustained flood stays throttled.
1664    pub fn flush(&mut self, now: Instant, sent: &mut Vec<Vec<u8>>) {
1665        let now_us = now.as_micros();
1666        let mut count = self.outbound_control.len();
1667        sent.append(&mut self.outbound_control);
1668        let mut paced = 0;
1669        while !self.outbound_data.is_empty() && paced < self.pacing_burst_packets {
1670            if let Some(deadline) = self.next_data_send_at_us
1671                && now_us < deadline
1672            {
1673                break;
1674            }
1675            let Some(datagram) = self.outbound_data.pop_front() else {
1676                break;
1677            };
1678            if let Some(seq) = datagram.retransmit {
1679                self.sender.on_retransmit_sent(seq);
1680            }
1681            let period = micros(self.livecc.on_ack_received());
1682            let floor =
1683                now_us.saturating_sub(period.saturating_mul(self.pacing_burst_packets as u64));
1684            let base = self.next_data_send_at_us.map_or(now_us, |t| t.max(floor));
1685            self.next_data_send_at_us = base.checked_add(period);
1686            paced += 1;
1687            count += 1;
1688            sent.push(datagram.bytes);
1689        }
1690        // An idle connection owes nothing: drop an expired slot so the next backlog starts at
1691        // "now" instead of replaying the idle gap as credit.
1692        if self.outbound_data.is_empty() {
1693            self.next_data_send_at_us = self.next_data_send_at_us.filter(|&t| t > now_us);
1694        }
1695        if count > 0 {
1696            self.last_tx_us = now_us;
1697        }
1698    }
1699
1700    fn advance_key_refresh_step(&mut self, now_us: u64) {
1701        if let Some(parity) = self.key_refresh_retry.take() {
1702            self.announce_key(parity, now_us);
1703        }
1704        if self.tx_keys.is_empty() {
1705            return;
1706        }
1707        for ev in self.km_refresh.on_packet_sent(1) {
1708            match ev {
1709                KmRefreshEvent::PreAnnounce { next_parity } => {
1710                    self.announce_key(next_parity, now_us);
1711                }
1712                KmRefreshEvent::Switchover { .. } => {
1713                    if self.km_pending.is_some() {
1714                        self.counts.key_refresh_unconfirmed =
1715                            self.counts.key_refresh_unconfirmed.saturating_add(1);
1716                    }
1717                }
1718                KmRefreshEvent::Decommission { retired } => self.retire_deferred = Some(retired),
1719            }
1720        }
1721        if self.km_pending.is_none() {
1722            let active = self.km_refresh.active_parity();
1723            if active != self.tx_parity {
1724                self.tx_parity = active;
1725                self.tx_key_sent = 0;
1726            }
1727        }
1728        if let Some(retired) = self.retire_deferred
1729            && retired != self.tx_parity
1730        {
1731            self.tx_keys.clear(retired);
1732            self.retire_deferred = None;
1733        }
1734    }
1735
1736    fn key_refresh_failed(&mut self, parity: KeyParity) {
1737        self.counts.key_refresh_failed = self.counts.key_refresh_failed.saturating_add(1);
1738        self.key_refresh_retry = Some(parity);
1739    }
1740
1741    fn announce_key(&mut self, parity: KeyParity, now_us: u64) {
1742        if self.km_pending.is_some() {
1743            return;
1744        }
1745        let key_len = if self.crypto_key_len == 0 {
1746            DEFAULT_SEK_LEN
1747        } else {
1748            self.crypto_key_len
1749        };
1750        if self.key_refresh_seed.len() < MIN_KEY_REFRESH_SEED_LEN || key_len > KEY_LEN {
1751            self.key_refresh_failed(parity);
1752            return;
1753        }
1754        let draw = self.key_refresh_counter;
1755        self.key_refresh_counter = draw.saturating_add(1);
1756        let mut salt = [0u8; crate::crypto::SALT_LEN];
1757        salt.copy_from_slice(
1758            &derive(&self.key_refresh_seed, LABEL_REFRESH_SALT, draw)[..crate::crypto::SALT_LEN],
1759        );
1760        let sek = derive(&self.key_refresh_seed, LABEL_REFRESH_SEK, draw)[..key_len].to_vec();
1761        let Ok(kek) = crate::crypto::derive_kek(&self.crypto_passphrase, &salt, key_len) else {
1762            self.key_refresh_failed(parity);
1763            return;
1764        };
1765        let Ok((icv, wrapped)) = crate::crypto::wrap_sek(&kek, &sek) else {
1766            self.key_refresh_failed(parity);
1767            return;
1768        };
1769        let km = KeyMaterial {
1770            kk: match parity {
1771                KeyParity::Even => KmKeyFlag::Even,
1772                KeyParity::Odd => KmKeyFlag::Odd,
1773            },
1774            keki: 0,
1775            cipher: crate::packet::Cipher::AesCtr,
1776            auth: crate::packet::KmAuth::None,
1777            se: crate::packet::StreamEncapsulation::MpegTsSrt,
1778            salt: &salt,
1779            icv,
1780            x_sek: &wrapped,
1781            o_sek: None,
1782        };
1783        let Some(datagram) = self.key_material_datagram(EXT_TYPE_KMREQ, &km, now_us) else {
1784            self.key_refresh_failed(parity);
1785            return;
1786        };
1787        self.tx_keys.install(parity, sek, salt);
1788        self.outbound_control.push(datagram.clone());
1789        self.km_pending = Some(PendingKm {
1790            parity,
1791            salt,
1792            datagram,
1793            resend_at_us: now_us.checked_add(micros(self.timers.cadence.km_resend)),
1794        });
1795    }
1796
1797    fn key_material_datagram(
1798        &self,
1799        subtype: u16,
1800        km: &KeyMaterial<'_>,
1801        now_us: u64,
1802    ) -> Option<Vec<u8>> {
1803        let mut cif = alloc::vec![0u8; km.serialized_len()];
1804        km.serialize_into(&mut cif).ok()?;
1805        let ud = ControlPacket::UserDefined(crate::packet::UserDefinedPacket {
1806            control_type: crate::packet::ControlType::UserDefined.to_bits(),
1807            subtype,
1808            type_specific_info: 0,
1809            timestamp: self.wire_now(now_us),
1810            dest_socket_id: SocketId::from_wire(self.peer_socket_id),
1811            cif: &cif,
1812        });
1813        let mut out = alloc::vec![0u8; ud.serialized_len()];
1814        ud.serialize_into(&mut out).ok()?;
1815        Some(out)
1816    }
1817
1818    fn resend_pending_km(&mut self, now_us: u64) {
1819        if let Some(pending) = &mut self.km_pending
1820            && pending.resend_at_us.is_some_and(|at| now_us >= at)
1821        {
1822            self.outbound_control.push(pending.datagram.clone());
1823            pending.resend_at_us = now_us.checked_add(micros(self.timers.cadence.km_resend));
1824        }
1825    }
1826
1827    fn on_peer_key_material(&mut self, subtype: u16, km: &KeyMaterial<'_>, now_us: u64) {
1828        if subtype == EXT_TYPE_KMRSP {
1829            if let Some(pending) = &self.km_pending
1830                && parity_of_kk(km.kk) == Some(pending.parity)
1831                && km.salt == pending.salt
1832            {
1833                self.km_pending = None;
1834            }
1835            return;
1836        }
1837        if subtype != EXT_TYPE_KMREQ {
1838            return;
1839        }
1840        // Recovering the SEK runs PBKDF2; a peer re-sending Key Material back to back is refused
1841        // beyond one message per `KMREQ_MIN_INTERVAL` (#2840). A legitimate refresh that lands
1842        // inside the window is retransmitted by the peer.
1843        if self.last_peer_kmreq_us.is_some_and(|last| {
1844            now_us.saturating_sub(last) < micros(self.timers.cadence.kmreq_min_interval)
1845        }) {
1846            return;
1847        }
1848        self.last_peer_kmreq_us = Some(now_us);
1849        let installed = match km.kk {
1850            KmKeyFlag::Both => crate::handshake_sm::recover_both_seks(
1851                &self.crypto_passphrase,
1852                km,
1853                &mut self.kek_cache,
1854            )
1855            .map(|(even, odd, salt)| {
1856                self.rx_keys.install(KeyParity::Even, even.to_vec(), salt);
1857                self.rx_keys.install(KeyParity::Odd, odd.to_vec(), salt);
1858            })
1859            .is_ok(),
1860            kk => {
1861                let parity = if kk == KmKeyFlag::Odd {
1862                    KeyParity::Odd
1863                } else {
1864                    KeyParity::Even
1865                };
1866                crate::handshake_sm::recover_sek(&self.crypto_passphrase, km, &mut self.kek_cache)
1867                    .map(|(sek, salt)| self.rx_keys.install(parity, sek.to_vec(), salt))
1868                    .is_ok()
1869            }
1870        };
1871        if installed && let Some(rsp) = self.key_material_datagram(EXT_TYPE_KMRSP, km, now_us) {
1872            self.outbound_control.push(rsp);
1873        }
1874    }
1875}
1876
1877// ===========================================================================
1878// CallerLink — the caller role: handshake, then a Link
1879// ===========================================================================
1880
1881/// Width of a derived value: a SHA-256 digest, and the seed the tokio adapter gives it.
1882pub const KEY_LEN: usize = 32;
1883
1884/// Fewest bytes of entropy a link's key-refresh seed may hold: a shorter seed would let the
1885/// publicly derived refresh keys be enumerated.
1886const MIN_KEY_REFRESH_SEED_LEN: usize = 16;
1887
1888const KEYSTREAM_PACKETS: u64 = crate::km_refresh::KEYSTREAM_PACKETS;
1889/// Largest Socket ID either side may draw: the 30-bit field's range (§3).
1890const MAX_OWN_SOCKET_ID: u32 = 0x3FFF_FFFF;
1891/// Width of the Packet Sequence Number field (§3.1).
1892const SEQ_NUMBER_MASK: u32 = 0x7FFF_FFFF;
1893const LABEL_SOCKET_ID: &[u8] = b"srt-socket-id";
1894const LABEL_ISN: &[u8] = b"srt-isn";
1895const LABEL_SALT: &[u8] = b"srt-salt";
1896const LABEL_SEK: &[u8] = b"srt-sek";
1897const LABEL_REFRESH_SALT: &[u8] = b"srt-refresh-salt";
1898const LABEL_REFRESH_SEK: &[u8] = b"srt-refresh-sek";
1899
1900/// One value `seed` derives for `attempt` under `label`: the digest of the seed, the label and the
1901/// attempt number. Nothing it returns is itself a secret: the seed is.
1902fn derive(seed: &[u8], label: &[u8], attempt: u64) -> [u8; KEY_LEN] {
1903    let mut h = Sha256::new();
1904    h.update(seed);
1905    h.update(label);
1906    h.update(attempt.to_be_bytes());
1907    h.finalize().into()
1908}
1909
1910fn first_u32(bytes: &[u8; KEY_LEN]) -> u32 {
1911    let mut head = [0u8; size_of::<u32>()];
1912    head.copy_from_slice(&bytes[..size_of::<u32>()]);
1913    u32::from_be_bytes(head)
1914}
1915
1916fn derive_socket_id(seed: &[u8], attempt: u64) -> u32 {
1917    first_u32(&derive(seed, LABEL_SOCKET_ID, attempt)) % MAX_OWN_SOCKET_ID + 1
1918}
1919
1920fn derive_isn(seed: &[u8], attempt: u64) -> u32 {
1921    first_u32(&derive(seed, LABEL_ISN, attempt)) & SEQ_NUMBER_MASK
1922}
1923
1924/// The caller role: the HSv5 caller handshake, then the established [`Link`].
1925///
1926/// The host calls [`CallerLink::connect`] once and sends what [`CallerLink::take_sent`] hands back;
1927/// every answer from the peer goes to [`CallerLink::on_datagram`], and the host wakes at
1928/// [`CallerLink::next_deadline`] to call [`CallerLink::poll`]. A resolution turns the state into
1929/// a [`Link`], whose own deadlines and datagrams follow from then on.
1930pub struct CallerLink {
1931    params: CallerParams,
1932    attempt: u64,
1933    seed: Vec<u8>,
1934    handshake: Option<CallerHandshake>,
1935    started_us: u64,
1936    next_tick_us: Option<u64>,
1937    last_tick_us: u64,
1938    link: Option<Link>,
1939    sent: Vec<Vec<u8>>,
1940}
1941
1942impl core::fmt::Debug for CallerLink {
1943    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1944        f.debug_struct("CallerLink")
1945            .field("attempt", &self.attempt)
1946            .field("handshaking", &self.handshake.is_some())
1947            .field("connected", &self.link.is_some())
1948            .finish_non_exhaustive()
1949    }
1950}
1951
1952impl CallerLink {
1953    /// A link that has not opened yet. `seed` is the secret entropy every attempt derives its
1954    /// Socket ID, ISN and stream key from, and `attempt` names this opening (a reconnect is the
1955    /// next attempt, and derives fresh values).
1956    #[must_use]
1957    pub fn new(params: &CallerParams, seed: Vec<u8>, attempt: u64) -> Self {
1958        Self {
1959            params: params.clone(),
1960            attempt,
1961            seed,
1962            handshake: None,
1963            started_us: 0,
1964            next_tick_us: None,
1965            last_tick_us: 0,
1966            link: None,
1967            sent: Vec::new(),
1968        }
1969    }
1970
1971    /// The caller's own SRT Socket ID this side advertises: the caller's if it named itself,
1972    /// else this attempt's derivation from the seed.
1973    #[must_use]
1974    pub fn own_socket_id(&self) -> u32 {
1975        if self.params.own_socket_id == 0 {
1976            derive_socket_id(&self.seed, self.attempt)
1977        } else {
1978            self.params.own_socket_id
1979        }
1980    }
1981
1982    /// The established link, once the peer has resolved the handshake.
1983    #[must_use]
1984    pub fn link(&self) -> Option<&Link> {
1985        self.link.as_ref()
1986    }
1987
1988    /// The established link, for sending and polling.
1989    pub fn link_mut(&mut self) -> Option<&mut Link> {
1990        self.link.as_mut()
1991    }
1992
1993    /// Start the handshake at `now`, deriving this attempt's Socket ID, ISN and stream key from
1994    /// the seed. The induction datagram waits for [`CallerLink::take_sent`]; a caller that cannot
1995    /// frame one has no datagram to send.
1996    pub fn connect(&mut self, now: Instant) {
1997        let now_us = now.as_micros();
1998        if self.handshake.is_some() || self.link.is_some() {
1999            return;
2000        }
2001        let config = self.attempt_config();
2002        self.started_us = now_us;
2003        self.last_tick_us = now_us;
2004        self.next_tick_us =
2005            Some(now_us.saturating_add(micros(self.params.timers.cadence.handshake_retransmit)));
2006        let mut handshake = CallerHandshake::new(self.own_socket_id(), config);
2007        handshake.set_elapsed(Duration::ZERO);
2008        match handshake.start() {
2009            Ok(induction) => {
2010                self.sent.push(induction);
2011                self.handshake = Some(handshake);
2012            }
2013            Err(_) => self.sent.clear(),
2014        }
2015    }
2016
2017    /// The handshake this attempt advertises: the caller's own, with this attempt's ISN and its
2018    /// own derived stream key.
2019    fn attempt_config(&self) -> HandshakeConfig {
2020        let config = self
2021            .params
2022            .handshake
2023            .clone()
2024            .with_initial_seq_number(self.initial_seq_number());
2025        if config.encryption_field == EncryptionField::NoEncryption {
2026            return config;
2027        }
2028        // The stream key length follows the advertised cipher; the salt and the SEK derive
2029        // from the seed, so every attempt carries fresh ones.
2030        let key_len = match config.encryption_field {
2031            EncryptionField::Aes192 => 24,
2032            EncryptionField::Aes256 => 32,
2033            _ => DEFAULT_SEK_LEN,
2034        };
2035        let mut salt = [0u8; crate::crypto::SALT_LEN];
2036        let derived = derive(&self.seed, LABEL_SALT, self.attempt);
2037        salt.copy_from_slice(&derived[..crate::crypto::SALT_LEN]);
2038        let sek = derive(&self.seed, LABEL_SEK, self.attempt)[..key_len].to_vec();
2039        let crypto = match config.crypto.clone() {
2040            Some(mut crypto) => {
2041                crypto.salt = salt;
2042                crypto.sek = sek;
2043                crypto
2044            }
2045            None => CryptoConfig {
2046                passphrase: Vec::new(),
2047                salt,
2048                sek,
2049            },
2050        };
2051        config.with_crypto(Some(crypto))
2052    }
2053
2054    /// This attempt's initial sequence number.
2055    fn initial_seq_number(&self) -> u32 {
2056        derive_isn(&self.seed, self.attempt)
2057    }
2058
2059    /// Process one datagram from the peer at `now`.
2060    #[must_use]
2061    pub fn on_datagram(&mut self, datagram: &[u8], now: Instant) -> Delivered {
2062        let now_us = now.as_micros();
2063        if let Some(link) = self.link.as_mut() {
2064            return link.on_datagram(datagram, now);
2065        }
2066        let Some(handshake) = self.handshake.as_mut() else {
2067            return Delivered::default();
2068        };
2069        let mut batch = Batch::default();
2070        handshake.set_elapsed(Duration::from_micros(
2071            now_us.saturating_sub(self.started_us),
2072        ));
2073        let Ok(outputs) = handshake.feed_bytes(datagram) else {
2074            return Delivered::default();
2075        };
2076        for output in outputs {
2077            match output {
2078                HandshakeOutput::Send(bytes) => self.sent.push(bytes),
2079                HandshakeOutput::Connected(params) => {
2080                    let Ok(SrtPacket::Control(ControlPacket::Handshake(hp))) =
2081                        SrtPacket::parse(datagram)
2082                    else {
2083                        batch.end(LinkEnd::HandshakeTimedOut);
2084                        break;
2085                    };
2086                    let started = Instant::from_micros(self.started_us);
2087                    let setup = LinkSetup::new(params, hp.initial_seq_number, 0).with_arrival(
2088                        Duration::from_micros(now_us.saturating_sub(self.started_us)),
2089                        hp.timestamp.value(),
2090                    );
2091                    let mut link = Link::new(started, &setup, &self.params);
2092                    link.start_idle_clock(now);
2093                    self.link = Some(link);
2094                    return batch.finish(&mut false);
2095                }
2096                HandshakeOutput::Rejected(reason) => {
2097                    batch.end(LinkEnd::Rejected(reason));
2098                    break;
2099                }
2100                HandshakeOutput::TimedOut => {
2101                    batch.end(LinkEnd::HandshakeTimedOut);
2102                    break;
2103                }
2104            }
2105        }
2106        batch.finish(&mut false)
2107    }
2108
2109    /// Advance the handshake at `now`: an unanswered request is re-sent once per period — a
2110    /// late wake is one retransmit, not one per missed period (#3847) — and the caller's budget
2111    /// bounds the attempt.
2112    #[must_use]
2113    pub fn poll(&mut self, now: Instant) -> Delivered {
2114        let now_us = now.as_micros();
2115        if let Some(link) = self.link.as_mut() {
2116            return link.poll(now);
2117        }
2118        let Some(handshake) = self.handshake.as_mut() else {
2119            return Delivered::default();
2120        };
2121        let mut batch = Batch::default();
2122        if now_us.saturating_sub(self.started_us) >= micros(self.params.timers.handshake_timeout) {
2123            batch.end(LinkEnd::HandshakeTimedOut);
2124            return batch.finish(&mut false);
2125        }
2126        if self.next_tick_us.is_some_and(|next| now_us >= next) {
2127            let elapsed_us = now_us.saturating_sub(self.last_tick_us).max(1);
2128            self.last_tick_us = now_us;
2129            self.next_tick_us = Some(
2130                now_us.saturating_add(micros(self.params.timers.cadence.handshake_retransmit)),
2131            );
2132            handshake.set_elapsed(Duration::from_micros(
2133                now_us.saturating_sub(self.started_us),
2134            ));
2135            for output in handshake.tick(Duration::from_micros(elapsed_us)) {
2136                match output {
2137                    HandshakeOutput::Send(bytes) => self.sent.push(bytes),
2138                    HandshakeOutput::TimedOut => {
2139                        batch.end(LinkEnd::HandshakeTimedOut);
2140                        return batch.finish(&mut false);
2141                    }
2142                    _ => {}
2143                }
2144            }
2145        }
2146        batch.finish(&mut false)
2147    }
2148
2149    /// The next instant this link must act without an inbound datagram, whichever half is active.
2150    #[must_use]
2151    pub fn next_deadline(&self, now: Instant) -> Option<Instant> {
2152        if let Some(link) = &self.link {
2153            return link.next_deadline(now);
2154        }
2155        self.handshake.as_ref()?;
2156        let budget = self
2157            .started_us
2158            .saturating_add(micros(self.params.timers.handshake_timeout));
2159        Some(Instant::from_micros(match self.next_tick_us {
2160            Some(tick) => budget.min(tick),
2161            None => budget,
2162        }))
2163    }
2164
2165    /// Every datagram this attempt still owes the peer: the handshake's, or the link's.
2166    #[must_use]
2167    pub fn take_sent(&mut self) -> Vec<Vec<u8>> {
2168        let mut sent = core::mem::take(&mut self.sent);
2169        if let Some(link) = self.link.as_mut() {
2170            sent.append(&mut link.take_sent());
2171        }
2172        sent
2173    }
2174
2175    /// Append every datagram due at `now` to `sent`, as the host writes them: the handshake's,
2176    /// then the link's through [`Link::flush`], which records the transmission.
2177    pub fn flush(&mut self, now: Instant, sent: &mut Vec<Vec<u8>>) {
2178        sent.append(&mut self.sent);
2179        if let Some(link) = self.link.as_mut() {
2180            link.flush(now, sent);
2181        }
2182    }
2183}
2184
2185#[cfg(test)]
2186mod caller_link_tests {
2187    use super::*;
2188    use crate::handshake_sm::{HandshakeOutput, NegotiatedParams};
2189    use crate::listener::ListenerHandshake;
2190    use crate::packet::{HandshakePacket, SocketId};
2191    use crate::test_support::at;
2192
2193    const STALL_US: u64 = 3_600_000;
2194    const LATENCY_MS: u64 = 120;
2195
2196    fn params() -> CallerParams {
2197        CallerParams::new(
2198            HandshakeConfig::for_profile(broadcast_core::Profile::Server),
2199            0,
2200            0,
2201            TEST_TIMERS,
2202            crate::test_support::ARQ_BOUNDS,
2203            alloc::vec![7; KEY_LEN],
2204            TEST_DRIFT_WINDOW,
2205        )
2206    }
2207
2208    fn negotiated(flags: u32) -> NegotiatedParams {
2209        NegotiatedParams {
2210            version: 5,
2211            flags: crate::packet::HandshakeExtensionMessageFlags::new(flags),
2212            latency: Duration::from_millis(LATENCY_MS),
2213            own_socket_id: 2,
2214            peer_socket_id: 1,
2215            mtu: 1500,
2216            max_flow_window_size: 8192,
2217            stream_id: None,
2218            group: None,
2219            sek: None,
2220            salt: None,
2221        }
2222    }
2223
2224    fn data(seq: u32, payload: &[u8]) -> Vec<u8> {
2225        let dp = crate::packet::DataPacket {
2226            seq_number: seq,
2227            position: crate::packet::PacketPosition::Solo,
2228            in_order: true,
2229            key_flag: EncryptionKeyField::NotEncrypted,
2230            retransmitted: false,
2231            message_number: seq,
2232            timestamp: SrtTimestamp::ZERO,
2233            dest_socket_id: SocketId::from_wire(1),
2234            data: payload,
2235        };
2236        let mut buf = alloc::vec![0u8; dp.serialized_len()];
2237        dp.serialize_into(&mut buf).expect("serialize data");
2238        buf
2239    }
2240
2241    fn handshake_send(outputs: &[HandshakeOutput]) -> Vec<u8> {
2242        outputs
2243            .iter()
2244            .find_map(|o| match o {
2245                HandshakeOutput::Send(bytes) => Some(bytes.clone()),
2246                _ => None,
2247            })
2248            .expect("a handshake datagram")
2249    }
2250
2251    /// The seed-derived Socket ID stays inside libsrt's allocation range and the
2252    /// ISN inside its 31-bit field, for every seed byte and every attempt.
2253    #[test]
2254    fn the_caller_socket_id_and_initial_sequence_number_are_in_range() {
2255        for (byte, attempt) in [(0xFFu8, 0u64), (0x00, 0), (0x7F, 3)] {
2256            let mut caller = CallerLink::new(&params(), alloc::vec![byte; KEY_LEN], attempt);
2257            caller.connect(Instant::ZERO);
2258            let first = caller.take_sent();
2259            let induction = first.first().expect("the induction handshake");
2260            match SrtPacket::parse(induction) {
2261                Ok(SrtPacket::Control(ControlPacket::Handshake(hs))) => {
2262                    let socket_id = hs.srt_socket_id;
2263                    let isn = hs.initial_seq_number;
2264                    assert!(
2265                        (1..=MAX_OWN_SOCKET_ID).contains(&socket_id),
2266                        "socket id {socket_id} for seed byte {byte} attempt {attempt}"
2267                    );
2268                    assert!(
2269                        isn <= SEQ_NUMBER_MASK,
2270                        "initial sequence number {isn} for seed byte {byte}"
2271                    );
2272                    assert_eq!(socket_id, caller.own_socket_id());
2273                    assert_eq!(isn, caller.initial_seq_number());
2274                }
2275                other => panic!("the first datagram is an induction handshake: {other:?}"),
2276            }
2277        }
2278    }
2279
2280    /// The same seed and attempt derive the same values; a later attempt
2281    /// derives fresh ones.
2282    #[test]
2283    fn the_socket_id_and_initial_sequence_number_derive_from_the_seed() {
2284        let mut seen = alloc::vec::Vec::new();
2285        for attempt in 0..3u64 {
2286            let mut caller = CallerLink::new(&params(), alloc::vec![0x5A; KEY_LEN], attempt);
2287            caller.connect(Instant::ZERO);
2288            let bytes = caller.take_sent().remove(0);
2289            let Ok(SrtPacket::Control(ControlPacket::Handshake(hs))) = SrtPacket::parse(&bytes)
2290            else {
2291                panic!("an induction handshake");
2292            };
2293            seen.push((hs.srt_socket_id, hs.initial_seq_number));
2294
2295            let mut again = CallerLink::new(&params(), alloc::vec![0x5A; KEY_LEN], attempt);
2296            again.connect(Instant::ZERO);
2297            assert_eq!(
2298                again.take_sent(),
2299                alloc::vec![bytes],
2300                "deterministic for one attempt"
2301            );
2302        }
2303        for (a, b) in [(seen[0], seen[1]), (seen[0], seen[2]), (seen[1], seen[2])] {
2304            assert_ne!(a, b, "every attempt derives fresh identifiers");
2305        }
2306    }
2307
2308    /// A starved runtime can wake the session once, several retransmit
2309    /// periods late. That single late poll must count as one retransmit, not
2310    /// synthesize one tick per nominal period: doing the latter spends the
2311    /// whole 12-retry budget at once and times the handshake out while the
2312    /// wall-clock budget is nowhere near spent. The dropped first INDUCTION is
2313    /// still resent and the connection still completes (issue #3847).
2314    #[test]
2315    fn a_late_poll_resends_the_lost_induction_instead_of_timing_out() {
2316        let params = params().with_handshake_timeout(Duration::from_secs(10));
2317        let mut caller = CallerLink::new(&params, alloc::vec![7; KEY_LEN], 0);
2318        caller.connect(Instant::ZERO);
2319        // The very first INDUCTION is lost: the listener never receives it.
2320        let _lost = caller.take_sent();
2321
2322        // One wake, 3.6 s late — fourteen nominal 250 ms periods in one step.
2323        assert!(caller.poll(at(STALL_US)).is_empty());
2324        let late = caller.take_sent();
2325        assert_eq!(late.len(), 1, "exactly one retransmit, not a burst");
2326        let induction = late.into_iter().next().expect("retransmitted induction");
2327        assert_eq!(
2328            caller.next_deadline(at(STALL_US)),
2329            Some(at(
2330                STALL_US + micros(TEST_TIMERS.cadence.handshake_retransmit)
2331            )),
2332            "the next retransmit is one period away"
2333        );
2334
2335        let mut listener = ListenerHandshake::new(
2336            0x1234_5678,
2337            0xC0FF_EE00,
2338            HandshakeConfig::for_profile(broadcast_core::Profile::Server),
2339        );
2340        listener.set_elapsed(Duration::from_micros(STALL_US));
2341        let response = handshake_send(
2342            &listener
2343                .feed_bytes(&induction)
2344                .expect("listener induction response"),
2345        );
2346        let _ = caller.on_datagram(&response, at(STALL_US));
2347        let conclusion = caller.take_sent().into_iter().next().expect("conclusion");
2348
2349        listener.set_elapsed(Duration::from_micros(STALL_US));
2350        let outputs = listener
2351            .feed_bytes(&conclusion)
2352            .expect("listener conclusion response");
2353        assert!(
2354            outputs
2355                .iter()
2356                .any(|o| matches!(o, HandshakeOutput::Connected(_))),
2357            "the listener completes the handshake"
2358        );
2359        let _ = caller.on_datagram(&handshake_send(&outputs), at(STALL_US));
2360        assert!(
2361            caller.link().is_some(),
2362            "the lost-and-resent induction still connects"
2363        );
2364    }
2365
2366    const SLOW_START_US: u64 = 300_000;
2367    const SLOW_CONCLUDED_US: u64 = 800_000;
2368
2369    /// A caller whose handshake took 800 ms, against a listener that began it 300 ms in. Returns
2370    /// the connected caller and the peer's initial sequence number.
2371    fn slow_connected_caller(params: &CallerParams) -> (CallerLink, u32) {
2372        let mut caller = CallerLink::new(params, alloc::vec![7; KEY_LEN], 0);
2373        caller.connect(Instant::ZERO);
2374        let induction = caller.take_sent().into_iter().next().expect("induction");
2375        let mut listener = ListenerHandshake::new(
2376            0x1234_5678,
2377            0xC0FF_EE00,
2378            HandshakeConfig::for_profile(broadcast_core::Profile::Server),
2379        );
2380        listener.set_elapsed(Duration::ZERO);
2381        let response =
2382            handshake_send(&listener.feed_bytes(&induction).expect("induction response"));
2383        let _ = caller.on_datagram(&response, at(SLOW_START_US + 100_000));
2384        let conclusion = caller.take_sent().into_iter().next().expect("conclusion");
2385        listener.set_elapsed(Duration::from_micros(SLOW_CONCLUDED_US - SLOW_START_US));
2386        let outputs = listener
2387            .feed_bytes(&conclusion)
2388            .expect("conclusion response");
2389        let response = handshake_send(&outputs);
2390        let Ok(SrtPacket::Control(ControlPacket::Handshake(hp))) = SrtPacket::parse(&response)
2391        else {
2392            panic!("the listener answers with a handshake");
2393        };
2394        let isn = hp.initial_seq_number;
2395        let _ = caller.on_datagram(&response, at(SLOW_CONCLUDED_US));
2396        assert!(caller.link().is_some(), "connected");
2397        (caller, isn)
2398    }
2399
2400    /// The handshake's timestamps and the link's counted from `started_us`: a payload sent 100 ms
2401    /// after a handshake that took 800 ms carries 900 ms, not 100 ms, which the peer would take
2402    /// to mean it was sent 800 ms earlier and release early.
2403    #[test]
2404    fn payloads_are_stamped_from_the_handshakes_start() {
2405        let (mut caller, _) = slow_connected_caller(&params());
2406        let sent_at = at(SLOW_CONCLUDED_US + 100_000);
2407        let link = caller.link_mut().expect("connected");
2408        link.send(b"payload", sent_at);
2409        let mut out = Vec::new();
2410        link.flush(sent_at, &mut out);
2411        let stamp = out
2412            .iter()
2413            .find_map(|d| match SrtPacket::parse(d) {
2414                Ok(SrtPacket::Data(dp)) => Some(u64::from(dp.timestamp.value())),
2415                _ => None,
2416            })
2417            .expect("a data packet");
2418        assert_eq!(stamp, SLOW_CONCLUDED_US + 100_000);
2419    }
2420
2421    /// The peer's timestamps map onto the link's clock through the signed time base: a payload
2422    /// stamped when the peer sent it is released one latency after it arrived (zero flight).
2423    #[test]
2424    fn a_peers_payload_is_released_one_latency_after_it_was_sent() {
2425        let (mut caller, isn) = slow_connected_caller(&params());
2426        let sent_at_us = SLOW_CONCLUDED_US + 100_000;
2427        let peer_elapsed_us = sent_at_us - SLOW_START_US;
2428        let dp = crate::packet::DataPacket {
2429            seq_number: isn,
2430            position: crate::packet::PacketPosition::Solo,
2431            in_order: true,
2432            key_flag: EncryptionKeyField::NotEncrypted,
2433            retransmitted: false,
2434            message_number: 1,
2435            timestamp: SrtTimestamp::from_wire(u32::try_from(peer_elapsed_us).expect("fits")),
2436            dest_socket_id: SocketId::from_wire(2),
2437            data: b"payload",
2438        };
2439        let mut wire = alloc::vec![0u8; dp.serialized_len()];
2440        dp.serialize_into(&mut wire).expect("serialize");
2441        let release_us = sent_at_us + LATENCY_MS * 1_000;
2442        let _ = caller.on_datagram(&wire, at(sent_at_us));
2443        let early = caller.poll(at(release_us - 1_000));
2444        assert_eq!(
2445            early.payloads().count(),
2446            0,
2447            "not before the latency has passed"
2448        );
2449        let due = caller.poll(at(release_us));
2450        assert_eq!(due.payloads().collect::<Vec<_>>(), [b"payload".as_slice()]);
2451    }
2452
2453    /// The silence clock starts when the connection is made, not at the handshake's start: a
2454    /// silent peer ends it one `read_idle` after the conclusion.
2455    #[test]
2456    fn the_idle_clock_starts_at_the_conclusion() {
2457        let (mut caller, _) = slow_connected_caller(&params());
2458        let idle_us = micros(TEST_TIMERS.read_idle);
2459        let before = caller.poll(at(SLOW_CONCLUDED_US + idle_us - 1_000));
2460        assert!(
2461            !before
2462                .items()
2463                .iter()
2464                .any(|item| matches!(item, DeliveredItem::Ended(LinkEnd::PeerIdle))),
2465            "alive just inside the bound"
2466        );
2467        let after = caller.poll(at(SLOW_CONCLUDED_US + idle_us));
2468        assert!(
2469            after
2470                .items()
2471                .iter()
2472                .any(|item| matches!(item, DeliveredItem::Ended(LinkEnd::PeerIdle)))
2473        );
2474    }
2475
2476    /// A caller whose budget runs out before any resolution ends the attempt
2477    /// once, and names why.
2478    #[test]
2479    fn the_handshake_budget_ends_the_attempt() {
2480        let budget = Duration::from_millis(400);
2481        let params = params().with_handshake_timeout(budget);
2482        let mut caller = CallerLink::new(&params, alloc::vec![1; KEY_LEN], 0);
2483        caller.connect(Instant::ZERO);
2484        let _ = caller.take_sent();
2485        assert!(
2486            caller.poll(at(micros(budget) - 1)).is_empty(),
2487            "still inside it"
2488        );
2489        assert!(matches!(
2490            caller.poll(at(micros(budget))).items(),
2491            [DeliveredItem::Ended(LinkEnd::HandshakeTimedOut)]
2492        ));
2493    }
2494
2495    /// A peer that refuses ends the attempt with its own reason.
2496    #[test]
2497    fn a_rejection_ends_the_attempt_with_its_reason() {
2498        let params = CallerParams::new(
2499            HandshakeConfig::for_profile(broadcast_core::Profile::Server)
2500                .with_encryption_field(EncryptionField::Aes128),
2501            0,
2502            0,
2503            TEST_TIMERS,
2504            crate::test_support::ARQ_BOUNDS,
2505            alloc::vec![7; KEY_LEN],
2506            TEST_DRIFT_WINDOW,
2507        )
2508        .with_passphrase(b"passphrase".to_vec());
2509        let mut caller = CallerLink::new(&params, alloc::vec![2; KEY_LEN], 0);
2510        caller.connect(Instant::ZERO);
2511        let _ = caller.take_sent();
2512        let reason = RejectionReason::Unsecure;
2513        let packet = ControlPacket::Handshake(HandshakePacket {
2514            timestamp: SrtTimestamp::ZERO,
2515            dest_socket_id: SocketId::CONNECTION_REQUEST,
2516            version: crate::handshake_sm::HANDSHAKE_VERSION_5,
2517            encryption_field: EncryptionField::NoEncryption,
2518            extension_field: crate::packet::HandshakeExtensionFlags::new(0),
2519            initial_seq_number: 0,
2520            mtu: 1500,
2521            max_flow_window_size: 8192,
2522            handshake_type: reason.to_handshake_type(),
2523            srt_socket_id: 9,
2524            syn_cookie: 0,
2525            peer_ip: [0; 4],
2526            extensions: crate::packet::HandshakeExtensions(alloc::vec::Vec::new()),
2527        });
2528        let mut bytes = alloc::vec![0u8; packet.serialized_len()];
2529        packet
2530            .serialize_into(&mut bytes)
2531            .expect("serialize rejection");
2532        assert!(matches!(
2533            caller.on_datagram(&bytes, Instant::ZERO).items(),
2534            [DeliveredItem::Ended(LinkEnd::Rejected(r))] if *r == reason
2535        ));
2536    }
2537
2538    /// The control-packet wire timestamp is a microsecond count that wraps at 2^32.
2539    #[test]
2540    fn a_control_timestamp_is_the_low_32_bits_of_the_clock() {
2541        assert_eq!(
2542            timestamp_to_wire_us(Instant::from_micros(0x1_0000_0005)).value(),
2543            5
2544        );
2545        assert_eq!(
2546            timestamp_to_wire_us(Instant::from_micros(0x00FF_FFFF_FFFF)).value(),
2547            0xFFFF_FFFF
2548        );
2549    }
2550
2551    /// A DROPREQ removes the staged packets inside its range; the packets outside
2552    /// it are released on time.
2553    #[test]
2554    fn a_drop_request_removes_the_staged_packets_inside_its_range() {
2555        let mut link = Link::new(
2556            Instant::ZERO,
2557            &LinkSetup::new(
2558                negotiated(crate::packet::handshake::HS_MSG_FLAG_TLPKTDROP),
2559                100,
2560                0,
2561            ),
2562            &params(),
2563        );
2564        for seq in [100u32, 101, 102, 103, 104] {
2565            assert!(
2566                link.on_datagram(&data(seq, b"x"), Instant::ZERO).is_empty(),
2567                "nothing released yet"
2568            );
2569        }
2570        assert_eq!(
2571            link.staged_len(),
2572            5,
2573            "everything ahead of the cursor is staged"
2574        );
2575        let req = ControlPacket::DropReq(DropReqPacket {
2576            message_number: crate::packet::MessageNumber::try_new(1).expect("message"),
2577            timestamp: SrtTimestamp::ZERO,
2578            dest_socket_id: SocketId::from_wire(1),
2579            first_seq: crate::packet::SeqNo::try_new(101).expect("first"),
2580            last_seq: crate::packet::SeqNo::try_new(103).expect("last"),
2581        });
2582        let mut bytes = alloc::vec![0u8; req.serialized_len()];
2583        req.serialize_into(&mut bytes).expect("serialize dropreq");
2584        // The DROPREQ does not drain on its own: the ring has no gap between the
2585        // staged range and the release pass, and the dropped range is never handed
2586        // to the host.
2587        let _ = link.on_datagram(&bytes, Instant::ZERO);
2588        let mut delivered = alloc::vec::Vec::new();
2589        delivered.extend(
2590            link.poll(at(micros(Duration::from_millis(LATENCY_MS))))
2591                .into_items(),
2592        );
2593        let payloads: usize = delivered
2594            .iter()
2595            .filter(|item| matches!(item, DeliveredItem::Payload(_)))
2596            .count();
2597        assert!(
2598            (1..=5).contains(&payloads),
2599            "the dropped range is never delivered, and the rest arrives on time: {payloads}"
2600        );
2601    }
2602}
2603
2604#[cfg(test)]
2605mod link_key_tests {
2606    use super::*;
2607    use crate::handshake_sm::NegotiatedParams;
2608    use crate::test_support::at;
2609
2610    const LATENCY_MS: u64 = 120;
2611
2612    fn test_link() -> Link {
2613        test_link_with(TEST_TIMERS, alloc::vec![7; KEY_LEN])
2614    }
2615
2616    fn test_link_with(timers: LinkTimers, seed: Vec<u8>) -> Link {
2617        let params = NegotiatedParams {
2618            version: 5,
2619            flags: crate::packet::HandshakeExtensionMessageFlags::new(0),
2620            latency: Duration::from_millis(LATENCY_MS),
2621            own_socket_id: 2,
2622            peer_socket_id: 1,
2623            mtu: 1500,
2624            max_flow_window_size: 8192,
2625            stream_id: None,
2626            group: None,
2627            sek: None,
2628            salt: None,
2629        };
2630        Link::new(
2631            Instant::ZERO,
2632            &LinkSetup::new(params, 0, 0),
2633            &CallerParams::new(
2634                HandshakeConfig::for_profile(broadcast_core::Profile::Server),
2635                0,
2636                0,
2637                timers,
2638                crate::test_support::ARQ_BOUNDS,
2639                seed,
2640                TEST_DRIFT_WINDOW,
2641            ),
2642        )
2643    }
2644
2645    #[test]
2646    fn key_set_clear_empties_the_slot() {
2647        let mut keys = KeySet::default();
2648        keys.install(
2649            KeyParity::Even,
2650            alloc::vec![1u8; DEFAULT_SEK_LEN],
2651            [0; crate::crypto::SALT_LEN],
2652        );
2653        assert!(!keys.is_empty());
2654        keys.clear(KeyParity::Even);
2655        assert!(keys.is_empty());
2656    }
2657
2658    #[test]
2659    fn key_refresh_does_not_clear_the_active_parity() {
2660        let mut link = test_link();
2661        link.install_active_parity(KeyParity::Even);
2662        link.defer_retire(KeyParity::Even);
2663        link.advance_key_refresh(0);
2664        assert!(
2665            link.tx_key_installed(KeyParity::Even),
2666            "the active parity must never be retired"
2667        );
2668    }
2669
2670    #[test]
2671    fn key_refresh_clears_a_retired_parity() {
2672        let mut link = test_link();
2673        link.install_active_parity(KeyParity::Even);
2674        link.install_key(KeyParity::Odd, alloc::vec![2u8; DEFAULT_SEK_LEN]);
2675        link.defer_retire(KeyParity::Odd);
2676        link.advance_key_refresh(0);
2677        assert!(
2678            !link.tx_key_installed(KeyParity::Odd),
2679            "a retired (non-active) parity is wiped"
2680        );
2681        assert!(link.tx_key_installed(KeyParity::Even));
2682    }
2683
2684    #[test]
2685    fn announce_key_uses_the_default_sek_length_when_unset() {
2686        let mut link = test_link();
2687        link.set_passphrase(b"pw".to_vec());
2688        link.announce_key_for_test(KeyParity::Even);
2689        assert_eq!(link.tx_key_len(KeyParity::Even), Some(DEFAULT_SEK_LEN));
2690        assert_eq!(DEFAULT_SEK_LEN, 16);
2691    }
2692
2693    #[test]
2694    fn resend_pending_km_repeats_a_due_key_material_request() {
2695        let mut link = test_link();
2696        link.pend_km_for_test(KeyParity::Even, alloc::vec![9u8, 9], 0);
2697        link.resend_pending_km(0);
2698        assert_eq!(link.take_sent(), alloc::vec![alloc::vec![9u8, 9]]);
2699    }
2700
2701    fn keepalives(sent: &[Vec<u8>]) -> usize {
2702        sent.iter()
2703            .filter(|d| {
2704                matches!(
2705                    SrtPacket::parse(d),
2706                    Ok(SrtPacket::Control(ControlPacket::KeepAlive(_)))
2707                )
2708            })
2709            .count()
2710    }
2711
2712    /// A receive-only link sends only control: writing it out must restart the Keep-Alive period,
2713    /// or the link queues a Keep-Alive on every wake once the first second has passed.
2714    #[test]
2715    fn a_flushed_control_datagram_restarts_the_keepalive_period() {
2716        const SENT_US: u64 = 600_000;
2717        let period = micros(TEST_TIMERS.cadence.keepalive);
2718        let mut link = test_link();
2719        let mut sent = Vec::new();
2720        link.queue_keepalive(SENT_US);
2721        link.flush(at(SENT_US), &mut sent);
2722        assert_eq!(keepalives(&sent), 1);
2723
2724        let mut sent = Vec::new();
2725        let _ = link.poll_io(at(period + micros(MIN_WAKE)), &mut sent);
2726        assert_eq!(
2727            keepalives(&sent),
2728            0,
2729            "{} µs after the last write",
2730            period + micros(MIN_WAKE) - SENT_US
2731        );
2732    }
2733
2734    #[test]
2735    fn a_key_refresh_without_entropy_is_counted_reported_and_retried() {
2736        let mut link = test_link_with(TEST_TIMERS, Vec::new());
2737        link.set_passphrase(b"pw".to_vec());
2738        link.announce_key_for_test(KeyParity::Even);
2739        assert_eq!(link.counts().key_refresh_failed, 1);
2740        assert!(!link.tx_key_installed(KeyParity::Even));
2741        let delivered = link.poll(at(1));
2742        assert!(
2743            delivered
2744                .items()
2745                .iter()
2746                .any(|i| matches!(i, DeliveredItem::Damage(_))),
2747            "{:?}",
2748            delivered.items()
2749        );
2750        link.advance_key_refresh(2);
2751        assert_eq!(link.counts().key_refresh_failed, 2);
2752    }
2753
2754    #[test]
2755    fn a_seeded_key_refresh_is_deterministic_and_seed_specific() {
2756        let announce = |seed: u8| {
2757            let mut link = test_link_with(TEST_TIMERS, alloc::vec![seed; KEY_LEN]);
2758            link.set_passphrase(b"pw".to_vec());
2759            link.announce_key_for_test(KeyParity::Even);
2760            assert_eq!(link.counts().key_refresh_failed, 0);
2761            link.take_sent()
2762        };
2763        let first = announce(1);
2764        assert!(!first.is_empty());
2765        assert_eq!(first, announce(1));
2766        assert_ne!(first, announce(2));
2767    }
2768
2769    #[test]
2770    fn the_keepalive_period_is_the_callers() {
2771        let mut timers = TEST_TIMERS;
2772        timers.cadence.keepalive = Duration::from_millis(20);
2773        let mut link = test_link_with(timers, alloc::vec![7; KEY_LEN]);
2774        let mut sent = Vec::new();
2775        let _ = link.poll_io(at(micros(Duration::from_millis(19))), &mut sent);
2776        assert_eq!(keepalives(&sent), 0);
2777        let _ = link.poll_io(at(micros(Duration::from_millis(45))), &mut sent);
2778        assert!(keepalives(&sent) >= 1);
2779    }
2780
2781    #[test]
2782    fn the_key_material_resend_interval_is_the_callers() {
2783        let mut timers = TEST_TIMERS;
2784        timers.cadence.km_resend = Duration::from_millis(30);
2785        let mut link = test_link_with(timers, alloc::vec![7; KEY_LEN]);
2786        link.set_passphrase(b"pw".to_vec());
2787        link.announce_key_for_test(KeyParity::Even);
2788        let _ = link.take_sent();
2789        link.resend_pending_km(0);
2790        let _ = link.take_sent();
2791        link.resend_pending_km(micros(Duration::from_millis(29)));
2792        assert!(link.take_sent().is_empty());
2793        link.resend_pending_km(micros(Duration::from_millis(31)));
2794        assert_eq!(link.take_sent().len(), 1);
2795    }
2796
2797    #[test]
2798    fn the_read_idle_bound_is_the_callers() {
2799        let mut timers = TEST_TIMERS;
2800        timers.read_idle = Duration::from_millis(40);
2801        let mut link = test_link_with(timers, alloc::vec![7; KEY_LEN]);
2802        assert!(
2803            link.poll(at(micros(Duration::from_millis(39))))
2804                .items()
2805                .is_empty()
2806        );
2807        assert!(matches!(
2808            link.poll(at(micros(Duration::from_millis(41)))).items(),
2809            [DeliveredItem::Ended(LinkEnd::PeerIdle)]
2810        ));
2811    }
2812
2813    #[test]
2814    fn no_timer_or_cadence_type_has_a_default() {
2815        trait AmbiguousIfDefault<A> {
2816            fn some_item() {}
2817        }
2818        impl<T> AmbiguousIfDefault<()> for T {}
2819        impl<T: Default> AmbiguousIfDefault<u8> for T {}
2820        <LinkTimers as AmbiguousIfDefault<_>>::some_item();
2821        <LinkCadence as AmbiguousIfDefault<_>>::some_item();
2822    }
2823}
2824
2825#[cfg(test)]
2826mod retransmit_tests;
2827
2828#[cfg(test)]
2829mod key_lifetime_tests;