Skip to main content

srt_runtime/
io.rs

1//! Async real-socket UDP adapter over the sans-IO SRT engine.
2//!
3//! The sans-IO [`crate::caller::CallerHandshake`] / [`crate::listener::ListenerHandshake`]
4//! engines never touch a socket — they turn state transitions into typed events
5//! and byte buffers. The ARQ sender/receiver, TSBPD scheduler, and LiveCC
6//! pacing controller follow the same contract: all take caller-supplied
7//! `now: core::time::Duration` and never read a wall clock.
8//!
9//! This module is the thin tokio layer that actually moves bytes over a
10//! [`tokio::net::UdpSocket`], drives the handshake to completion, and then
11//! runs a **background driver task** per connection that pumps socket RX →
12//! engines → socket TX and, crucially, drives the timers (retransmit, ACK,
13//! NAK, TSBPD release, keep-alive, pacing) from the connection's own next
14//! deadline (`Driver::poll_timeout`) — so loss recovery keeps making progress
15//! even when the application is neither sending nor receiving at that instant,
16//! without a fixed tick. The sans-IO core stays `no_std`; the adapter is pure
17//! plumbing.
18//!
19//! Timeouts and the datagram size are explicit: [`IoConfig`]
20//! (`connect`/`handshake`/`read_idle`/`write`, `max_datagram`). Datagrams are
21//! [`bytes::Bytes`], one exactly-sized allocation per received datagram (never a
22//! view into a shared chunk, which would pin the whole chunk while one packet
23//! is held); the payload handed to the application is a slice of it, so there
24//! is no further copy.
25//!
26//! # Why a background task
27//!
28//! SRT reliability is bidirectional and continuous: a receiver that detects a
29//! gap emits a NAK, and the *sender* must react to that NAK by retransmitting
30//! — long after the application handed it the original payload. A purely
31//! pull-based `send`/`recv` (one that only advances the protocol while the
32//! app is blocked inside a call) deadlocks the moment a fire-and-forget sender
33//! stops calling `send`: the inbound NAK is never drained and the lost packet
34//! is never resent. The driver task decouples protocol progress from
35//! application call timing: [`SrtSocket::send`] enqueues a payload,
36//! [`SrtSocket::recv`] awaits a delivered payload, and the task in between
37//! runs the select loop (RX / app-send / next deadline) until the peer shuts
38//! down, falls silent, or the [`SrtSocket`] is dropped.
39//!
40//! # Connection lifetime
41//!
42//! - **Keep-alive** (§3.2.3): after one second without sending anything, the
43//!   driver sends a Keep-Alive, so a quiet sender is not mistaken for a dead
44//!   one by a peer's own idle timeout (libsrt's default is five seconds).
45//! - **Peer idle timeout**: five seconds without *any* packet from the peer
46//!   ends the connection ([`SrtSocket::recv`] then returns `None`).
47//! - **Shutdown** (§3.2.7): dropping an [`SrtSocket`] sends the peer a
48//!   SHUTDOWN so it closes at once instead of waiting out its idle timeout;
49//!   a received SHUTDOWN ends the connection.
50//! - **Backpressure**: [`SrtSocket::send`] waits while the sender already
51//!   holds a full flow window of unacknowledged packets, so a stalled or dead
52//!   peer cannot make the send buffer grow without bound.
53//!
54//! # Structure
55//!
56//! - [`SrtListener`] — binds a UDP port and accepts incoming SRT connections,
57//!   returning a [`SrtSocket`] per connected peer.
58//! - [`SrtSocket`] — a handle to an established SRT connection (caller or
59//!   listener role) with async [`send`](SrtSocket::send) and
60//!   [`recv`](SrtSocket::recv) for application payloads; the actual protocol
61//!   runs on the background driver task the handle owns.
62//!
63//! # Feature gate
64//!
65//! Only available with `features = ["tokio"]` (implies `std`). Without the
66//! `tokio` feature, the crate stays `no_std`+`alloc` and nothing in this
67//! module is compiled.
68
69use broadcast_common::error::InvalidField;
70use broadcast_common::stage::Timestamp;
71use broadcast_common::timeouts::Timeouts;
72use std::hash::{Hash, Hasher};
73use std::sync::atomic::{AtomicU64, Ordering};
74use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
75
76use alloc::collections::VecDeque;
77use core::time::Duration;
78
79use bytes::Bytes;
80use tokio::net::UdpSocket;
81use tokio::sync::mpsc;
82use tokio::time::Instant;
83use tokio_util::sync::CancellationToken;
84use tokio_util::task::TaskTracker;
85
86use crate::arq::seq::{contiguous_runs, seq_diff, seq_in_closed_range, seq_lt, seq_next};
87use crate::arq::{Receiver as ArqReceiver, Sender as ArqSender};
88use crate::caller::CallerHandshake;
89use crate::error::{Error, Result};
90use crate::handshake_sm::{self, HandshakeConfig, HandshakeOutput, RejectionReason, derive_cookie};
91use crate::listener::{ListenerHandshake, ListenerHandshakeState};
92use crate::livecc::{LiveCC, MaxBwConfig};
93use crate::packet::data::next_message_number;
94use crate::packet::misc::{KeepAlivePacket, ShutdownPacket};
95use crate::packet::{
96    ControlPacket, DropReqPacket, EncryptionField, EncryptionKeyField, HandshakeExtensionFlags,
97    HandshakeExtensions, HandshakePacket, HandshakeType, SEQ_NUMBER_MASK, SRT_HEADER_LEN,
98    SrtPacket,
99};
100use crate::tsbpd::{TickOutcome, TsbpdScheduler};
101
102#[cfg(feature = "crypto")]
103#[cfg(feature = "crypto")]
104use crate::km_refresh::{KeyParity, KmRefreshEvent};
105
106// ===========================================================================
107// Constants
108// ===========================================================================
109
110/// Default for [`IoConfig::max_datagram`]: one Ethernet MTU of UDP payload.
111const DEFAULT_MAX_DATAGRAM: usize = 1500;
112/// Smallest accepted [`IoConfig::max_datagram`]: a full SRT header (16 bytes)
113/// plus room for a control CIF. A smaller request is clamped up to this (and a
114/// larger one down to [`MAX_MAX_DATAGRAM`]).
115pub const MIN_MAX_DATAGRAM: usize = 64;
116/// Largest accepted [`IoConfig::max_datagram`]: the biggest UDP payload.
117pub const MAX_MAX_DATAGRAM: usize = 65_535;
118
119/// The SRT adapter's default [`Timeouts`]: 10 s to resolve and bind, a 5 s
120/// caller handshake, and 5 s for both an idle peer (libsrt's
121/// `SRTO_PEERIDLETIMEO` default of 5000 ms) and a single `send_to`.
122pub const SRT_TIMEOUTS: Timeouts = Timeouts::new(
123    Duration::from_secs(10),
124    Duration::from_secs(5),
125    Duration::from_secs(5),
126    Duration::from_secs(5),
127);
128
129/// Everything one SRT connection or listener is configured by: the handshake
130/// this side advertises and the adapter's timeouts and sizes. Every
131/// `SrtSocket` and `SrtListener` constructor takes the config:
132/// `SrtSocketConfig::default()` (a default [`HandshakeConfig`] and [`IoConfig`])
133/// or `SrtSocketConfig::new(handshake).with_io(io)` for its own values. It is
134/// named for its role, not `SrtClientConfig`, because one config serves both
135/// the caller (`SrtSocket::connect`) and the listener (`SrtListener::bind`).
136#[derive(Debug, Clone, PartialEq)]
137#[non_exhaustive]
138pub struct SrtSocketConfig {
139    /// The handshake values this side advertises.
140    pub handshake: HandshakeConfig,
141    /// The tokio adapter's timeouts and sizes.
142    pub io: IoConfig,
143}
144
145impl SrtSocketConfig {
146    /// A config with `handshake` and the default [`IoConfig`].
147    pub fn new(handshake: HandshakeConfig) -> Self {
148        SrtSocketConfig {
149            handshake,
150            io: IoConfig::default(),
151        }
152    }
153
154    /// Replace [`SrtSocketConfig::handshake`].
155    #[must_use]
156    pub fn with_handshake(mut self, handshake: HandshakeConfig) -> Self {
157        self.handshake = handshake;
158        self
159    }
160
161    /// Replace [`SrtSocketConfig::io`].
162    #[must_use]
163    pub fn with_io(mut self, io: IoConfig) -> Self {
164        self.io = io;
165        self
166    }
167}
168
169impl Default for SrtSocketConfig {
170    fn default() -> Self {
171        SrtSocketConfig::new(HandshakeConfig::default())
172    }
173}
174
175/// Timeouts and sizes for the tokio adapter, carried by [`SrtSocketConfig`] into
176/// [`SrtSocket::connect`] and [`SrtListener::bind`].
177///
178/// Every field has a documented default; use the `with_*` builders so new
179/// fields can be added without breaking callers.
180#[derive(Debug, Clone, Copy, PartialEq, Eq)]
181#[non_exhaustive]
182pub struct IoConfig {
183    /// Largest datagram accepted from the network (bytes). Default 1500. A
184    /// larger datagram is dropped and counted in [`SocketStats::rx_oversize`]
185    /// (UDP would otherwise truncate it silently). Values below
186    /// [`MIN_MAX_DATAGRAM`] are clamped up to it.
187    pub max_datagram: usize,
188    /// The bounds on every awaited I/O: `connect` (resolving the remote
189    /// address and binding the local socket), `handshake` (the whole caller
190    /// handshake), `read_idle` (longest silence from a connected peer before the
191    /// connection is torn down) and `write` (longest a single `send_to` may
192    /// take). Default [`SRT_TIMEOUTS`].
193    pub timeouts: Timeouts,
194    /// KM Refresh thresholds (crypto feature / key rotation). Default the
195    /// spec-recommended `2^25` / `4000` values. Lower for testing.
196    #[cfg(feature = "crypto")]
197    pub km_refresh_thresholds: crate::km_refresh::KmRefreshThresholds,
198}
199
200impl Default for IoConfig {
201    fn default() -> Self {
202        IoConfig {
203            max_datagram: DEFAULT_MAX_DATAGRAM,
204            timeouts: SRT_TIMEOUTS,
205            #[cfg(feature = "crypto")]
206            km_refresh_thresholds: crate::km_refresh::KmRefreshThresholds::RECOMMENDED,
207        }
208    }
209}
210
211impl IoConfig {
212    /// Set [`max_datagram`](Self::max_datagram), clamped up to [`MIN_MAX_DATAGRAM`].
213    #[must_use]
214    pub fn with_max_datagram(mut self, n: usize) -> Self {
215        self.max_datagram = n.clamp(MIN_MAX_DATAGRAM, MAX_MAX_DATAGRAM);
216        self
217    }
218
219    /// Set [`timeouts`](Self::timeouts).
220    #[must_use]
221    pub fn with_timeouts(mut self, timeouts: Timeouts) -> Self {
222        self.timeouts = timeouts;
223        self
224    }
225
226    /// Set the KM Refresh thresholds (key rotation packet counts).
227    #[cfg(feature = "crypto")]
228    #[must_use]
229    pub fn with_km_refresh_thresholds(mut self, t: crate::km_refresh::KmRefreshThresholds) -> Self {
230        self.km_refresh_thresholds = t;
231        self
232    }
233}
234
235/// Reads one datagram into the reusable `scratch` buffer (length
236/// `max + 1`) and returns it as an exactly-sized `Bytes`, or `None` for an
237/// oversize datagram (which has been counted and dropped).
238///
239/// The copy-out is deliberate: a `Bytes` that was a view into a shared receive
240/// chunk would keep the WHOLE chunk alive for as long as that one packet is
241/// staged behind a gap, queued for the application or held by it (on a shared
242/// listener socket, interleaved connections multiply that). One small
243/// allocation per datagram bounds retained memory to the datagrams actually
244/// held; the payload is still not copied again on its way to the application
245/// (`Driver::release` slices it).
246async fn recv_datagram(
247    udp: &UdpSocket,
248    scratch: &mut [u8],
249    max: usize,
250    oversize: &AtomicU64,
251) -> std::io::Result<Option<(Bytes, std::net::SocketAddr)>> {
252    // `scratch` is `max + 1` long: a datagram of max+1 bytes proves "larger
253    // than max" (UDP would otherwise truncate it silently).
254    let (n, src) = udp.recv_from(scratch).await?;
255    if n > max {
256        oversize.fetch_add(1, Ordering::Relaxed);
257        return Ok(None);
258    }
259    Ok(Some((Bytes::copy_from_slice(&scratch[..n]), src)))
260}
261
262/// One [`RouteTable`] entry: the accepted connection's ingress channel, plus
263/// the source address it was accepted from. libsrt demultiplexes its
264/// multiplexed listener socket by Destination Socket ID, not source address
265/// (draft §4.3.1; `CRcvQueue::worker` dispatches on it in `srtcore/core.cpp`)
266/// — the address is kept here only to *check* it against the datagram that
267/// claims this ID (see [`routing_pump`]), so a spoofed ID from
268/// the wrong peer cannot be injected into someone else's session.
269#[derive(Debug, Clone)]
270struct RouteEntry {
271    addr: std::net::SocketAddr,
272    tx: mpsc::Sender<Bytes>,
273    /// Shared with that connection's [`Driver`]/[`SrtSocket`], so a drop
274    /// here (channel full) is counted where [`SrtSocket::stats`] can see it.
275    stats: Arc<Counters>,
276}
277
278/// Shared per-socket demultiplexing table (issue #1029): maps an accepted
279/// connection's own Socket ID to its [`RouteEntry`]. A [`SrtListener`]'s
280/// single bound socket is used by every connection it has accepted, so —
281/// unlike a [`SrtSocket::connect`]'s own dedicated, unshared socket — the
282/// listener needs exactly one task reading the socket and routing each
283/// datagram, never one `recv_from` call per connection racing another's on
284/// the same socket (see the module doc on [`SrtListener`]).
285type RouteTable = Arc<Mutex<std::collections::HashMap<u32, RouteEntry>>>;
286
287/// Lock `mutex`, recovering the guard if a previous holder panicked.
288///
289/// A poisoned lock must never turn into a second panic — least of all inside
290/// a `Drop` (see [`RouteCleanup`]) or the routing pump, which would then take
291/// the whole listener down for one panicking connection task. Every critical
292/// section here is a single `HashMap` insert/remove/get that cannot leave the
293/// map half-updated, so the state behind a poisoned lock is still consistent
294/// (issue #1134).
295fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
296    mutex.lock().unwrap_or_else(PoisonError::into_inner)
297}
298
299/// RAII guard that removes this connection's entry from the listener's shared
300/// [`RouteTable`] when dropped. A stale route was a real leak: dropping a
301/// listener-accepted [`SrtSocket`] runs `Drop::drop` → `handle.abort()`,
302/// which cancels the driver task at its next await point and drops its
303/// future (and everything the future owns) without ever reaching the
304/// explicit cleanup that used to sit at the tail of [`Driver::run`]'s loop —
305/// that code only ran on a *normal* return, never on abort. A `Drop` impl
306/// runs either way, since it fires when this guard's owner (the future) is
307/// dropped, not only when the function body finishes.
308struct RouteCleanup(Option<(u32, RouteTable)>);
309
310impl Drop for RouteCleanup {
311    fn drop(&mut self) {
312        if let Some((id, routes)) = self.0.take() {
313            lock(&routes).remove(&id);
314        }
315    }
316}
317
318/// Aborts the wrapped background task when dropped. A [`SrtSocket::connect`]ed
319/// caller's dedicated-socket forwarder task (`spawn_dedicated_socket_forwarder`)
320/// holds its own `Arc<UdpSocket>` clone and loops on `recv_from` forever —
321/// dropping the `Driver`'s own reference alone does not stop it, so without
322/// this guard the forwarder keeps the local port bound indefinitely after the
323/// `SrtSocket` is dropped, and a later attempt to bind that same port fails
324/// with `AddrInUse` (item 3). `None` for a listener-accepted connection,
325/// which has no per-connection forwarder to abort.
326struct TaskGuard(Option<tokio::task::JoinHandle<()>>);
327
328impl Drop for TaskGuard {
329    fn drop(&mut self) {
330        if let Some(handle) = self.0.take() {
331            handle.abort();
332        }
333    }
334}
335
336/// Capacity of a per-connection inbound-datagram channel (the dedicated
337/// forwarder for a [`SrtSocket::connect`]ed caller, or a [`SrtListener`]'s
338/// per-accepted-connection route) — bounded so a peer that floods faster than
339/// the driver task's tick loop can drain does not grow this queue (and this
340/// process's memory) without bound; excess datagrams are dropped, not
341/// buffered (item 4).
342const RX_CHANNEL_CAPACITY: usize = 4096;
343/// Capacity of a [`SrtListener`]'s candidate-new-connection queue (datagrams
344/// the routing pump could not match to any accepted connection). Bounded for
345/// the same reason as [`RX_CHANNEL_CAPACITY`] — a handshake flood must not
346/// grow this queue without bound even though [`MAX_PENDING`] already caps how
347/// many of those candidates get to hold engine state.
348const UNROUTED_CHANNEL_CAPACITY: usize = 1024;
349/// Capacity of the delivered-payload channel from a connection's driver task
350/// to its [`SrtSocket`] handle. Bounded so a slow/stalled application that
351/// never calls [`SrtSocket::recv`] cannot make TSBPD-released payloads pile
352/// up in memory without bound purely from network input — matching this
353/// adapter's live (TLPKTDROP) delivery philosophy of dropping rather than
354/// buffering forever (when TLPKTDROP was negotiated, §4.6).
355const DELIVER_CHANNEL_CAPACITY: usize = 4096;
356/// Capacity of the application-to-driver payload channel
357/// ([`SrtSocket::send`]). Bounded so the application is paced by the driver
358/// instead of queueing without limit; the driver additionally stops draining
359/// it while the sender holds a full flow window of unacknowledged packets
360/// (see `Driver::send_window_open`).
361const SEND_CHANNEL_CAPACITY: usize = 1024;
362
363/// Floor on how soon [`Driver::poll_timeout`] may ask to be woken: never a
364/// deadline in the past, and a 1 ms minimum cannot spin (it matches tokio's
365/// timer granularity).
366const MIN_WAKE: Duration = Duration::from_millis(1);
367/// Most DATA packets one `flush_outbound` pass sends, and the most pacing
368/// periods of catch-up credit a late wake may claim: with the ~1 ms timer
369/// granularity (`MIN_WAKE`) this lifts the idle-backlog drain ceiling from
370/// ~1000 packets/s to `PACING_BURST_CAP` x 1000 packets/s without ever
371/// dumping more than this many packets at once.
372const PACING_BURST_CAP: usize = 16;
373/// Initial TSBPD drift (zero: the scheduler estimates it from there).
374const DEFAULT_DRIFT_US: i64 = 0;
375/// Default max bandwidth (1 Gbps).
376const DEFAULT_MAX_BW: MaxBwConfig = MaxBwConfig::Set(125_000_000);
377/// How often an unanswered handshake request is re-sent. libsrt re-sends its
378/// handshake request every 250 ms until it is answered; the previous 15 s
379/// (three five-second receive timeouts) made one lost INDUCTION cost the
380/// whole connect budget.
381const HANDSHAKE_RETRANSMIT_PERIOD: Duration = Duration::from_millis(250);
382/// Keep-Alive period (`draft-sharabayko-srt-01` §3.2.3: "The default timeout
383/// for a keep-alive packet to be sent is 1 second", measured from the last
384/// time any packet — control or data — was sent).
385const KEEPALIVE_PERIOD: Duration = Duration::from_secs(1);
386/// How often an unconfirmed refresh KMREQ is re-sent until its KMRSP arrives
387/// (`private/specs-verified/ietf/specs/ietf_draft_sharabayko_srt_01.txt`
388/// §6.1.6; the interval is this crate's choice).
389#[cfg(feature = "crypto")]
390const KM_RESEND_INTERVAL: Duration = Duration::from_millis(500);
391/// Shortest interval between two peer Key Material messages this driver
392/// processes. Recovering the SEK runs a 2048-iteration PBKDF2; a peer that
393/// re-sends KMREQ back to back would otherwise spend a core on it (#2840).
394/// The interval is this crate's choice — `private/specs-verified/rules/srt-crypto.md`
395/// §6.1.6 fixes the KM Refresh *packet-count* periods, not a time limit on
396/// inbound requests.
397#[cfg(feature = "crypto")]
398const KMREQ_MIN_INTERVAL: Duration = Duration::from_millis(100);
399/// SEK length used when the connection's own key length is unknown: AES-128.
400#[cfg(feature = "crypto")]
401const DEFAULT_SEK_LEN: usize = 16;
402/// Upper bound on concurrently in-progress listener handshakes. Every new
403/// source address that sends an INDUCTION allocates a [`PendingListener`]
404/// entry; without a cap, a flood of (possibly spoofed) handshake packets from
405/// many sources exhausts memory before any of them times out.
406const MAX_PENDING: usize = 1024;
407/// How often [`SrtListener::accept`] drives pending-handshake expiry and
408/// retransmits, independent of receive activity.
409const PENDING_TICK_INTERVAL: Duration = Duration::from_millis(100);
410/// How often the SYN-cookie key is replaced (§4.3.1.1 buckets the cookie's
411/// time input to one minute).
412const COOKIE_KEY_ROTATION: Duration = Duration::from_secs(60);
413/// How long an accepted connection's CONCLUSION response is remembered so a
414/// repeated CONCLUSION (the response was lost) can be answered again — a
415/// little longer than the Caller's own default connect budget ([`IoConfig::handshake`]).
416const RECENT_ACCEPT_TTL: Duration = Duration::from_secs(10);
417/// Cap on remembered CONCLUSION responses (one per recently accepted source
418/// address), the same bound as [`MAX_PENDING`].
419const MAX_RECENT_ACCEPTS: usize = MAX_PENDING;
420
421// ===========================================================================
422// Outbound queue
423// ===========================================================================
424//
425// Two separate queues, not one queue tagged per-item: §5.1.2 paces DATA
426// packets only — ACK/NAK/ACKACK/Keep-Alive control feedback must never be
427// throttled behind the pacing delay, or loss recovery (which rides on that
428// same control traffic) stalls along with it. A single FIFO queue with an
429// `is_data` tag on each item got this half right (pacing never delayed a
430// control packet that had already reached the *front*) but not the other
431// half: `flush_outbound` stopped at the first not-yet-due DATA packet and
432// never looked past it, so a control packet enqueued *behind* one — the
433// common case, since `tick_engines` queues retransmits before this cycle's
434// ACK/NAK — sat there just as throttled as if pacing applied to it too. Two
435// queues make that structurally impossible: control is always drained in
436// full before data pacing is even considered.
437
438/// One queued outbound DATA datagram. `retransmit` names the sequence number
439/// when the datagram is a retransmission, so the sender's "already queued"
440/// mark is cleared when the datagram leaves this queue (#2819).
441#[derive(Debug)]
442struct OutboundData {
443    bytes: Vec<u8>,
444    retransmit: Option<u32>,
445}
446
447impl OutboundData {
448    /// A first transmission (never a retransmission).
449    fn first_transmission(bytes: Vec<u8>) -> Self {
450        Self {
451            bytes,
452            retransmit: None,
453        }
454    }
455}
456
457/// Per-connection counters for datagrams a bounded internal channel dropped
458/// because it was full (item 4) — this adapter's own internal backpressure,
459/// distinct from wire-level loss ARQ/TLPKTDROP already account for. Shared
460/// (via `Arc`) between a [`Driver`] and the [`SrtSocket`] handle so
461/// [`SrtSocket::stats`] reads live counts, not a snapshot frozen at spawn.
462#[derive(Debug, Default)]
463struct Counters {
464    rx_dropped: AtomicU64,
465    deliver_dropped: AtomicU64,
466    late_dropped: AtomicU64,
467    too_late_dropped: AtomicU64,
468    rx_oversize: AtomicU64,
469}
470
471/// A snapshot of one connection's `Counters`, returned by
472/// [`SrtSocket::stats`].
473#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
474#[non_exhaustive]
475pub struct SocketStats {
476    /// Inbound datagrams dropped because the per-connection ingress channel
477    /// was full (the peer sent faster than this connection's driver task
478    /// could drain).
479    pub rx_dropped: u64,
480    /// TSBPD-released payloads dropped because the application wasn't
481    /// calling [`SrtSocket::recv`] fast enough to keep the delivery channel
482    /// from filling.
483    pub deliver_dropped: u64,
484    /// DATA packets ignored because they were not ahead of the delivery
485    /// cursor: duplicates, retransmissions of what was already delivered or
486    /// given up on, and stale sequence numbers (never staged).
487    pub late_dropped: u64,
488    /// Sequence numbers the TSBPD scheduler gave up on: packets that arrived
489    /// after their play time by more than the too-late threshold, and gaps
490    /// skipped as unrecoverable when the next buffered packet reached its
491    /// play time (§4.6, too-late packet drop). Each one is a delivered
492    /// stream's payload that no retransmission can recover.
493    pub too_late_dropped: u64,
494    /// Datagrams larger than [`IoConfig::max_datagram`], dropped rather than
495    /// truncated.
496    pub rx_oversize: u64,
497}
498
499// ===========================================================================
500// SrtSocket — a handle to an established SRT connection
501// ===========================================================================
502
503/// What [`SrtSocket::spawn`] needs to build one connection's engines and
504/// driver task.
505struct ConnParams {
506    udp: Arc<UdpSocket>,
507    peer_addr: std::net::SocketAddr,
508    rx: mpsc::Receiver<Bytes>,
509    stats: Arc<Counters>,
510    route_cleanup: RouteCleanup,
511    forwarder_guard: TaskGuard,
512    /// For a listener-accepted connection: keeps the listener's tasks (and so
513    /// its socket) alive for as long as this connection is.
514    life: Option<Arc<ListenerLife>>,
515    /// [`IoConfig::read_idle`] for this connection.
516    read_idle: Duration,
517    /// [`IoConfig::write`] for this connection.
518    write: Duration,
519    our_initial_seq: u32,
520    peer_initial_seq: u32,
521    peer_socket_id: u32,
522    /// `TsbpdTimeBase` (§4.5.1.1, rule 12): `T_NOW - HSREQ_TIMESTAMP`, with
523    /// `T_NOW` measured from `epoch` — so `-(the peer's handshake timestamp)`
524    /// when `epoch` is the instant that handshake packet arrived.
525    tsbpd_time_base: i64,
526    /// The negotiated TSBPD delay ([`NegotiatedParams::latency`]).
527    tsbpd_delay: Duration,
528    epoch: Instant,
529    /// The negotiated Maximum Flow Window Size (§3.2.1): the smaller of the
530    /// two sides' values.
531    max_flow_window: u32,
532    /// The negotiated MTU (§3.2.1): the smaller of the two sides' values.
533    mtu: u32,
534    /// Whether Too-Late Packet Drop was negotiated (the `TLPKTDROP` flag both
535    /// sides advertised, §3.2.1.1.1): only then may the receiver skip a gap.
536    tlpkt_drop: bool,
537    /// Opt-in §6 payload-encryption state recovered from the handshake
538    /// (crypto feature only). `None` on every field when encryption was not
539    /// negotiated, and the connection runs in plaintext.
540    #[cfg(feature = "crypto")]
541    crypto_passphrase: Vec<u8>,
542    #[cfg(feature = "crypto")]
543    crypto_salt: Option<[u8; crate::crypto::SALT_LEN]>,
544    #[cfg(feature = "crypto")]
545    crypto_even_sek: Option<Vec<u8>>,
546    #[cfg(feature = "crypto")]
547    crypto_thresholds: crate::km_refresh::KmRefreshThresholds,
548}
549
550/// A handle to an established SRT connection over UDP.
551///
552/// Created by [`SrtSocket::connect`] (caller role) or
553/// [`SrtListener::accept`] (listener role). The protocol itself runs on a
554/// background [`tokio`] task the handle owns; [`send`](Self::send) enqueues an
555/// application payload and [`recv`](Self::recv) awaits a delivered one.
556/// Dropping the handle sends the peer a SHUTDOWN (§3.2.7) and aborts the
557/// driver task.
558#[derive(Debug)]
559pub struct SrtSocket {
560    peer_addr: std::net::SocketAddr,
561    /// Application payloads flowing to the driver task for transmission.
562    to_driver: mpsc::Sender<Bytes>,
563    /// TSBPD/ARQ-delivered payloads flowing back from the driver task.
564    from_driver: mpsc::Receiver<Bytes>,
565    /// The driver task; aborted on drop.
566    driver: Option<tokio::task::JoinHandle<()>>,
567    stats: Arc<Counters>,
568    /// The connection's socket, kept to send the SHUTDOWN from `Drop`.
569    udp: Arc<UdpSocket>,
570    /// The peer's SRT Socket ID — the SHUTDOWN's Destination Socket ID.
571    peer_socket_id: u32,
572    /// The connection epoch, for the SHUTDOWN's wire timestamp.
573    epoch: Instant,
574    /// Keeps a listener's background tasks alive while this accepted
575    /// connection is; `None` for a [`connect`](Self::connect)ed caller.
576    /// Declared last so it drops after the SHUTDOWN in `Drop`.
577    _life: Option<Arc<ListenerLife>>,
578}
579
580impl SrtSocket {
581    /// Connect to a remote SRT peer as a Caller.
582    ///
583    /// # Encryption
584    /// With `crypto` set in the [`HandshakeConfig`], the adapter negotiates
585    /// keys in the handshake and encrypts outgoing / decrypts incoming data
586    /// packets (AES-CTR, draft section 6) on this connection.
587    ///
588    /// # Errors
589    /// [`Error::Rejected`] carries the peer's [`RejectionReason`];
590    /// [`Error::HandshakeTimedOut`] means the peer never answered within the
591    /// handshake budget; [`Error::Handshake`] wraps an engine failure with the
592    /// stage it happened in.
593    pub async fn connect<A: tokio::net::ToSocketAddrs>(
594        remote_addr: A,
595        config: SrtSocketConfig,
596    ) -> Result<Self> {
597        let local = std::net::SocketAddr::from(([0, 0, 0, 0], 0));
598        Self::connect_from(local, remote_addr, config).await
599    }
600
601    /// Connect from a specific local address.
602    ///
603    /// # Encryption
604    /// Like [`Self::connect`], negotiates and applies payload encryption when
605    /// `crypto` is set in the [`HandshakeConfig`].
606    pub async fn connect_from<A: tokio::net::ToSocketAddrs>(
607        local_addr: std::net::SocketAddr,
608        remote_addr: A,
609        config: SrtSocketConfig,
610    ) -> Result<Self> {
611        let socket = bounded(config.io.timeouts.connect, "bind", async {
612            UdpSocket::bind(local_addr)
613                .await
614                .map_err(|e| io_err("bind", e))
615        })
616        .await?;
617        Self::connect_from_socket(socket, remote_addr, config).await
618    }
619
620    /// Like [`Self::connect_from`], but takes an already-bound UDP socket
621    /// instead of binding one. The socket's own local address is used as the
622    /// connection's local endpoint, which lets a caller hold the port from
623    /// bind to use and avoid a bind/read/drop/rebind race.
624    ///
625    /// # Errors
626    /// Same as [`Self::connect_from`].
627    pub async fn connect_from_socket<A: tokio::net::ToSocketAddrs>(
628        socket: tokio::net::UdpSocket,
629        remote_addr: A,
630        config: SrtSocketConfig,
631    ) -> Result<Self> {
632        let SrtSocketConfig {
633            handshake: config,
634            io,
635        } = config;
636        let max_datagram = io.max_datagram.clamp(MIN_MAX_DATAGRAM, MAX_MAX_DATAGRAM);
637        let peer = bounded(io.timeouts.connect, "resolve", resolve_one(remote_addr)).await?;
638        let socket = Arc::new(socket);
639
640        // Both this Caller's own Socket ID and its ISN must be freshly
641        // generated per connection, not carried over from `config` (whose
642        // `initial_seq_number` a caller may leave at its `0` default) —
643        // `draft-sharabayko-srt-01` §3/§4.3.1.1 expects both random, and a
644        // fixed or predictable pair lets an off-path party that knows the
645        // 4-tuple guess a live connection's wire identifiers outright.
646        let own_socket_id = random_socket_id()?;
647        let mut config = config;
648        config.initial_seq_number = random_isn()?;
649        let mut hs = CallerHandshake::new(own_socket_id, config.clone());
650
651        let epoch = Instant::now();
652        hs.set_elapsed(epoch.elapsed());
653        let induction = hs.start().map_err(|e| handshake_err("caller start", e))?;
654        send_bounded(
655            &socket,
656            &induction,
657            peer,
658            io.timeouts.write,
659            "send induction",
660        )
661        .await?;
662
663        // Re-send an unanswered request every `HANDSHAKE_RETRANSMIT_PERIOD`
664        // (each tick hands the engine its own elapsed time), and give up at
665        // `IoConfig::handshake` whatever the retry budget says.
666        let tick_period = HANDSHAKE_RETRANSMIT_PERIOD;
667        let mut ticker = tokio::time::interval_at(Instant::now() + tick_period, tick_period);
668        ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
669        let deadline = Instant::now() + io.timeouts.handshake;
670        let mut scratch = vec![0u8; max_datagram + 1];
671        // The handshake loop has no `SocketStats` yet; oversize datagrams are
672        // simply ignored (the real peer retransmits).
673        let hs_oversize = AtomicU64::new(0);
674
675        loop {
676            enum Event {
677                Datagram(Bytes, std::net::SocketAddr),
678                Oversize,
679                Tick,
680                Deadline,
681            }
682            let event = tokio::select! {
683                r = recv_datagram(&socket, &mut scratch, max_datagram, &hs_oversize) => {
684                    match r.map_err(|e| io_err("recv hs", e))? {
685                        Some((bytes, src)) => Event::Datagram(bytes, src),
686                        None => Event::Oversize,
687                    }
688                }
689                _ = ticker.tick() => Event::Tick,
690                _ = tokio::time::sleep_until(deadline) => Event::Deadline,
691            };
692
693            let (outputs, received) = match event {
694                Event::Deadline => {
695                    return Err(Error::HandshakeTimedOut {
696                        stage: "caller connect",
697                    });
698                }
699                Event::Oversize => continue,
700                Event::Tick => {
701                    hs.set_elapsed(epoch.elapsed());
702                    (hs.tick(tick_period), None)
703                }
704                Event::Datagram(bytes, src) => {
705                    // A packet from anyone but the peer we're connecting to
706                    // (some unrelated traffic that happened to land on this
707                    // freshly bound port) must not fail the connect — ignore
708                    // it and keep waiting for the real peer.
709                    if src != peer {
710                        continue;
711                    }
712                    // Likewise, a packet that isn't a well-formed Handshake
713                    // control packet right now (a stray Keep-Alive, a
714                    // resent/duplicate reply, garbage) must not fail the
715                    // connect either — only a genuine handshake rejection or
716                    // timeout does that.
717                    hs.set_elapsed(epoch.elapsed());
718                    let Ok(outputs) = hs.feed_bytes(&bytes) else {
719                        continue;
720                    };
721                    (outputs, Some(bytes))
722                }
723            };
724
725            for outcome in outputs {
726                match outcome {
727                    HandshakeOutput::Send(bytes) => {
728                        send_bounded(&socket, &bytes, peer, io.timeouts.write, "send hs").await?;
729                    }
730                    HandshakeOutput::Connected(params) => {
731                        // `Connected` only ever comes out of `feed_bytes`, so
732                        // the datagram that completed the handshake is still
733                        // in `buf`. The peer's ISN (seeds ARQ/TSBPD sequence
734                        // tracking) and handshake timestamp (seeds the TSBPD
735                        // time base, rule 12) are carried in those bytes; the
736                        // peer's SRT Socket ID (the wire `dest_socket_id`
737                        // for every outgoing packet) is the negotiated
738                        // `params.peer_socket_id` — the two ids are unrelated
739                        // values (§3).
740                        //
741                        // `peer_handshake` errors (rather than defaulting to
742                        // 0) if the very bytes that just drove the handshake
743                        // state machine to `Connected` fail to re-parse as a
744                        // Handshake control packet — an internal
745                        // inconsistency. A silent `0` fallback would be
746                        // indistinguishable from a genuine ISN of 0 and would
747                        // seed ARQ/TSBPD sequence tracking wrong for the life
748                        // of the connection.
749                        let received = received.ok_or(Error::InvalidField(InvalidField {
750                            field: "handshake",
751                            reason: "Connected without a received datagram",
752                        }))?;
753                        let peer_hs = peer_handshake(&received)?;
754                        return Ok(Self::established(
755                            socket,
756                            peer,
757                            config.initial_seq_number,
758                            &params,
759                            peer_hs,
760                            epoch,
761                            max_datagram,
762                            &io,
763                            #[cfg(feature = "crypto")]
764                            config
765                                .crypto
766                                .as_ref()
767                                .map(|c| c.passphrase.clone())
768                                .unwrap_or_default(),
769                        ));
770                    }
771                    HandshakeOutput::Rejected(reason) => return Err(Error::Rejected(reason)),
772                    HandshakeOutput::TimedOut => {
773                        return Err(Error::HandshakeTimedOut {
774                            stage: "caller retransmit budget",
775                        });
776                    }
777                }
778            }
779        }
780    }
781
782    /// Wire up a connected socket from a completed handshake (Caller or
783    /// Rendezvous): a dedicated-socket forwarder feeding the same
784    /// `Driver::rx` path a listener-accepted connection uses (issue #1029),
785    /// seeded from the peer's ISN and handshake timestamp (TSBPD rule 12).
786    fn established(
787        socket: Arc<UdpSocket>,
788        peer: std::net::SocketAddr,
789        our_initial_seq: u32,
790        params: &handshake_sm::NegotiatedParams,
791        peer_hs: PeerHandshake,
792        epoch: Instant,
793        max_datagram: usize,
794        io: &IoConfig,
795        #[cfg(feature = "crypto")] passphrase: Vec<u8>,
796    ) -> SrtSocket {
797        // This socket is exclusively this connection's own (bound fresh by
798        // the connect/rendezvous call, never shared) - no demux table needed.
799        let stats = Arc::new(Counters::default());
800        let (rx, forwarder) = spawn_dedicated_socket_forwarder(
801            Arc::clone(&socket),
802            peer,
803            Arc::clone(&stats),
804            max_datagram,
805        );
806        SrtSocket::spawn(ConnParams {
807            udp: socket,
808            peer_addr: peer,
809            rx,
810            stats,
811            route_cleanup: RouteCleanup(None),
812            forwarder_guard: TaskGuard(Some(forwarder)),
813            life: None,
814            read_idle: io.timeouts.read_idle,
815            write: io.timeouts.write,
816            our_initial_seq,
817            peer_initial_seq: peer_hs.initial_seq_number,
818            peer_socket_id: params.peer_socket_id,
819            tsbpd_time_base: tsbpd_time_base_at(epoch, Instant::now(), peer_hs.timestamp_us),
820            tsbpd_delay: params.latency,
821            epoch,
822            max_flow_window: params.max_flow_window_size,
823            mtu: params.mtu,
824            tlpkt_drop: params.flags.tlpktdrop(),
825            #[cfg(feature = "crypto")]
826            crypto_passphrase: passphrase,
827            #[cfg(feature = "crypto")]
828            crypto_salt: params.salt,
829            #[cfg(feature = "crypto")]
830            crypto_even_sek: params.sek.as_ref().map(|s| s.to_vec()),
831            #[cfg(feature = "crypto")]
832            crypto_thresholds: io.km_refresh_thresholds,
833        })
834    }
835
836    /// Establish a connection with a peer in **Rendezvous** mode
837    /// (`draft-sharabayko-srt-01` §4.3.2): both sides bind a known local port
838    /// and send to each other's address at the same time, so neither is
839    /// Caller or Listener; the cookie contest picks Initiator / Responder.
840    /// Runs the sans-IO [`crate::rendezvous::RendezvousHandshake`] over a UDP
841    /// socket bound to `local_addr` (its port must be the one the peer targets).
842    ///
843    /// # Errors
844    /// [`Error::Rejected`] carries the peer's [`RejectionReason`];
845    /// [`Error::HandshakeTimedOut`] means the peer never completed the
846    /// exchange within the handshake budget.
847    pub async fn rendezvous<A: tokio::net::ToSocketAddrs>(
848        local_addr: std::net::SocketAddr,
849        remote_addr: A,
850        config: SrtSocketConfig,
851    ) -> Result<Self> {
852        let socket = bounded(config.io.timeouts.connect, "bind", async {
853            UdpSocket::bind(local_addr)
854                .await
855                .map_err(|e| io_err("bind", e))
856        })
857        .await?;
858        Self::rendezvous_from_socket(socket, remote_addr, config).await
859    }
860
861    /// Like [`Self::rendezvous`], but takes an already-bound UDP socket
862    /// instead of binding one. The socket's own local address is used as the
863    /// connection's local endpoint, which lets a caller hold the port from
864    /// bind to use and avoid a bind/read/drop/rebind race.
865    ///
866    /// # Errors
867    /// Same as [`Self::rendezvous`].
868    pub async fn rendezvous_from_socket<A: tokio::net::ToSocketAddrs>(
869        socket: tokio::net::UdpSocket,
870        remote_addr: A,
871        config: SrtSocketConfig,
872    ) -> Result<Self> {
873        let SrtSocketConfig {
874            handshake: config,
875            io,
876        } = config;
877        let max_datagram = io.max_datagram.clamp(MIN_MAX_DATAGRAM, MAX_MAX_DATAGRAM);
878        let peer = bounded(io.timeouts.connect, "resolve", resolve_one(remote_addr)).await?;
879        let socket = Arc::new(socket);
880
881        // Fresh per-connection Socket ID, ISN and cookie (a zero cookie is
882        // never drawn: it is the "no cookie yet" value on the wire).
883        let own_socket_id = random_socket_id()?;
884        let mut config = config;
885        config.initial_seq_number = random_isn()?;
886        let mut own_cookie = random_u32()?;
887        while own_cookie == 0 {
888            own_cookie = random_u32()?;
889        }
890        let mut hs =
891            crate::rendezvous::RendezvousHandshake::new(own_socket_id, own_cookie, config.clone());
892        let epoch = Instant::now();
893        hs.set_elapsed(epoch.elapsed());
894        let first = hs
895            .start()
896            .map_err(|e| handshake_err("rendezvous start", e))?;
897        send_bounded(&socket, &first, peer, io.timeouts.write, "send waveahand").await?;
898
899        let tick_period = HANDSHAKE_RETRANSMIT_PERIOD;
900        let mut ticker = tokio::time::interval_at(Instant::now() + tick_period, tick_period);
901        ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
902        let deadline = Instant::now() + io.timeouts.handshake;
903        let mut scratch = vec![0u8; max_datagram + 1];
904        let hs_oversize = AtomicU64::new(0);
905        // The newest Handshake packet the peer sent: every one carries the
906        // peer's ISN, and the freshest timestamp seeds the TSBPD time base.
907        // (A Responder promoted to Connected by a data packet, recovery
908        // rule 3, completes on a non-handshake datagram.)
909        let mut last_peer_hs: Option<PeerHandshake> = None;
910
911        loop {
912            enum Event {
913                Datagram(Bytes, std::net::SocketAddr),
914                Oversize,
915                Tick,
916                Deadline,
917            }
918            let event = tokio::select! {
919                r = recv_datagram(&socket, &mut scratch, max_datagram, &hs_oversize) => {
920                    match r.map_err(|e| io_err("recv hs", e))? {
921                        Some((bytes, src)) => Event::Datagram(bytes, src),
922                        None => Event::Oversize,
923                    }
924                }
925                _ = ticker.tick() => Event::Tick,
926                _ = tokio::time::sleep_until(deadline) => Event::Deadline,
927            };
928
929            let outputs = match event {
930                Event::Deadline => {
931                    return Err(Error::HandshakeTimedOut {
932                        stage: "rendezvous connect",
933                    });
934                }
935                Event::Oversize => continue,
936                Event::Tick => {
937                    hs.set_elapsed(epoch.elapsed());
938                    hs.tick(tick_period)
939                }
940                Event::Datagram(bytes, src) => {
941                    if src != peer {
942                        continue;
943                    }
944                    hs.set_elapsed(epoch.elapsed());
945                    match SrtPacket::parse(&bytes) {
946                        Ok(SrtPacket::Control(ControlPacket::Handshake(hp))) => {
947                            last_peer_hs = Some(PeerHandshake {
948                                initial_seq_number: hp.initial_seq_number,
949                                timestamp_us: hp.timestamp.value(),
950                            });
951                            match hs.feed_bytes(&bytes) {
952                                Ok(o) => o,
953                                Err(_) => continue,
954                            }
955                        }
956                        // A data packet before we are Connected: missing-
957                        // packet recovery rule 3 (a Responder stuck in
958                        // Initiated is promoted; anything else is a no-op).
959                        Ok(SrtPacket::Data(_)) => match hs.on_recovery_trigger() {
960                            Ok(o) => o,
961                            Err(_) => continue,
962                        },
963                        // Any other control packet is fed straight to the
964                        // engine, which applies the same recovery rule.
965                        Ok(SrtPacket::Control(c)) => match hs.feed(&c) {
966                            Ok(o) => o,
967                            Err(_) => continue,
968                        },
969                        Err(_) => continue,
970                    }
971                }
972            };
973
974            for outcome in outputs {
975                match outcome {
976                    HandshakeOutput::Send(bytes) => {
977                        send_bounded(&socket, &bytes, peer, io.timeouts.write, "send hs").await?;
978                    }
979                    HandshakeOutput::Connected(params) => {
980                        let peer_hs = last_peer_hs.ok_or(Error::InvalidField(InvalidField {
981                            field: "handshake",
982                            reason: "Connected without having received a peer Handshake packet",
983                        }))?;
984                        return Ok(Self::established(
985                            socket,
986                            peer,
987                            config.initial_seq_number,
988                            &params,
989                            peer_hs,
990                            epoch,
991                            max_datagram,
992                            &io,
993                            #[cfg(feature = "crypto")]
994                            config
995                                .crypto
996                                .as_ref()
997                                .map(|c| c.passphrase.clone())
998                                .unwrap_or_default(),
999                        ));
1000                    }
1001                    HandshakeOutput::Rejected(reason) => return Err(Error::Rejected(reason)),
1002                    HandshakeOutput::TimedOut => {
1003                        return Err(Error::HandshakeTimedOut {
1004                            stage: "rendezvous retransmit budget",
1005                        });
1006                    }
1007                }
1008            }
1009        }
1010    }
1011
1012    /// Build the engine state, spawn its background driver task, and return
1013    /// the [`SrtSocket`] handle wired to it.
1014    fn spawn(p: ConnParams) -> Self {
1015        let (to_driver, app_out) = mpsc::channel::<Bytes>(SEND_CHANNEL_CAPACITY);
1016        let (deliver, from_driver) = mpsc::channel(DELIVER_CHANNEL_CAPACITY);
1017
1018        let udp = Arc::clone(&p.udp);
1019        let (peer_addr, peer_socket_id, epoch) = (p.peer_addr, p.peer_socket_id, p.epoch);
1020        let stats = Arc::clone(&p.stats);
1021        let life = p.life.clone();
1022        let driver = Driver::new(p, deliver);
1023        let handle = tokio::spawn(driver.run(app_out));
1024
1025        SrtSocket {
1026            peer_addr,
1027            to_driver,
1028            from_driver,
1029            driver: Some(handle),
1030            stats,
1031            udp,
1032            peer_socket_id,
1033            epoch,
1034            _life: life,
1035        }
1036    }
1037
1038    /// Enqueue a payload for transmission to the peer.
1039    ///
1040    /// Returns once the payload is handed to the driver task — actual
1041    /// transmission, ACK/NAK handling, and retransmission all happen on that
1042    /// task. Waits (applying backpressure) while the sender already holds a
1043    /// full flow window of unacknowledged packets or the hand-off queue is
1044    /// full. Fails only if the driver task has stopped (peer shut down, went
1045    /// silent, or a connection error).
1046    pub async fn send(&mut self, payload: &[u8]) -> Result<()> {
1047        self.send_bytes(Bytes::copy_from_slice(payload)).await
1048    }
1049
1050    /// Like [`send`](Self::send) but takes ownership of an already-built
1051    /// [`Bytes`], so the hand-off to the driver task does not copy it.
1052    pub async fn send_bytes(&mut self, payload: Bytes) -> Result<()> {
1053        self.to_driver.send(payload).await.map_err(|_| Error::Io {
1054            kind: std::io::ErrorKind::BrokenPipe,
1055            context: "send",
1056        })
1057    }
1058
1059    /// The peer's socket address.
1060    pub fn peer_addr(&self) -> std::net::SocketAddr {
1061        self.peer_addr
1062    }
1063
1064    /// Receive the next payload, waiting until one is available.
1065    /// Returns `None` once the peer has shut down (or the driver task has
1066    /// stopped) and no further payloads will arrive.
1067    pub async fn recv(&mut self) -> Result<Option<Bytes>> {
1068        Ok(self.from_driver.recv().await)
1069    }
1070
1071    /// A snapshot of this connection's internal-backpressure drop counters
1072    /// (item 4) — datagrams or delivered payloads this adapter's own bounded
1073    /// channels dropped because they were full, not wire-level loss.
1074    pub fn stats(&self) -> SocketStats {
1075        SocketStats {
1076            rx_dropped: self.stats.rx_dropped.load(Ordering::Relaxed),
1077            deliver_dropped: self.stats.deliver_dropped.load(Ordering::Relaxed),
1078            late_dropped: self.stats.late_dropped.load(Ordering::Relaxed),
1079            too_late_dropped: self.stats.too_late_dropped.load(Ordering::Relaxed),
1080            rx_oversize: self.stats.rx_oversize.load(Ordering::Relaxed),
1081        }
1082    }
1083}
1084
1085impl Drop for SrtSocket {
1086    fn drop(&mut self) {
1087        if let Some(handle) = self.driver.take() {
1088            // Tell a still-connected peer we are leaving (§3.2.7) so it can
1089            // close at once instead of waiting out its idle timeout. Not when
1090            // the driver already ended: the peer shut down (or went silent)
1091            // and has nothing left to be told.
1092            if !handle.is_finished() {
1093                let timestamp =
1094                    crate::packet::SrtTimestamp::from_wire(crate::arq::duration_to_wire_us(
1095                        Instant::now().saturating_duration_since(self.epoch),
1096                    ));
1097                send_shutdown(&self.udp, self.peer_addr, self.peer_socket_id, timestamp);
1098            }
1099            handle.abort();
1100        }
1101    }
1102}
1103
1104/// The SHUTDOWN datagram (§3.2.7) for a peer.
1105fn shutdown_datagram(
1106    peer_socket_id: u32,
1107    timestamp: crate::packet::SrtTimestamp,
1108) -> Option<Vec<u8>> {
1109    let pkt = ControlPacket::Shutdown(ShutdownPacket {
1110        timestamp,
1111        dest_socket_id: crate::packet::SocketId::from_wire(peer_socket_id),
1112        libsrt_pad: true,
1113    });
1114    let mut buf = vec![0u8; pkt.serialized_len()];
1115    pkt.serialize_into(&mut buf).ok()?;
1116    Some(buf)
1117}
1118
1119/// Best-effort, non-blocking SHUTDOWN (§3.2.7) to `peer`, for `Drop`, where
1120/// nothing can be awaited. A failure (socket buffer full, peer unreachable, or
1121/// a socket that was never polled for writability) is ignored: the peer's idle
1122/// timeout is the fallback.
1123fn send_shutdown(
1124    udp: &UdpSocket,
1125    peer: std::net::SocketAddr,
1126    peer_socket_id: u32,
1127    timestamp: crate::packet::SrtTimestamp,
1128) {
1129    if let Some(buf) = shutdown_datagram(peer_socket_id, timestamp) {
1130        let _ = udp.try_send_to(&buf, peer);
1131    }
1132}
1133
1134// ===========================================================================
1135// Driver — the per-connection background task
1136// ===========================================================================
1137
1138/// One packet held by the receive staging buffer until TSBPD releases it: the
1139/// whole datagram, header included. Keeping the datagram's own allocation —
1140/// rather than copying the payload out of it — means a received packet is
1141/// copied once (socket buffer to this `Vec`) and then handed to the
1142/// application with the header drained off the front, never copied into a
1143/// second allocation.
1144type StagedDatagram = Bytes;
1145
1146#[cfg(feature = "crypto")]
1147type SekSlot = Option<(zeroize::Zeroizing<Vec<u8>>, [u8; crate::crypto::SALT_LEN])>;
1148
1149/// The even/odd SEKs (with their Salts) of ONE direction. A connection holds
1150/// two: `tx_keys` for what this side encrypts with (generated by this side's
1151/// own KM Refresh) and `rx_keys` for what it decrypts with (installed from the
1152/// peer's Key Material), because each side rotates its own SEKs
1153/// (`private/specs-verified/ietf/specs/ietf_draft_sharabayko_srt_01.txt`
1154/// §6.1.6).
1155#[cfg(feature = "crypto")]
1156#[derive(Default)]
1157struct KeySet {
1158    even: SekSlot,
1159    odd: SekSlot,
1160}
1161
1162#[cfg(feature = "crypto")]
1163impl KeySet {
1164    fn initial(sek: Option<&[u8]>, salt: Option<[u8; crate::crypto::SALT_LEN]>) -> Self {
1165        let mut keys = KeySet::default();
1166        if let (Some(sek), Some(salt)) = (sek, salt) {
1167            keys.install(KeyParity::Even, sek.to_vec(), salt);
1168        }
1169        keys
1170    }
1171
1172    fn slot(&self, parity: KeyParity) -> &SekSlot {
1173        match parity {
1174            KeyParity::Even => &self.even,
1175            KeyParity::Odd => &self.odd,
1176        }
1177    }
1178
1179    fn slot_mut(&mut self, parity: KeyParity) -> &mut SekSlot {
1180        match parity {
1181            KeyParity::Even => &mut self.even,
1182            KeyParity::Odd => &mut self.odd,
1183        }
1184    }
1185
1186    fn get(&self, parity: KeyParity) -> Option<(&[u8], [u8; crate::crypto::SALT_LEN])> {
1187        self.slot(parity)
1188            .as_ref()
1189            .map(|(sek, salt)| (sek.as_slice(), *salt))
1190    }
1191
1192    fn install(&mut self, parity: KeyParity, sek: Vec<u8>, salt: [u8; crate::crypto::SALT_LEN]) {
1193        *self.slot_mut(parity) = Some((zeroize::Zeroizing::new(sek), salt));
1194    }
1195
1196    fn clear(&mut self, parity: KeyParity) {
1197        *self.slot_mut(parity) = None;
1198    }
1199
1200    fn is_empty(&self) -> bool {
1201        self.even.is_none() && self.odd.is_none()
1202    }
1203}
1204
1205/// A KMREQ announcing a refreshed SEK that the peer has not yet confirmed with
1206/// a KMRSP; re-sent every [`KM_RESEND_INTERVAL`] until it is.
1207#[cfg(feature = "crypto")]
1208struct PendingKm {
1209    parity: KeyParity,
1210    salt: [u8; crate::crypto::SALT_LEN],
1211    datagram: Vec<u8>,
1212    resend_at: Instant,
1213}
1214
1215#[cfg(feature = "crypto")]
1216fn parity_of_kk(kk: crate::packet::KmKeyFlag) -> Option<KeyParity> {
1217    match kk {
1218        crate::packet::KmKeyFlag::Even => Some(KeyParity::Even),
1219        crate::packet::KmKeyFlag::Odd => Some(KeyParity::Odd),
1220        _ => None,
1221    }
1222}
1223
1224#[cfg(feature = "crypto")]
1225fn parity_of_key_field(kf: EncryptionKeyField) -> Option<KeyParity> {
1226    match kf {
1227        EncryptionKeyField::Even => Some(KeyParity::Even),
1228        EncryptionKeyField::Odd => Some(KeyParity::Odd),
1229        _ => None,
1230    }
1231}
1232
1233#[cfg(feature = "crypto")]
1234fn key_field_of(parity: KeyParity) -> EncryptionKeyField {
1235    match parity {
1236        KeyParity::Even => EncryptionKeyField::Even,
1237        KeyParity::Odd => EncryptionKeyField::Odd,
1238    }
1239}
1240
1241/// The engine state driven by one connection's background task. Owns the
1242/// socket, the sans-IO ARQ/TSBPD/LiveCC engines, and the outbound queue; runs
1243/// the RX / app-send / next-deadline select loop in [`Driver::run`].
1244struct Driver {
1245    udp: Arc<UdpSocket>,
1246    peer_addr: std::net::SocketAddr,
1247    peer_socket_id: u32,
1248    /// Shared with the [`SrtSocket`] handle (for [`SrtSocket::stats`]) and
1249    /// whichever task feeds `rx` (the dedicated forwarder, or the listener's
1250    /// routing pump via its `RouteEntry`), so a drop on either side of that
1251    /// channel is counted in the one place the application can read it.
1252    stats: Arc<Counters>,
1253
1254    // Inbound datagrams for *this* connection only (issue #1029). Fed by
1255    // exactly one upstream demultiplexer: a per-connection forwarder task
1256    // reading a dedicated socket ([`SrtSocket::connect_from`]), or the
1257    // [`SrtListener`]'s single shared-socket routing pump. Never
1258    // `udp.recv_from` directly — that would race every other task reading
1259    // the same socket for whichever datagram arrives next, handing some of
1260    // this connection's own traffic to a different connection (or the
1261    // listener's own accept loop) at random. Bounded (item 4): a peer that
1262    // floods faster than this task's tick loop drains gets its excess
1263    // datagrams dropped, not buffered without bound.
1264    rx: mpsc::Receiver<Bytes>,
1265    // For a listener-accepted connection: removes this connection's entry
1266    // from the shared route table on drop — including on `SrtSocket::Drop`'s
1267    // task abort, not only a normal `run()` return (see [`RouteCleanup`]).
1268    // Holds `None` for a `SrtSocket::connect`ed connection (no shared table).
1269    _route_cleanup: RouteCleanup,
1270    // For a `SrtSocket::connect`ed connection: aborts the dedicated-socket
1271    // forwarder task on drop, so it stops holding the local UDP port open
1272    // (see [`TaskGuard`]). `None` for a listener-accepted connection (no
1273    // per-connection forwarder — the listener's routing pump outlives it).
1274    _forwarder_guard: TaskGuard,
1275    // Absolute time the last datagram (of any kind, valid or not) was
1276    // received from the peer — the basis for the peer-idle timeout below.
1277    last_rx_at: Instant,
1278    // Absolute time the last datagram of any kind was sent to the peer — the
1279    // basis for the Keep-Alive timer (§3.2.3).
1280    last_tx_at: Instant,
1281
1282    // ARQ
1283    sender: ArqSender,
1284    receiver: ArqReceiver,
1285
1286    // TSBPD
1287    tsbpd: TsbpdScheduler,
1288
1289    // LiveCC pacing
1290    livecc: LiveCC,
1291
1292    next_message_number: u32,
1293    next_send_seq: u32,
1294
1295    // Wall-clock epoch for `now: Timestamp`.
1296    epoch: Instant,
1297
1298    // Staging: seq → received datagram, released to `deliver` by TSBPD/ARQ.
1299    staged: std::collections::BTreeMap<u32, StagedDatagram>,
1300
1301    // Negotiated maximum flow window (§3.2.1): the cap on how far ahead of
1302    // the delivery cursor a packet may be staged, and on how many
1303    // unacknowledged packets the sender may hold.
1304    max_flow_window: u32,
1305
1306    /// §6 payload-encryption state (crypto feature only). `None` salts/SEKs
1307    /// mean the connection is plaintext.
1308    #[cfg(feature = "crypto")]
1309    crypto_passphrase: zeroize::Zeroizing<alloc::vec::Vec<u8>>,
1310    #[cfg(feature = "crypto")]
1311    tx_keys: KeySet,
1312    #[cfg(feature = "crypto")]
1313    rx_keys: KeySet,
1314    #[cfg(feature = "crypto")]
1315    tx_parity: KeyParity,
1316    #[cfg(feature = "crypto")]
1317    km_pending: Option<PendingKm>,
1318    #[cfg(feature = "crypto")]
1319    retire_deferred: Option<KeyParity>,
1320    #[cfg(feature = "crypto")]
1321    crypto_key_len: usize,
1322    #[cfg(feature = "crypto")]
1323    km_refresh: crate::km_refresh::KmRefreshDriver,
1324    /// The last KEK derived from a peer Key Material message, so a repeated
1325    /// KMREQ with the same `(Salt, KLen)` does not rerun PBKDF2 (#2840).
1326    #[cfg(feature = "crypto")]
1327    kek_cache: crate::crypto::KekCache,
1328    /// When the peer's most recent KMREQ was processed, so a peer cannot burn
1329    /// a core by re-sending Key Material (#2840, `KMREQ_MIN_INTERVAL`).
1330    #[cfg(feature = "crypto")]
1331    last_peer_kmreq_at: Option<Instant>,
1332
1333    // Outbound datagram queues — separate so control can never queue behind
1334    // a not-yet-due paced DATA packet (see the module doc above).
1335    outbound_data: VecDeque<OutboundData>,
1336    outbound_control: VecDeque<Vec<u8>>,
1337
1338    // Token-bucket pacing schedule (issue #1061): the earliest time the next
1339    // DATA packet may go out. `None` means no DATA packet is currently
1340    // pacing-blocked (the queue is empty of DATA, or was last drained with
1341    // room to spare). Advanced by `LiveCC::on_ack_received()`'s period each
1342    // time a DATA packet is actually sent, *from whichever is later of the
1343    // previous schedule slot or now* — so a burst that arrives after this
1344    // connection was otherwise idle (RX/tick-bound) sends immediately
1345    // instead of being penalized for the gap, while a sustained flood is
1346    // still throttled to the configured rate. This replaces a real
1347    // `tokio::time::sleep` per DATA packet in `flush_outbound`, which — even
1348    // at a sub-millisecond computed period — actually blocked for
1349    // tokio's real timer resolution (>= ~1 ms), capping throughput at
1350    // roughly 1000 pkt/s regardless of the configured MAX_BW, and blocked
1351    // the same `run()` iteration's RX processing while it slept.
1352    next_data_send_at: Option<Instant>,
1353
1354    // Delivered payloads flowing back to the application handle. Bounded
1355    // (item 4): see [`DELIVER_CHANNEL_CAPACITY`].
1356    deliver: mpsc::Sender<Bytes>,
1357
1358    peer_shutdown: bool,
1359
1360    /// Longest silence from the peer before the connection ends
1361    /// ([`IoConfig::read_idle`]).
1362    read_idle: Duration,
1363    /// Longest a single `send_to` may take ([`IoConfig::write`]).
1364    write_timeout: Duration,
1365
1366    /// Test hook: counts `tick_engines` calls, so a test can prove the run
1367    /// loop wakes at deadlines rather than on a fixed tick.
1368    #[cfg(test)]
1369    tick_counter: Option<Arc<AtomicU64>>,
1370}
1371
1372impl Driver {
1373    fn new(p: ConnParams, deliver: mpsc::Sender<Bytes>) -> Self {
1374        let now = Instant::now();
1375        Driver {
1376            udp: p.udp,
1377            peer_addr: p.peer_addr,
1378            peer_socket_id: p.peer_socket_id,
1379            stats: p.stats,
1380            rx: p.rx,
1381            _route_cleanup: p.route_cleanup,
1382            _forwarder_guard: p.forwarder_guard,
1383            last_rx_at: now,
1384            last_tx_at: now,
1385            // `dest_socket_id` on every outgoing DATA/ACKACK/NAK/ACK packet
1386            // must be the peer's negotiated SRT Socket ID, not its ISN — the
1387            // two are unrelated values (§3).
1388            sender: ArqSender::new(p.peer_socket_id),
1389            receiver: ArqReceiver::new(p.peer_socket_id, p.peer_initial_seq, p.max_flow_window)
1390                .with_mtu(p.mtu),
1391            tsbpd: TsbpdScheduler::new(
1392                p.peer_initial_seq,
1393                p.tsbpd_time_base,
1394                p.tsbpd_delay,
1395                DEFAULT_DRIFT_US,
1396                p.tlpkt_drop,
1397                None,
1398            ),
1399            livecc: LiveCC::new(DEFAULT_MAX_BW),
1400            next_message_number: 1,
1401            next_send_seq: p.our_initial_seq,
1402            epoch: p.epoch,
1403            staged: std::collections::BTreeMap::new(),
1404            max_flow_window: p.max_flow_window,
1405            #[cfg(feature = "crypto")]
1406            crypto_passphrase: zeroize::Zeroizing::new(p.crypto_passphrase.clone()),
1407            #[cfg(feature = "crypto")]
1408            tx_keys: KeySet::initial(p.crypto_even_sek.as_deref(), p.crypto_salt),
1409            #[cfg(feature = "crypto")]
1410            rx_keys: KeySet::initial(p.crypto_even_sek.as_deref(), p.crypto_salt),
1411            #[cfg(feature = "crypto")]
1412            tx_parity: KeyParity::Even,
1413            #[cfg(feature = "crypto")]
1414            km_pending: None,
1415            #[cfg(feature = "crypto")]
1416            retire_deferred: None,
1417            #[cfg(feature = "crypto")]
1418            crypto_key_len: p
1419                .crypto_even_sek
1420                .as_ref()
1421                .map(|v| v.len())
1422                .or_else(|| p.crypto_salt.map(|_| DEFAULT_SEK_LEN))
1423                .unwrap_or(0),
1424            #[cfg(feature = "crypto")]
1425            km_refresh: crate::km_refresh::KmRefreshDriver::new(
1426                p.crypto_thresholds,
1427                crate::km_refresh::KeyParity::Even,
1428            ),
1429            #[cfg(feature = "crypto")]
1430            kek_cache: crate::crypto::KekCache::new(),
1431            #[cfg(feature = "crypto")]
1432            last_peer_kmreq_at: None,
1433            outbound_data: VecDeque::new(),
1434            outbound_control: VecDeque::new(),
1435            next_data_send_at: None,
1436            deliver,
1437            peer_shutdown: false,
1438            read_idle: p.read_idle,
1439            write_timeout: p.write,
1440            #[cfg(test)]
1441            tick_counter: None,
1442        }
1443    }
1444
1445    /// The next instant at which this connection must act without any inbound
1446    /// event: the next Full ACK / NAK, the next TSBPD release (or too-late
1447    /// skip), the Keep-Alive when idle, the peer-idle expiry and the next
1448    /// pacing slot. Never in the past (floored at [`MIN_WAKE`]).
1449    fn poll_timeout(&self) -> Option<Instant> {
1450        let now = self.elapsed();
1451        // Full ACK / NAK. A deadline past the end of the clock never fires, so
1452        // it is simply not one of the wake-ups folded in below.
1453        let mut at = self
1454            .receiver
1455            .next_timeout()
1456            .map(|t| self.epoch + Duration::from_micros(t.as_micros()));
1457        // TSBPD release / TLPKTDROP skip.
1458        if let Some(t) = self.tsbpd.next_release_after(now) {
1459            at = Some(match at {
1460                Some(a) => a.min(self.epoch + t),
1461                None => self.epoch + t,
1462            });
1463        }
1464        // Keep-Alive (only judged when nothing is queued).
1465        if self.outbound_control.is_empty() && self.outbound_data.is_empty() {
1466            at = Some(match at {
1467                Some(a) => a.min(self.last_tx_at + KEEPALIVE_PERIOD),
1468                None => self.last_tx_at + KEEPALIVE_PERIOD,
1469            });
1470        }
1471        #[cfg(feature = "crypto")]
1472        if let Some(pending) = &self.km_pending {
1473            at = Some(match at {
1474                Some(a) => a.min(pending.resend_at),
1475                None => pending.resend_at,
1476            });
1477        }
1478        // Peer idle.
1479        at = Some(match at {
1480            Some(a) => a.min(self.last_rx_at + self.read_idle),
1481            None => self.last_rx_at + self.read_idle,
1482        });
1483        // Pacing slot.
1484        if let Some(wait) = self.next_paced_send_wait() {
1485            at = Some(match at {
1486                Some(a) => a.min(Instant::now() + wait),
1487                None => Instant::now() + wait,
1488            });
1489        }
1490        at.map(|at| at.max(Instant::now() + MIN_WAKE))
1491    }
1492
1493    /// The select loop: socket RX, application-send, and a periodic engine
1494    /// tick — the tick arm is what keeps retransmit/ACK/NAK progressing when
1495    /// neither peer is actively sending application data.
1496    async fn run(mut self, mut app_out: mpsc::Receiver<Bytes>) {
1497        let mut app_open = true;
1498
1499        // Set when the application handle is gone (its `to_driver` sender was
1500        // dropped): the loop makes one final flush pass and then exits, so a
1501        // dropped [`SrtSocket`] does not leave a driver task parked forever on
1502        // the socket/timer arms — which would keep a current-thread runtime
1503        // from shutting down. (`SrtSocket::Drop` also aborts the task; this is
1504        // the cooperative path that does not rely on abort-during-shutdown.)
1505        let mut shutting_down = false;
1506
1507        loop {
1508            // The next instant this connection must act on its own (ACK/NAK,
1509            // TSBPD release, keep-alive, peer idle, pacing slot): the loop
1510            // sleeps until then or until an event, never on a fixed tick.
1511            let wake_at = self
1512                .poll_timeout()
1513                .unwrap_or_else(|| Instant::now() + KEEPALIVE_PERIOD);
1514            // Stop taking application payloads while a full flow window of
1515            // packets is still unacknowledged: the hand-off channel then
1516            // fills and `SrtSocket::send` waits, instead of the send buffer
1517            // growing without bound behind a stalled or dead peer.
1518            let accept_app_data = app_open && self.send_window_open();
1519
1520            tokio::select! {
1521                // Application handed us a payload to send.
1522                maybe = app_out.recv(), if accept_app_data => {
1523                    match maybe {
1524                        Some(payload) => self.send_one(&payload),
1525                        None => {
1526                            // Handle dropped its sender — no more app data
1527                            // will ever arrive. Stop polling this (now
1528                            // permanently `Ready(None)`) arm and tear down.
1529                            app_open = false;
1530                            shutting_down = true;
1531                        }
1532                    }
1533                }
1534                // A datagram for this connection, already demultiplexed by
1535                // the upstream forwarder/router (issue #1029) — never a
1536                // shared `udp.recv_from` racing another task for the same
1537                // socket.
1538                maybe = self.rx.recv() => {
1539                    match maybe {
1540                        Some(bytes) => {
1541                            // A malformed datagram is ignored, not fatal.
1542                            let _ = self.ingress(bytes);
1543                        }
1544                        None => break, // upstream demux/forwarder is gone.
1545                    }
1546                }
1547                // Deadline: retransmit, ACK, NAK, TSBPD release, keep-alive
1548                // and the pacing slot are all folded into `poll_timeout`.
1549                _ = tokio::time::sleep_until(wake_at) => {}
1550            }
1551
1552            // Timer-driven engine work runs after EVERY wake-up: it is a pure
1553            // function of `now`, so an inbound packet also gets its
1554            // ACK/NAK/TSBPD release without waiting for a tick.
1555            self.tick_engines();
1556
1557            if self.flush_outbound().await.is_err() {
1558                break;
1559            }
1560            if self.peer_idle(Instant::now()) {
1561                // libsrt's default `SRTO_PEERIDLETIMEO`: no packet at all
1562                // (not just DATA) from the peer for this long means the
1563                // connection is broken, not merely quiet — a live SRT peer
1564                // always sends at least periodic Keep-Alives.
1565                break;
1566            }
1567            if self.peer_shutdown || shutting_down {
1568                break;
1569            }
1570        }
1571        // A cooperative exit because *we* are leaving (not the peer's
1572        // SHUTDOWN, nor an idle peer, nor a socket error) tells the peer
1573        // (§3.2.7); `SrtSocket::drop` does the same for the abort path.
1574        if shutting_down
1575            && !self.peer_shutdown
1576            && let Some(buf) = shutdown_datagram(self.peer_socket_id, self.elapsed_us())
1577        {
1578            let _ = send_bounded(&self.udp, &buf, self.peer_addr, self.write_timeout, "send").await;
1579        }
1580        // The route-table and forwarder-task cleanup this used to do inline
1581        // now happens in `_route_cleanup`/`_forwarder_guard`'s `Drop` impls,
1582        // which run here too (falling off the end of this function drops
1583        // `self`) as well as on `SrtSocket::Drop`'s task abort — the case
1584        // this inline code used to miss entirely.
1585        //
1586        // Dropping `self.deliver` here closes the channel, so the handle's
1587        // `recv` returns `None` (clean shutdown / task ended).
1588    }
1589
1590    /// No packet at all has arrived from the peer for [`IoConfig::read_idle`].
1591    fn peer_idle(&self, now: Instant) -> bool {
1592        now.saturating_duration_since(self.last_rx_at) >= self.read_idle
1593    }
1594
1595    /// Room in the send window: fewer than a full flow window of packets are
1596    /// buffered unacknowledged (§3.2.1 Maximum Flow Window Size).
1597    fn send_window_open(&self) -> bool {
1598        let window = usize::try_from(self.max_flow_window)
1599            .unwrap_or(usize::MAX)
1600            .max(1);
1601        self.sender.buffered_count() < window
1602    }
1603
1604    #[cfg(feature = "crypto")]
1605    fn advance_key_refresh(&mut self) {
1606        if self.tx_keys.is_empty() {
1607            return;
1608        }
1609        for ev in self.km_refresh.on_packet_sent(1) {
1610            match ev {
1611                KmRefreshEvent::PreAnnounce { next_parity } => self.announce_key(next_parity),
1612                KmRefreshEvent::Switchover { .. } => {}
1613                KmRefreshEvent::Decommission { retired } => self.retire_deferred = Some(retired),
1614            }
1615        }
1616        if self.km_pending.is_none() {
1617            self.tx_parity = self.km_refresh.active_parity();
1618        }
1619        if let Some(retired) = self.retire_deferred
1620            && retired != self.tx_parity
1621        {
1622            self.tx_keys.clear(retired);
1623            self.retire_deferred = None;
1624        }
1625    }
1626
1627    #[cfg(feature = "crypto")]
1628    fn announce_key(&mut self, parity: KeyParity) {
1629        if self.km_pending.is_some() {
1630            return;
1631        }
1632        let key_len = if self.crypto_key_len == 0 {
1633            DEFAULT_SEK_LEN
1634        } else {
1635            self.crypto_key_len
1636        };
1637        let mut salt = [0u8; crate::crypto::SALT_LEN];
1638        let mut sek = vec![0u8; key_len];
1639        if getrandom::fill(&mut salt).is_err() || getrandom::fill(&mut sek).is_err() {
1640            return;
1641        }
1642        let Ok(kek) = crate::crypto::derive_kek(&self.crypto_passphrase, &salt, key_len) else {
1643            return;
1644        };
1645        let Ok((icv, wrapped)) = crate::crypto::wrap_sek(&kek, &sek) else {
1646            return;
1647        };
1648        let km = crate::packet::KeyMaterial {
1649            kk: match parity {
1650                KeyParity::Even => crate::packet::KmKeyFlag::Even,
1651                KeyParity::Odd => crate::packet::KmKeyFlag::Odd,
1652            },
1653            keki: 0,
1654            cipher: crate::packet::Cipher::AesCtr,
1655            auth: crate::packet::KmAuth::None,
1656            se: crate::packet::StreamEncapsulation::MpegTsSrt,
1657            salt: &salt,
1658            icv,
1659            x_sek: &wrapped,
1660            o_sek: None,
1661        };
1662        let Some(datagram) =
1663            self.key_material_datagram(crate::packet::handshake::EXT_TYPE_KMREQ, &km)
1664        else {
1665            return;
1666        };
1667        self.tx_keys.install(parity, sek, salt);
1668        self.outbound_control.push_back(datagram.clone());
1669        self.km_pending = Some(PendingKm {
1670            parity,
1671            salt,
1672            datagram,
1673            resend_at: Instant::now() + KM_RESEND_INTERVAL,
1674        });
1675    }
1676
1677    #[cfg(feature = "crypto")]
1678    fn key_material_datagram(
1679        &self,
1680        subtype: u16,
1681        km: &crate::packet::KeyMaterial<'_>,
1682    ) -> Option<Vec<u8>> {
1683        let mut cif = vec![0u8; km.serialized_len()];
1684        km.serialize_into(&mut cif).ok()?;
1685        let ud = ControlPacket::UserDefined(crate::packet::UserDefinedPacket {
1686            control_type: crate::packet::ControlType::UserDefined.to_bits(),
1687            subtype,
1688            type_specific_info: 0,
1689            timestamp: self.elapsed_us(),
1690            dest_socket_id: crate::packet::SocketId::from_wire(self.peer_socket_id),
1691            cif: &cif,
1692        });
1693        let mut out = vec![0u8; ud.serialized_len()];
1694        ud.serialize_into(&mut out).ok()?;
1695        Some(out)
1696    }
1697
1698    #[cfg(feature = "crypto")]
1699    fn resend_pending_km(&mut self) {
1700        let now = Instant::now();
1701        if let Some(pending) = &mut self.km_pending
1702            && now >= pending.resend_at
1703        {
1704            self.outbound_control.push_back(pending.datagram.clone());
1705            pending.resend_at = now + KM_RESEND_INTERVAL;
1706        }
1707    }
1708
1709    #[cfg(feature = "crypto")]
1710    fn on_peer_key_material(&mut self, subtype: u16, km: &crate::packet::KeyMaterial<'_>) {
1711        if subtype == crate::packet::handshake::EXT_TYPE_KMRSP {
1712            if let Some(pending) = &self.km_pending
1713                && parity_of_kk(km.kk) == Some(pending.parity)
1714                && km.salt == pending.salt
1715            {
1716                self.km_pending = None;
1717            }
1718            return;
1719        }
1720        if subtype != crate::packet::handshake::EXT_TYPE_KMREQ {
1721            return;
1722        }
1723        // Recovering the SEK runs PBKDF2; a peer re-sending Key Material
1724        // back to back is refused beyond one message per
1725        // `KMREQ_MIN_INTERVAL` (#2840). A legitimate refresh that lands
1726        // inside the window is retransmitted by the peer.
1727        let now = Instant::now();
1728        if self
1729            .last_peer_kmreq_at
1730            .is_some_and(|last| now.saturating_duration_since(last) < KMREQ_MIN_INTERVAL)
1731        {
1732            return;
1733        }
1734        self.last_peer_kmreq_at = Some(now);
1735        let installed = match km.kk {
1736            crate::packet::KmKeyFlag::Both => crate::handshake_sm::recover_both_seks(
1737                &self.crypto_passphrase,
1738                km,
1739                &mut self.kek_cache,
1740            )
1741            .map(|(even, odd, salt)| {
1742                self.rx_keys.install(KeyParity::Even, even.to_vec(), salt);
1743                self.rx_keys.install(KeyParity::Odd, odd.to_vec(), salt);
1744            })
1745            .is_ok(),
1746            kk => {
1747                let parity = if kk == crate::packet::KmKeyFlag::Odd {
1748                    KeyParity::Odd
1749                } else {
1750                    KeyParity::Even
1751                };
1752                crate::handshake_sm::recover_sek(&self.crypto_passphrase, km, &mut self.kek_cache)
1753                    .map(|(sek, salt)| self.rx_keys.install(parity, sek.to_vec(), salt))
1754                    .is_ok()
1755            }
1756        };
1757        if installed
1758            && let Some(rsp) =
1759                self.key_material_datagram(crate::packet::handshake::EXT_TYPE_KMRSP, km)
1760        {
1761            self.outbound_control.push_back(rsp);
1762        }
1763    }
1764
1765    fn send_one(&mut self, payload: &[u8]) {
1766        let now = self.elapsed();
1767        self.livecc
1768            .on_data_packet(u64::try_from(payload.len()).unwrap_or(u64::MAX));
1769
1770        #[cfg(feature = "crypto")]
1771        self.advance_key_refresh();
1772
1773        #[cfg(feature = "crypto")]
1774        let encrypted: Option<alloc::vec::Vec<u8>> = match self.tx_keys.get(self.tx_parity) {
1775            Some((sek, salt)) => {
1776                let mut enc = payload.to_vec();
1777                if crate::crypto::aes_ctr_apply(sek, &salt, self.next_send_seq, &mut enc).is_err() {
1778                    return;
1779                }
1780                Some(enc)
1781            }
1782            None => None,
1783        };
1784        #[cfg(feature = "crypto")]
1785        let key_flag = if encrypted.is_some() {
1786            key_field_of(self.tx_parity)
1787        } else {
1788            EncryptionKeyField::NotEncrypted
1789        };
1790        #[cfg(feature = "crypto")]
1791        let payload = encrypted.as_deref().unwrap_or(payload);
1792        #[cfg(not(feature = "crypto"))]
1793        let key_flag = EncryptionKeyField::NotEncrypted;
1794
1795        // The counters are kept within their wire widths below, so this cannot
1796        // be queued; if it ever were, the payload is dropped, not the task.
1797        let Ok(bytes) = self.sender.on_data_keyed(
1798            self.next_send_seq,
1799            self.next_message_number,
1800            payload,
1801            key_flag,
1802            now,
1803        ) else {
1804            return;
1805        };
1806        // Wrap at the wire field's own bit width ...
1807        self.next_send_seq = seq_next(self.next_send_seq);
1808        self.next_message_number = next_message_number(self.next_message_number);
1809        self.outbound_data
1810            .push_back(OutboundData::first_transmission(bytes));
1811    }
1812
1813    /// Process one datagram from the peer. Takes the datagram by value so a
1814    /// DATA packet's own allocation can be staged without a copy.
1815    fn ingress(&mut self, datagram: Bytes) -> Result<()> {
1816        // Any datagram from the peer — even one that fails to parse below —
1817        // is evidence the peer is still there, resetting the idle timeout.
1818        self.last_rx_at = Instant::now();
1819        let now = self.elapsed();
1820        match SrtPacket::parse(&datagram)? {
1821            SrtPacket::Data(d) => {
1822                let (seq_number, timestamp, key_flag) = (d.seq_number, d.timestamp, d.key_flag);
1823                self.ingress_data(datagram, seq_number, timestamp, key_flag, now);
1824            }
1825            SrtPacket::Control(c) => self.ingress_control(&c, now),
1826        }
1827        Ok(())
1828    }
1829
1830    fn ingress_data(
1831        &mut self,
1832        datagram: Bytes,
1833        seq_number: u32,
1834        timestamp: crate::packet::SrtTimestamp,
1835        key_flag: EncryptionKeyField,
1836        now: Timestamp,
1837    ) {
1838        // Decrypt an encrypted data packet in place before staging, using the
1839        // SEK named by its `KK` flag. A missing key (not yet unwrapped, or
1840        // already decommissioned) means the packet cannot be delivered and is
1841        // dropped — never surfaced as corrupt plaintext.
1842        let (datagram, _key_flag) = {
1843            #[cfg(feature = "crypto")]
1844            {
1845                if key_flag != EncryptionKeyField::NotEncrypted {
1846                    let keys = parity_of_key_field(key_flag).and_then(|p| self.rx_keys.get(p));
1847                    match keys {
1848                        Some((sek, salt)) => {
1849                            let mut bytes = datagram.to_vec();
1850                            if bytes.len() > SRT_HEADER_LEN
1851                                && crate::crypto::aes_ctr_apply(
1852                                    sek,
1853                                    &salt,
1854                                    seq_number,
1855                                    &mut bytes[SRT_HEADER_LEN..],
1856                                )
1857                                .is_err()
1858                            {
1859                                return;
1860                            }
1861                            (Bytes::from(bytes), EncryptionKeyField::NotEncrypted)
1862                        }
1863                        None => return,
1864                    }
1865                } else {
1866                    (datagram, key_flag)
1867                }
1868            }
1869            #[cfg(not(feature = "crypto"))]
1870            {
1871                if key_flag != EncryptionKeyField::NotEncrypted {
1872                    return;
1873                }
1874                (datagram, key_flag)
1875            }
1876        };
1877
1878        // The ARQ receiver drives *reliability* only: loss detection and the
1879        // resulting NAK (rules 4, 14) plus the ACK point. Application
1880        // delivery is the TSBPD scheduler's job — it is the single in-order
1881        // delivery authority (see below), so its `outcome.delivered` is
1882        // intentionally NOT used to deliver here. Running both cursors over
1883        // one `staged` map races them and reorders retransmitted packets.
1884        //
1885        // Flow-window overflow guard (§3.2.1): a packet further ahead of the
1886        // ack point than the negotiated maximum flow window can never be
1887        // released in this connection's lifetime — staging it would let an
1888        // unrecoverable gap grow memory without bound, so the receiver
1889        // an unsupported packet and nothing downstream sees it.
1890        //
1891        // A packet that is not ahead of the delivery cursor (a duplicate, a
1892        // retransmission of what was delivered or given up on, or an
1893        // attacker-chosen stale number with a future timestamp) has nothing
1894        // left to do: TSBPD would ignore it and nothing would ever remove it
1895        // from `staged`, so it is never staged at all.
1896        if seq_lt(seq_number, self.tsbpd.next_release()) {
1897            self.stats.late_dropped.fetch_add(1, Ordering::Relaxed);
1898            return;
1899        }
1900        let outcome = self.receiver.feed_data(seq_number, now);
1901        if outcome.out_of_window {
1902            return;
1903        }
1904        if let Some(nak_bytes) = outcome.nak {
1905            self.outbound_control.push_back(nak_bytes);
1906        }
1907
1908        self.staged.entry(seq_number).or_insert(datagram);
1909
1910        // TSBPD is the sole delivery cursor: it releases packets in strict
1911        // sequence order, waiting for a NAK-recovered gap to be filled —
1912        // until the next available packet reaches its play time, at which
1913        // point live mode skips the unrecoverable gap and delivers that
1914        // packet (only if TLPKTDROP was negotiated, §3.2.1.1.1; otherwise it waits for the
1915        // retransmission, and the ARQ ack point never moves past the gap).
1916        let tsbpd_out = self.tsbpd.feed_data(seq_number, timestamp.value(), now);
1917        self.release(&tsbpd_out);
1918    }
1919
1920    fn ingress_control(&mut self, c: &ControlPacket<'_>, now: Timestamp) {
1921        match c {
1922            ControlPacket::Ack(ack) => {
1923                if let Some(ackack_bytes) = self.sender.on_ack(ack, now) {
1924                    self.outbound_control.push_back(ackack_bytes);
1925                }
1926            }
1927            ControlPacket::Nak(nak) => {
1928                // Record the reported loss; the next `tick_engines`
1929                // (or this cycle's, if a tick fired) drains the
1930                // retransmit queue — retransmits are queued ahead of any
1931                // new first-time data (rules 5, 15, 16).
1932                self.sender.on_nak(nak);
1933            }
1934            ControlPacket::AckAck(ackack) => {
1935                self.receiver.on_ackack(ackack, now);
1936            }
1937            ControlPacket::DropReq(d) => {
1938                self.handle_dropreq(d, now);
1939            }
1940            // A Keep-Alive only tells us the peer is alive (`last_rx_at` is
1941            // already refreshed): it is not answered. Echoing it made two of
1942            // these adapters bounce a Keep-Alive back and forth forever now
1943            // that an idle connection sends its own every second.
1944            ControlPacket::KeepAlive(_) => {}
1945            ControlPacket::Shutdown(_) => {
1946                self.peer_shutdown = true;
1947            }
1948            #[cfg(feature = "crypto")]
1949            ControlPacket::UserDefined(u) => {
1950                if let Ok(km) = u.as_key_material() {
1951                    self.on_peer_key_material(u.subtype, &km);
1952                }
1953            }
1954            _ => {}
1955        }
1956    }
1957
1958    /// Handle a DROPREQ (§3.2.9): the peer announces it will never deliver
1959    /// sequence numbers `first..=last`. Tell the ARQ receiver to stop NAKing
1960    /// them and advance its ack point, tell the TSBPD scheduler to skip them
1961    /// for delivery purposes, discard anything already staged inside the
1962    /// range (the sender has given up on the message they belonged to), then
1963    /// drive one release pass so whatever the gap was blocking becomes
1964    /// deliverable immediately.
1965    fn handle_dropreq(&mut self, d: &DropReqPacket, now: Timestamp) {
1966        let first = d.first_seq.value();
1967        let last = d.last_seq.value();
1968        if seq_diff(last, first) < 0 {
1969            // `last` precedes `first` — malformed range; nothing sane to skip.
1970            return;
1971        }
1972        let reach = seq_diff(last, self.receiver.ack_point());
1973        if !u32::try_from(reach).is_ok_and(|ahead| ahead <= self.max_flow_window) {
1974            return;
1975        }
1976        self.receiver.skip_range(first, last);
1977        self.tsbpd.skip_range(first, last);
1978        self.staged
1979            .retain(|&s, _| !seq_in_closed_range(s, first, last));
1980
1981        let tsbpd_out = self.tsbpd.tick(now);
1982        self.release(&tsbpd_out);
1983    }
1984
1985    /// Apply one TSBPD outcome to `staged` and the application channel:
1986    /// deliver the released payloads, and purge anything the scheduler dropped
1987    /// as too-late/skipped so a lost packet cannot leak its staged bytes.
1988    ///
1989    /// What the scheduler gave up on (§4.6) is also skipped in the ARQ
1990    /// receiver: its ack point then moves past the dropped packets — the
1991    /// "fake ACK" of Too-Late Packet Drop — so it stops NAKing packets that
1992    /// can no longer be delivered, the ACKs it sends let the peer free them,
1993    /// and the flow window it measures new arrivals against advances with the
1994    /// delivery cursor instead of stalling at the lost packet forever.
1995    fn release(&mut self, outcome: &TickOutcome) {
1996        for &seq in &outcome.delivered {
1997            if let Some(datagram) = self.staged.remove(&seq) {
1998                // The staged datagram is a DATA packet (it parsed as one):
1999                // hand over the payload as a view into the same allocation.
2000                let payload = datagram.slice(SRT_HEADER_LEN.min(datagram.len())..);
2001                if self.deliver.try_send(payload).is_err() {
2002                    // Full (app isn't calling `recv` fast enough) or the
2003                    // handle is gone; either way, drop rather than buffer
2004                    // without bound (item 4) and count it.
2005                    self.stats.deliver_dropped.fetch_add(1, Ordering::Relaxed);
2006                }
2007            }
2008        }
2009        for &seq in &outcome.dropped {
2010            self.staged.remove(&seq);
2011            self.stats.too_late_dropped.fetch_add(1, Ordering::Relaxed);
2012        }
2013        for (first, last) in contiguous_runs(&outcome.dropped) {
2014            self.receiver.skip_range(first, last);
2015        }
2016    }
2017
2018    fn tick_engines(&mut self) {
2019        #[cfg(test)]
2020        if let Some(counter) = &self.tick_counter {
2021            counter.fetch_add(1, Ordering::Relaxed);
2022        }
2023        let now = self.elapsed();
2024
2025        // Retransmitted DATA packets first (rules 5, 15, 16, 18): they are
2026        // drained from the NAK-populated loss list and queued *before* any
2027        // new first-time data appended later this cycle, reproducing the
2028        // sans-IO engine's "loss list before first transmission" priority
2029        // (see `arq::sender`'s module doc). Feed LiveCC the same as a
2030        // first-time send (`private/specs-verified/rules/srt-livecc.md` §5.1.2, L3216-3217:
2031        // "original or retransmitted") and tag them `is_data` so pacing
2032        // applies. The payload length is the datagram less its fixed header —
2033        // no need to re-parse the packet just to learn it.
2034        let queue_cap = usize::try_from(self.max_flow_window).unwrap_or(usize::MAX);
2035        for (seq, bytes) in self.sender.tick(now) {
2036            self.livecc.on_data_packet(
2037                u64::try_from(bytes.len().saturating_sub(SRT_HEADER_LEN)).unwrap_or(u64::MAX),
2038            );
2039            // Retransmissions are capped at the negotiated flow window: a
2040            // NAK naming the whole send buffer must not turn into an
2041            // unbounded queue (#2819). A dropped retransmission stays in the
2042            // sender's loss list and is offered again by a later tick.
2043            if self.outbound_data.len() < queue_cap {
2044                self.outbound_data.push_back(OutboundData {
2045                    bytes,
2046                    retransmit: Some(seq),
2047                });
2048            } else {
2049                self.sender.on_retransmit_dropped(seq);
2050            }
2051        }
2052
2053        // Keep-Alive (§3.2.3): a connection that has sent nothing for a
2054        // second says so, or the peer's own idle timeout ends it. Judged
2055        // before this tick's ACK/NAK are queued: it asks whether anything has
2056        // gone out for a second, not whether something is about to. (The
2057        // receiver's 10 ms Full ACK normally keeps `last_tx_at` fresh, so
2058        // this is the backstop for when it does not.)
2059        if self.outbound_control.is_empty()
2060            && self.outbound_data.is_empty()
2061            && Instant::now().saturating_duration_since(self.last_tx_at) >= KEEPALIVE_PERIOD
2062        {
2063            self.queue_keepalive();
2064        }
2065
2066        #[cfg(feature = "crypto")]
2067        self.resend_pending_km();
2068
2069        // Periodic ACK/NAK (rules 11, 12, 21, 22): control feedback, never
2070        // paced.
2071        for bytes in self.receiver.tick(now) {
2072            self.outbound_control.push_back(bytes);
2073        }
2074
2075        let tsbpd_out = self.tsbpd.tick(now);
2076        self.release(&tsbpd_out);
2077    }
2078
2079    fn queue_keepalive(&mut self) {
2080        let pkt = ControlPacket::KeepAlive(KeepAlivePacket {
2081            timestamp: self.elapsed_us(),
2082            dest_socket_id: crate::packet::SocketId::from_wire(self.peer_socket_id),
2083            libsrt_pad: true,
2084        });
2085        let mut buf = vec![0u8; pkt.serialized_len()];
2086        if pkt.serialize_into(&mut buf).is_ok() {
2087            self.outbound_control.push_back(buf);
2088        }
2089    }
2090
2091    fn elapsed(&self) -> Timestamp {
2092        let micros = u64::try_from(
2093            Instant::now()
2094                .saturating_duration_since(self.epoch)
2095                .as_micros(),
2096        )
2097        .unwrap_or(u64::MAX);
2098        Timestamp::from_micros(micros)
2099    }
2100
2101    /// The Keep-Alive/ACKACK/etc. control-packet wire `Timestamp` — wraps
2102    /// modulo `2^32` past ~71.58 minutes, matching `arq::timestamp_to_wire_us`
2103    /// (issue #1063; a clamp here made every control packet after that point
2104    /// carry the exact same wire timestamp forever).
2105    fn elapsed_us(&self) -> crate::packet::SrtTimestamp {
2106        crate::arq::timestamp_to_wire_us(self.elapsed())
2107    }
2108
2109    /// How long until the DATA packet at the front of the outbound data
2110    /// queue (if any) is next allowed to go out — `None` if there is nothing
2111    /// pacing-blocked right now (the data queue is empty, or its front
2112    /// packet's slot has already arrived). Drives the `run()` loop's pacing
2113    /// `select!` arm (issue #1061): by construction, `flush_outbound` always
2114    /// drains everything currently due before returning, so a `Some` here is
2115    /// always a genuine future deadline, never one already past. Never
2116    /// consults `outbound_control` — control is never pacing-blocked (item 6:
2117    /// two separate queues, not one tagged queue, so control can never queue
2118    /// behind a not-yet-due DATA packet either).
2119    fn next_paced_send_wait(&self) -> Option<Duration> {
2120        if self.outbound_data.is_empty() {
2121            return None;
2122        }
2123        let deadline = self.next_data_send_at?;
2124        Some(deadline.saturating_duration_since(Instant::now()))
2125    }
2126
2127    /// Send every outbound item that is due right now, in order, without
2128    /// blocking on the pacing delay itself (issue #1061).
2129    ///
2130    /// `private/specs-verified/rules/srt-livecc.md` §5.1.2: `PKT_SND_PERIOD` paces DATA
2131    /// packets only — control feedback (ACK/NAK/ACKACK/Keep-Alive) must go
2132    /// out immediately, or loss recovery (which rides on that same control
2133    /// traffic) would be throttled right along with the data it is meant to
2134    /// unblock.
2135    ///
2136    /// DATA packets are scheduled against `next_data_send_at`, a token-bucket
2137    /// style deadline rather than a per-packet `tokio::time::sleep`: a real
2138    /// sleep, even for a sub-millisecond computed period, actually blocks for
2139    /// tokio's real timer resolution (documented as coarse — at least
2140    /// roughly a millisecond on this host) — capping throughput at roughly
2141    /// 1000 pkt/s regardless of the configured `MAX_BW`, and (since the old
2142    /// code awaited it serially inside this function, called from every
2143    /// `run()` iteration) stalling RX/app-send processing for that same
2144    /// window. The schedule advances from whichever is later of the
2145    /// previous deadline or now, so a connection that was genuinely idle
2146    /// (or RX/tick-bound, not pacing-bound) for a while does not have to
2147    /// "pay back" that gap — it sends immediately and only then resumes
2148    /// pacing at the configured rate — while a sustained flood is still
2149    /// throttled to it.
2150    async fn flush_outbound(&mut self) -> Result<()> {
2151        // Control first, and all of it, unconditionally — never paced, and
2152        // (being its own queue) never stuck behind a not-yet-due DATA packet
2153        // either (item 6).
2154        while let Some(bytes) = self.outbound_control.pop_front() {
2155            send_bounded(
2156                &self.udp,
2157                &bytes,
2158                self.peer_addr,
2159                self.write_timeout,
2160                "send",
2161            )
2162            .await?;
2163            self.last_tx_at = Instant::now();
2164        }
2165        let mut sent = 0;
2166        while self.outbound_data.front().is_some() && sent < PACING_BURST_CAP {
2167            let now = Instant::now();
2168            if let Some(deadline) = self.next_data_send_at
2169                && now < deadline
2170            {
2171                // Not yet due — leave it (and everything behind it, to
2172                // preserve send order) queued for a later pass.
2173                break;
2174            }
2175            let Some(datagram) = self.outbound_data.pop_front() else {
2176                break;
2177            };
2178            if let Some(seq) = datagram.retransmit {
2179                self.sender.on_retransmit_sent(seq);
2180            }
2181            let period = self.livecc.on_ack_received();
2182            // Catch-up: a wake that arrives late (the timer has ~1 ms
2183            // granularity, `MIN_WAKE`) still owes the packets whose slots
2184            // passed meanwhile, so the schedule advances from the previous
2185            // slot even if it is already past — but never by more than
2186            // `PACING_BURST_CAP` periods of credit, so a stall cannot be
2187            // repaid as an unbounded burst.
2188            let floor = now
2189                .checked_sub(period * PACING_BURST_CAP as u32)
2190                .unwrap_or(now);
2191            let base = self.next_data_send_at.map_or(now, |t| t.max(floor));
2192            self.next_data_send_at = Some(base + period);
2193            sent += 1;
2194            send_bounded(
2195                &self.udp,
2196                &datagram.bytes,
2197                self.peer_addr,
2198                self.write_timeout,
2199                "send",
2200            )
2201            .await?;
2202            self.last_tx_at = Instant::now();
2203        }
2204        // An idle connection owes nothing: drop an expired slot so the next
2205        // backlog starts at "now" instead of replaying the idle gap as credit.
2206        if self.outbound_data.is_empty() {
2207            self.next_data_send_at = self.next_data_send_at.filter(|&t| t > Instant::now());
2208        }
2209        Ok(())
2210    }
2211}
2212
2213/// Spawn the forwarder task for a connection with its own **dedicated,
2214/// unshared** socket (a [`SrtSocket::connect`]ed caller): reads that socket
2215/// directly (no demux table needed — nothing else ever reads it) and
2216/// forwards only datagrams from `peer`, matching the filtering
2217/// `Driver::run`'s old direct-`recv_from` arm used to do inline (issue
2218/// #1029; see the module doc on [`SrtListener`] for the shared-socket case,
2219/// which needs actual demultiplexing, not just this filter).
2220///
2221/// Returns the receiver the [`Driver`] reads plus the task's own
2222/// [`tokio::task::JoinHandle`] — the caller must abort it (via
2223/// [`TaskGuard`]) once the connection ends, or this loop keeps the socket's
2224/// local port bound forever (item 3): dropping the `Driver`'s `Arc<UdpSocket>`
2225/// reference alone does not stop this task, which holds its own clone and
2226/// stays parked in `recv_from` waiting for a datagram that may never come.
2227fn spawn_dedicated_socket_forwarder(
2228    udp: Arc<UdpSocket>,
2229    peer: std::net::SocketAddr,
2230    stats: Arc<Counters>,
2231    max_datagram: usize,
2232) -> (mpsc::Receiver<Bytes>, tokio::task::JoinHandle<()>) {
2233    let (tx, rx) = mpsc::channel(RX_CHANNEL_CAPACITY);
2234    let handle = tokio::spawn(async move {
2235        let mut scratch = vec![0u8; max_datagram + 1];
2236        loop {
2237            match recv_datagram(&udp, &mut scratch, max_datagram, &stats.rx_oversize).await {
2238                Ok(Some((bytes, src))) if src == peer => {
2239                    if tx.try_send(bytes).is_err() {
2240                        if tx.is_closed() {
2241                            break; // Driver is gone.
2242                        }
2243                        // Full — the driver isn't draining fast enough; drop
2244                        // this datagram rather than buffer without bound
2245                        // (item 4) and count it.
2246                        stats.rx_dropped.fetch_add(1, Ordering::Relaxed);
2247                    }
2248                }
2249                Ok(_) => {} // datagram from another peer, or oversize (counted); ignore.
2250                Err(_) => break,
2251            }
2252        }
2253    });
2254    (rx, handle)
2255}
2256
2257// ===========================================================================
2258// SrtListener
2259// ===========================================================================
2260
2261/// An SRT listener that accepts incoming Caller connections.
2262///
2263/// # One socket, many connections (issue #1029)
2264///
2265/// Every connection this listener accepts shares its single bound socket —
2266/// unlike [`SrtSocket::connect`], which binds a fresh, unshared socket per
2267/// connection. `recv_from` on a shared socket delivers each datagram to
2268/// whichever waiting caller happens to be polled next, *not* whichever
2269/// caller the datagram is actually addressed to: if both this listener's own
2270/// `accept` loop and one or more accepted connections' driver tasks each
2271/// called `recv_from` on the same socket, a datagram belonging to one
2272/// connection could be handed to a completely different one (which would
2273/// then just discard it as foreign), silently losing it for its rightful
2274/// recipient. So exactly one task ever calls `recv_from` on `udp`: the
2275/// routing pump spawned once in [`SrtListener::bind`]. It demultiplexes the
2276/// way libsrt does (item 2, draft §4.3.1): a Destination Socket ID of `0`
2277/// (every handshake packet this crate's Caller ever sends, per the
2278/// `dest_socket_id` fix in `caller.rs`) always means "not yet an established
2279/// connection" and goes to `unrouted_rx` (`accept`'s own input); any other ID
2280/// must match an entry in `routes` *and* that entry's accepted source
2281/// address, or the datagram is dropped — a stray packet naming an ID that was
2282/// never accepted (or accepted from a different address) has nowhere
2283/// legitimate to go.
2284///
2285/// A repeated CONCLUSION from an already-accepted Caller (its copy of our
2286/// response was lost) carries Destination Socket ID `0` too, so it reaches
2287/// the listener's background task, which answers it again — no one has to be
2288/// polling [`accept`](Self::accept) for that.
2289///
2290/// # Lifetime (defect 3)
2291///
2292/// Handshakes advance in a tracked background task, not inside
2293/// [`accept`](Self::accept); the routing pump is a second tracked task. Both end
2294/// on a [`CancellationToken`], fired when the last of {this handle, every
2295/// accepted [`SrtSocket`]} is dropped — so an idle listener releases its UDP
2296/// port the moment the handle is dropped, while connections it already
2297/// accepted keep being routed until they too are gone.
2298pub struct SrtListener {
2299    /// Held only so its `Drop` (cancel the tasks) runs with the handle.
2300    _life: Arc<ListenerLife>,
2301    local: std::net::SocketAddr,
2302    accepted: mpsc::Receiver<Result<SrtSocket>>,
2303    /// Shared demux table (see [`RouteTable`]); the core and the routing pump
2304    /// hold the same `Arc`. Read by tests only.
2305    #[cfg(test)]
2306    routes: RouteTable,
2307    unrouted_dropped: Arc<AtomicU64>,
2308    overflow_dropped: Arc<AtomicU64>,
2309    send_errors: Arc<AtomicU64>,
2310}
2311
2312/// Capacity of the pending-`accept` queue: handshakes that finished while
2313/// `accept` was not being polled.
2314const ACCEPT_BACKLOG: usize = 64;
2315
2316/// Owns the listener's background tasks. Dropped when the last of the
2317/// [`SrtListener`] handle and every accepted [`SrtSocket`] is gone; that
2318/// cancels the tasks, which closes the UDP socket.
2319#[derive(Debug)]
2320struct ListenerLife {
2321    cancel: CancellationToken,
2322    tasks: TaskTracker,
2323}
2324
2325impl Drop for ListenerLife {
2326    fn drop(&mut self) {
2327        self.cancel.cancel();
2328        self.tasks.close();
2329    }
2330}
2331
2332/// The listener's handshake state, driven by one tracked background task
2333/// ([`ListenerCore::run`]).
2334struct ListenerCore {
2335    udp: Arc<UdpSocket>,
2336    config: HandshakeConfig,
2337    io: IoConfig,
2338    /// Per-listener 128-bit key for [`derive_cookie`] (`draft-sharabayko-srt-01`
2339    /// §4.3.1.1: "a cookie that is crafted based on host, port and current
2340    /// time"), drawn from the OS at [`SrtListener::bind`] and rotated every
2341    /// [`COOKIE_KEY_ROTATION`], so a cookie is neither shared across listeners
2342    /// nor valid for the life of the process.
2343    cookie_keys: CookieKeys,
2344    pending: std::collections::HashMap<std::net::SocketAddr, PendingListener>,
2345    outbound_queue: std::collections::HashMap<std::net::SocketAddr, VecDeque<Vec<u8>>>,
2346    /// CONCLUSION responses of recently accepted connections, by source
2347    /// address, so a repeated CONCLUSION can be answered again (see
2348    /// [`RecentAccept`]).
2349    recent_accepts: std::collections::HashMap<std::net::SocketAddr, RecentAccept>,
2350    /// Shared demux table the routing pump task consults for every inbound
2351    /// datagram; `drain_completed` registers a new entry for each freshly
2352    /// accepted connection.
2353    routes: RouteTable,
2354    /// Datagrams the routing pump could not match to any entry in `routes`
2355    /// — candidate new-connection (handshake) traffic. Bounded (item 4): see
2356    /// [`UNROUTED_CHANNEL_CAPACITY`].
2357    unrouted_rx: mpsc::Receiver<(std::net::SocketAddr, Bytes)>,
2358    /// Weak, so the core never keeps the listener alive: a connection is only
2359    /// handed over while a handle (or another connection) still holds the
2360    /// `Arc`.
2361    life: std::sync::Weak<ListenerLife>,
2362    /// Finished handshakes, for [`SrtListener::accept`].
2363    accepted_tx: mpsc::Sender<Result<SrtSocket>>,
2364    /// Connections dropped because `accepted_tx` was full.
2365    overflow_dropped: Arc<AtomicU64>,
2366    /// Send failures met while answering peers (counted, never queued: they
2367    /// must not compete with finished connections for `accepted_tx` slots).
2368    send_errors: Arc<AtomicU64>,
2369    /// `false` once the handle is gone: no new handshakes are served, but the
2370    /// task keeps draining `unrouted_rx` so the routing pump (which accepted
2371    /// connections still depend on) is never starved into exiting.
2372    accepting: bool,
2373    /// When `tick_pending` last ran: the basis of [`ListenerCore::poll_timeout`].
2374    last_pending_tick: Instant,
2375}
2376
2377/// The listener's SYN-cookie key and when it was drawn. A stateless INDUCTION
2378/// answer stores no per-peer cookie, so the CONCLUSION is validated against
2379/// the current key and the one it replaced: a handshake that began just
2380/// before a rotation still completes.
2381struct CookieKeys {
2382    current: u128,
2383    previous: Option<u128>,
2384    drawn_at: Instant,
2385}
2386
2387impl CookieKeys {
2388    fn new(now: Instant) -> Result<Self> {
2389        Ok(CookieKeys {
2390            current: random_u128()?,
2391            previous: None,
2392            drawn_at: now,
2393        })
2394    }
2395
2396    fn current(&self) -> u128 {
2397        self.current
2398    }
2399
2400    /// Every key a CONCLUSION-phase cookie may have been issued under: the
2401    /// current one and the one it replaced on the last rotation.
2402    fn acceptable(&self) -> impl Iterator<Item = u128> + '_ {
2403        core::iter::once(self.current).chain(self.previous)
2404    }
2405
2406    /// Replace the key once it is [`COOKIE_KEY_ROTATION`] old. Returns whether
2407    /// it did. A failing OS random source keeps the old key (and is retried on
2408    /// the next call) rather than ending the listener.
2409    fn rotate_if_due(&mut self, now: Instant) -> bool {
2410        if now.saturating_duration_since(self.drawn_at) < COOKIE_KEY_ROTATION {
2411            return false;
2412        }
2413        match random_u128() {
2414            Ok(key) => {
2415                self.previous = Some(self.current);
2416                self.current = key;
2417                self.drawn_at = now;
2418                true
2419            }
2420            Err(_) => false,
2421        }
2422    }
2423}
2424
2425impl core::fmt::Debug for CookieKeys {
2426    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
2427        f.debug_struct("CookieKeys")
2428            .field("current", &format_args!("<redacted>"))
2429            .field("drawn_at", &self.drawn_at)
2430            .finish()
2431    }
2432}
2433
2434impl core::fmt::Debug for ListenerCore {
2435    // Manual: the cookie key must never reach a log via `{:?}` (#1142).
2436    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
2437        f.debug_struct("ListenerCore")
2438            .field("local_addr", &self.udp.local_addr().ok())
2439            .field("cookie_keys", &self.cookie_keys)
2440            .field("pending", &self.pending.len())
2441            .field("recent_accepts", &self.recent_accepts.len())
2442            .finish_non_exhaustive()
2443    }
2444}
2445
2446impl core::fmt::Debug for SrtListener {
2447    // Manual: only the address — the cookie key lives in `ListenerCore`,
2448    // which is never printed from here (#1142).
2449    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
2450        f.debug_struct("SrtListener")
2451            .field("local_addr", &self.local)
2452            .finish_non_exhaustive()
2453    }
2454}
2455
2456#[derive(Debug)]
2457struct PendingListener {
2458    handshake: ListenerHandshake,
2459    params: Option<HandshakeOutput>,
2460    /// The peer's ISN, extracted from the INDUCTION handshake packet.
2461    peer_initial_seq: u32,
2462    /// The `Timestamp` of the peer's CONCLUSION, which seeds the TSBPD time
2463    /// base (§4.5.1.1: `TsbpdTimeBase = T_NOW - HSREQ_TIMESTAMP`).
2464    peer_timestamp_us: u32,
2465    /// When that CONCLUSION arrived: `T_NOW` of the same formula, hence the
2466    /// connection epoch (not the later moment `accept` happens to hand the
2467    /// connection over).
2468    concluded_at: Option<Instant>,
2469    /// When this entry was created: the instant the connection started, the
2470    /// epoch every handshake and data timestamp counts from.
2471    created_at: Instant,
2472    /// The last handshake datagram this entry produced — on completion, the
2473    /// CONCLUSION response a lost-response retransmit must be answered with.
2474    last_response: Option<Vec<u8>>,
2475    /// This listener's own ISN for this connection, generated once when the
2476    /// entry was created and echoed back here (rather than re-read from
2477    /// `self.config` at completion) so it is guaranteed to be the exact
2478    /// value the [`ListenerHandshake`] was constructed with — see
2479    /// [`SrtListener::handle_datagram`].
2480    our_initial_seq: u32,
2481}
2482
2483/// The CONCLUSION response of an accepted connection, kept for
2484/// [`RECENT_ACCEPT_TTL`] so that when the Caller repeats its CONCLUSION (our
2485/// response was lost, so it never saw the handshake finish) the identical
2486/// response is sent again — libsrt re-answers a repeated CONCLUSION the same
2487/// way. Without it the repeat reaches a listener that has already forgotten
2488/// the handshake, nothing is sent, and the Caller times out against a
2489/// connection the application is already using.
2490#[derive(Debug)]
2491struct RecentAccept {
2492    /// The Caller's SRT Socket ID — a repeat must carry the same one.
2493    peer_socket_id: u32,
2494    response: Vec<u8>,
2495    accepted_at: Instant,
2496}
2497
2498impl SrtListener {
2499    /// Bind an SRT listener on `addr`.
2500    ///
2501    /// # Encryption
2502    /// A listener configured without a passphrase rejects any peer that asks
2503    /// for encryption (a Key Material extension or a non-zero `Encryption
2504    /// Field`). A listener configured with one negotiates keys and encrypts /
2505    /// decrypts the data path.
2506    pub async fn bind<A: tokio::net::ToSocketAddrs>(
2507        addr: A,
2508        config: SrtSocketConfig,
2509    ) -> Result<Self> {
2510        let SrtSocketConfig {
2511            handshake: config,
2512            io,
2513        } = config;
2514        let socket = Arc::new(UdpSocket::bind(addr).await.map_err(|e| io_err("bind", e))?);
2515        let local = socket.local_addr().map_err(|e| io_err("local_addr", e))?;
2516        let routes: RouteTable = Arc::new(Mutex::new(std::collections::HashMap::new()));
2517        let (unrouted_tx, unrouted_rx) = mpsc::channel(UNROUTED_CHANNEL_CAPACITY);
2518        let (accepted_tx, accepted) = mpsc::channel(ACCEPT_BACKLOG);
2519        let unrouted_dropped = Arc::new(AtomicU64::new(0));
2520        let overflow_dropped = Arc::new(AtomicU64::new(0));
2521        let send_errors = Arc::new(AtomicU64::new(0));
2522        let life = Arc::new(ListenerLife {
2523            cancel: CancellationToken::new(),
2524            tasks: TaskTracker::new(),
2525        });
2526
2527        let core = ListenerCore {
2528            udp: Arc::clone(&socket),
2529            config,
2530            io,
2531            cookie_keys: CookieKeys::new(Instant::now())?,
2532            pending: std::collections::HashMap::new(),
2533            outbound_queue: std::collections::HashMap::new(),
2534            recent_accepts: std::collections::HashMap::new(),
2535            routes: Arc::clone(&routes),
2536            unrouted_rx,
2537            life: Arc::downgrade(&life),
2538            accepted_tx,
2539            overflow_dropped: Arc::clone(&overflow_dropped),
2540            send_errors: Arc::clone(&send_errors),
2541            accepting: true,
2542            last_pending_tick: Instant::now(),
2543        };
2544        life.tasks.spawn(routing_pump(
2545            Arc::clone(&socket),
2546            Arc::clone(&routes),
2547            unrouted_tx,
2548            Arc::clone(&unrouted_dropped),
2549            io.max_datagram.clamp(MIN_MAX_DATAGRAM, MAX_MAX_DATAGRAM),
2550            life.cancel.clone(),
2551        ));
2552        life.tasks.spawn(core.run(life.cancel.clone()));
2553        #[cfg(test)]
2554        let listener_routes = Arc::clone(&routes);
2555        #[cfg(test)]
2556        let _ = &listener_routes;
2557        Ok(SrtListener {
2558            _life: life,
2559            local,
2560            accepted,
2561            #[cfg(test)]
2562            routes: listener_routes,
2563            unrouted_dropped,
2564            overflow_dropped,
2565            send_errors,
2566        })
2567    }
2568
2569    /// Datagrams dropped because the candidate-new-connection queue was full
2570    /// (item 4) — a handshake flood outrunning the listener's handshake task —
2571    /// or because they exceeded [`IoConfig::max_datagram`].
2572    pub fn unrouted_dropped(&self) -> u64 {
2573        self.unrouted_dropped.load(Ordering::Relaxed)
2574    }
2575
2576    /// Connections that completed their handshake but were dropped because
2577    /// [`accept`](Self::accept) was not keeping up (the pending-accept queue
2578    /// holds 64); each dropped peer is sent a SHUTDOWN.
2579    pub fn accept_overflow_dropped(&self) -> u64 {
2580        self.overflow_dropped.load(Ordering::Relaxed)
2581    }
2582
2583    /// Send failures the background task met while answering peers (for
2584    /// example an unreachable spoofed source). They are counted here and never
2585    /// surface from [`accept`](Self::accept), so a flood of them cannot displace
2586    /// finished connections or end an `accept` loop.
2587    pub fn send_errors(&self) -> u64 {
2588        self.send_errors.load(Ordering::Relaxed)
2589    }
2590
2591    /// The local socket address the listener is bound to.
2592    pub fn local_addr(&self) -> Result<std::net::SocketAddr> {
2593        Ok(self.local)
2594    }
2595
2596    /// Accept the next incoming SRT connection.
2597    ///
2598    /// Handshakes progress in the background whether or not this is being
2599    /// polled; this only waits for a finished one. Send errors met while
2600    /// answering peers are counted ([`send_errors`](Self::send_errors)), not
2601    /// returned.
2602    pub async fn accept(&mut self) -> Result<SrtSocket> {
2603        self.accepted.recv().await.unwrap_or(Err(Error::Io {
2604            kind: std::io::ErrorKind::BrokenPipe,
2605            context: "listener task ended",
2606        }))
2607    }
2608}
2609
2610impl ListenerCore {
2611    /// Next instant a pending handshake needs a tick; `None` when nothing is
2612    /// pending (an idle listener has no timer at all).
2613    fn poll_timeout(&self) -> Option<Instant> {
2614        (self.accepting && !self.pending.is_empty())
2615            .then(|| self.last_pending_tick + PENDING_TICK_INTERVAL)
2616    }
2617
2618    /// The handshake task: answer unrouted datagrams, tick pending handshakes
2619    /// on a deadline, hand finished connections to [`SrtListener::accept`].
2620    async fn run(mut self, cancel: CancellationToken) {
2621        loop {
2622            while self.accepting
2623                && let Some(conn) = self.drain_completed()
2624            {
2625                match self.accepted_tx.try_send(conn) {
2626                    Ok(()) => {}
2627                    Err(mpsc::error::TrySendError::Full(_dropped)) => {
2628                        // Dropping the SrtSocket sends the peer a SHUTDOWN.
2629                        self.overflow_dropped.fetch_add(1, Ordering::Relaxed);
2630                    }
2631                    Err(mpsc::error::TrySendError::Closed(_)) => {
2632                        // The handle is gone but accepted connections may
2633                        // still be alive: stop serving new handshakes, keep
2634                        // draining so the routing pump keeps running.
2635                        self.accepting = false;
2636                        self.pending.clear();
2637                        self.outbound_queue.clear();
2638                    }
2639                }
2640            }
2641            let deadline = self.poll_timeout();
2642            tokio::select! {
2643                _ = cancel.cancelled() => return,
2644                r = self.unrouted_rx.recv() => match r {
2645                    Some((src, bytes)) => {
2646                        if !self.accepting {
2647                            continue;
2648                        }
2649                        // Cookie rotation no longer rides a tick: do it whenever a
2650                        // datagram arrives.
2651                        self.cookie_keys.rotate_if_due(Instant::now());
2652                        let _ = self.handle_datagram(src, &bytes);
2653                        // Raced against cancellation: a stuck send must not
2654                        // delay releasing the port by up to `io.timeouts.write`.
2655                        tokio::select! {
2656                            _ = cancel.cancelled() => return,
2657                            r = self.flush_for_peer(src) => self.count_send_error(r),
2658                        }
2659                    }
2660                    None => return,
2661                },
2662                _ = async {
2663                    match deadline {
2664                        Some(d) => tokio::time::sleep_until(d).await,
2665                        None => std::future::pending::<()>().await,
2666                    }
2667                } => {
2668                    self.last_pending_tick = Instant::now();
2669                    self.tick_pending();
2670                    tokio::select! {
2671                        _ = cancel.cancelled() => return,
2672                        r = self.flush_all() => self.count_send_error(r),
2673                    }
2674                }
2675            }
2676        }
2677    }
2678
2679    /// Count a send failure (one unreachable peer must neither end the
2680    /// listener nor reach `accept`).
2681    fn count_send_error(&self, r: Result<()>) {
2682        if r.is_err() {
2683            self.send_errors.fetch_add(1, Ordering::Relaxed);
2684        }
2685    }
2686
2687    /// Whether this listener has its own crypto config (feature-gated: with
2688    /// the `crypto` feature compiled out there is no such field, and the
2689    /// adapter can never accept an encrypted connection).
2690    fn local_crypto_enabled(&self) -> bool {
2691        #[cfg(feature = "crypto")]
2692        {
2693            self.config.crypto.is_some()
2694        }
2695        #[cfg(not(feature = "crypto"))]
2696        {
2697            false
2698        }
2699    }
2700
2701    fn handle_datagram(&mut self, src: std::net::SocketAddr, bytes: &[u8]) -> Result<()> {
2702        let packet = SrtPacket::parse(bytes).map_err(|e| handshake_err("parse", e))?;
2703
2704        let ctrl = match packet {
2705            SrtPacket::Control(c) => c,
2706            _ => return Ok(()),
2707        };
2708
2709        // A repeated CONCLUSION from a Caller we already accepted means our
2710        // response never reached it: send the very same response again. A
2711        // fresh INDUCTION from the same address starts over instead.
2712        if let ControlPacket::Handshake(hp) = &ctrl {
2713            match hp.handshake_type {
2714                HandshakeType::Conclusion => {
2715                    if let Some(recent) = self.recent_accepts.get(&src)
2716                        && recent.peer_socket_id == hp.srt_socket_id
2717                        && recent.accepted_at.elapsed() < RECENT_ACCEPT_TTL
2718                    {
2719                        let response = recent.response.clone();
2720                        self.outbound_queue
2721                            .entry(src)
2722                            .or_default()
2723                            .push_back(response);
2724                        return Ok(());
2725                    }
2726                }
2727                HandshakeType::Induction => {
2728                    self.recent_accepts.remove(&src);
2729                    // §4.3.1.1's SYN Cookie exists so an unverified Caller
2730                    // allocates nothing: answer, and keep no state (#2820).
2731                    return self.answer_induction(src, hp);
2732                }
2733                _ => {}
2734            }
2735        }
2736
2737        // A listener without its own crypto config refuses a peer that asks
2738        // for encryption (a non-zero `Encryption Field` or a `KMREQ` bit),
2739        // since it has no passphrase to recover the SEK with. A listener that
2740        // does have crypto configured leaves this to the sans-IO engine, which
2741        // performs the Key Material exchange. (On an INDUCTION the extension
2742        // field is the legacy UDT socket-type value, not the Table 3 bitmask
2743        // — see `handshake_sm::INDUCTION_LEGACY_SOCKET_TYPE`.)
2744        if !self.local_crypto_enabled()
2745            && let ControlPacket::Handshake(hp) = &ctrl
2746        {
2747            let asks_cipher = hp.encryption_field != EncryptionField::NoEncryption;
2748            let asks_kmreq =
2749                hp.handshake_type == HandshakeType::Conclusion && hp.extension_field.kmreq();
2750            if asks_cipher || asks_kmreq {
2751                // Refuse before allocating handshake state for the
2752                // source; `own_socket_id` is 0 because no socket was ever
2753                // assigned to this refused connection.
2754                let rejection = build_encryption_rejection(hp, 0, &self.config)?;
2755                self.outbound_queue
2756                    .entry(src)
2757                    .or_default()
2758                    .push_back(rejection);
2759                self.pending.remove(&src);
2760                return Ok(());
2761            }
2762        }
2763
2764        let is_new = !self.pending.contains_key(&src);
2765
2766        if is_new {
2767            // Only a CONCLUSION that echoes a cookie this listener issued may
2768            // allocate anything: an INDUCTION was answered statelessly above,
2769            // so a flood of guessed or spoofed ones holds no slots (#2820).
2770            let ControlPacket::Handshake(hp) = &ctrl else {
2771                return Ok(());
2772            };
2773            if hp.handshake_type != HandshakeType::Conclusion {
2774                return Ok(());
2775            }
2776            let Some((own_socket_id, our_initial_seq)) =
2777                self.validated_conclusion_ids(src, hp.srt_socket_id, hp.syn_cookie)
2778            else {
2779                return Ok(());
2780            };
2781            // The cookie proves the round trip but the table is still bounded
2782            // against a flood of genuinely answered Callers.
2783            if self.pending.len() >= MAX_PENDING {
2784                return Ok(());
2785            }
2786            let mut per_conn_config = self.config.clone();
2787            per_conn_config.initial_seq_number = our_initial_seq;
2788            let created_at = Instant::now();
2789            self.pending.insert(
2790                src,
2791                PendingListener {
2792                    handshake: ListenerHandshake::awaiting_conclusion(
2793                        own_socket_id,
2794                        hp.syn_cookie,
2795                        per_conn_config,
2796                    ),
2797                    params: None,
2798                    peer_initial_seq: hp.initial_seq_number,
2799                    peer_timestamp_us: 0,
2800                    concluded_at: None,
2801                    created_at,
2802                    last_response: None,
2803                    our_initial_seq,
2804                },
2805            );
2806        }
2807
2808        let entry = self
2809            .pending
2810            .get_mut(&src)
2811            .ok_or(Error::InvalidField(InvalidField {
2812                field: "pending",
2813                reason: "no pending entry",
2814            }))?;
2815
2816        if let ControlPacket::Handshake(hp) = &ctrl
2817            && hp.handshake_type == HandshakeType::Conclusion
2818        {
2819            // The first CONCLUSION fixes the pair (a repeat must not move it).
2820            if entry.concluded_at.is_none() {
2821                entry.peer_timestamp_us = hp.timestamp.value();
2822                entry.concluded_at = Some(Instant::now());
2823            }
2824        }
2825
2826        entry.handshake.set_elapsed(entry.created_at.elapsed());
2827        let outcomes = match entry.handshake.feed(&ctrl) {
2828            Ok(outcomes) => outcomes,
2829            Err(e) => {
2830                if is_new {
2831                    self.pending.remove(&src);
2832                }
2833                return Err(handshake_err("listener feed", e));
2834            }
2835        };
2836
2837        for outcome in outcomes {
2838            match outcome {
2839                HandshakeOutput::Send(bytes) => {
2840                    entry.last_response = Some(bytes.clone());
2841                    self.outbound_queue.entry(src).or_default().push_back(bytes);
2842                }
2843                HandshakeOutput::Connected(negotiated) => {
2844                    entry.params = Some(HandshakeOutput::Connected(negotiated));
2845                }
2846                HandshakeOutput::Rejected(reason) => {
2847                    self.pending.remove(&src);
2848                    return Err(Error::Rejected(reason));
2849                }
2850                HandshakeOutput::TimedOut => {
2851                    self.pending.remove(&src);
2852                    return Err(Error::HandshakeTimedOut { stage: "listener" });
2853                }
2854            }
2855        }
2856
2857        Ok(())
2858    }
2859
2860    /// Answer an INDUCTION without retaining any per-peer state
2861    /// (`draft-sharabayko-srt-01` §4.3.1.1). The response is built by the same
2862    /// sans-IO machine the stateful path used, then dropped: the connection's
2863    /// Socket ID and ISN are re-derived from the same keyed inputs when a
2864    /// CONCLUSION proves the Caller received this answer (#2820).
2865    fn answer_induction(
2866        &mut self,
2867        src: std::net::SocketAddr,
2868        hp: &HandshakePacket<'_>,
2869    ) -> Result<()> {
2870        let peer_key = cookie_peer_key(&src, hp.srt_socket_id);
2871        let time_bucket = unix_time_bucket();
2872        let secret = self.cookie_keys.current();
2873        let syn_cookie = derive_cookie(peer_key, time_bucket, secret);
2874        let (own_socket_id, our_initial_seq) = self.connection_ids(peer_key, time_bucket, secret);
2875        let mut per_conn_config = self.config.clone();
2876        per_conn_config.initial_seq_number = our_initial_seq;
2877        let mut handshake = ListenerHandshake::new(own_socket_id, syn_cookie, per_conn_config);
2878        for outcome in handshake.feed(&ControlPacket::Handshake(hp.clone()))? {
2879            if let HandshakeOutput::Send(bytes) = outcome {
2880                self.outbound_queue.entry(src).or_default().push_back(bytes);
2881            }
2882        }
2883        Ok(())
2884    }
2885
2886    /// Validate a CONCLUSION's SYN Cookie against this listener's current and
2887    /// previous key, across the current and previous one-minute bucket, and
2888    /// return the `(own socket id, our ISN)` the stateless INDUCTION answer
2889    /// carried for that `(peer, bucket, key)`. `None` means no state may be
2890    /// allocated (§4.3.1.1).
2891    fn validated_conclusion_ids(
2892        &self,
2893        src: std::net::SocketAddr,
2894        caller_socket_id: u32,
2895        syn_cookie: u32,
2896    ) -> Option<(u32, u32)> {
2897        if syn_cookie == 0 {
2898            return None;
2899        }
2900        let peer_key = cookie_peer_key(&src, caller_socket_id);
2901        let now = unix_time_bucket();
2902        for time_bucket in [now, now.wrapping_sub(1)] {
2903            for secret in self.cookie_keys.acceptable() {
2904                if derive_cookie(peer_key, time_bucket, secret) == syn_cookie {
2905                    return Some(self.connection_ids(peer_key, time_bucket, secret));
2906                }
2907            }
2908        }
2909        None
2910    }
2911
2912    /// This listener's per-connection Socket ID and ISN for a cookie issued
2913    /// over `(peer_key, time_bucket, secret)`, kept in libsrt's allocation
2914    /// range for the Socket ID (see [`MAX_SRT_SOCKET_ID`]).
2915    fn connection_ids(&self, peer_key: u64, time_bucket: u32, secret: u128) -> (u32, u32) {
2916        let (socket_id, initial_seq) =
2917            handshake_sm::derive_listener_ids(peer_key, time_bucket, secret);
2918        (socket_id % MAX_SRT_SOCKET_ID + 1, initial_seq)
2919    }
2920
2921    fn tick_pending(&mut self) {
2922        let mut to_remove = Vec::new();
2923        for (addr, entry) in self.pending.iter_mut() {
2924            entry.handshake.set_elapsed(entry.created_at.elapsed());
2925            for outcome in entry.handshake.tick(PENDING_TICK_INTERVAL) {
2926                match outcome {
2927                    HandshakeOutput::Send(bytes) => {
2928                        self.outbound_queue
2929                            .entry(*addr)
2930                            .or_default()
2931                            .push_back(bytes);
2932                    }
2933                    HandshakeOutput::TimedOut => {
2934                        to_remove.push(*addr);
2935                    }
2936                    _ => {}
2937                }
2938            }
2939        }
2940        for addr in to_remove {
2941            self.pending.remove(&addr);
2942            // A timed-out peer will never see another packet: drop its queued
2943            // handshake bytes too, so `outbound_queue` cannot grow per-source
2944            // without bound under a flood.
2945            self.outbound_queue.remove(&addr);
2946        }
2947        self.recent_accepts
2948            .retain(|_, r| r.accepted_at.elapsed() < RECENT_ACCEPT_TTL);
2949    }
2950
2951    /// Remember an accepted connection's CONCLUSION response (bounded: expired
2952    /// entries are reaped first, then the oldest is evicted if still full).
2953    fn remember_accept(&mut self, addr: std::net::SocketAddr, recent: RecentAccept) {
2954        self.recent_accepts
2955            .retain(|_, r| r.accepted_at.elapsed() < RECENT_ACCEPT_TTL);
2956        if self.recent_accepts.len() >= MAX_RECENT_ACCEPTS
2957            && let Some(oldest) = self
2958                .recent_accepts
2959                .iter()
2960                .min_by_key(|(_, r)| r.accepted_at)
2961                .map(|(a, _)| *a)
2962        {
2963            self.recent_accepts.remove(&oldest);
2964        }
2965        self.recent_accepts.insert(addr, recent);
2966    }
2967
2968    fn drain_completed(&mut self) -> Option<Result<SrtSocket>> {
2969        // Every handle is gone: nothing may be handed over (the cancel token
2970        // ends this task right after).
2971        let life = self.life.upgrade()?;
2972        let addr = self
2973            .pending
2974            .iter()
2975            .find(|(_, p)| {
2976                p.params.is_some()
2977                    && matches!(p.handshake.state(), ListenerHandshakeState::Connected)
2978            })
2979            .map(|(addr, _)| *addr)?;
2980
2981        let entry = self.pending.remove(&addr)?;
2982        // `Connected` entries always carry negotiated parameters, but a
2983        // missing one must not panic the accept loop.
2984        let Some(negotiated) = entry.handshake.negotiated() else {
2985            return Some(Err(Error::InvalidField(InvalidField {
2986                field: "listener handshake",
2987                reason: "Connected without negotiated parameters",
2988            })));
2989        };
2990        let peer_initial_seq = entry.peer_initial_seq;
2991        // The peer's negotiated SRT Socket ID (distinct from its ISN above).
2992        let peer_socket_id = negotiated.peer_socket_id;
2993        // This listener's own Socket ID for this connection — the value a
2994        // real peer's packets carry as `dest_socket_id` from here on, and so
2995        // the key the routing pump demultiplexes by (item 2; see
2996        // [`routing_pump`]).
2997        let own_socket_id = negotiated.own_socket_id;
2998        // The exact ISN this listener generated for `entry` at INDUCTION
2999        // time (`handle_datagram`) — not `self.config.initial_seq_number`,
3000        // which is the listener-wide template and no longer carries the
3001        // per-connection value once randomized.
3002        let our_initial_seq = entry.our_initial_seq;
3003        let tsbpd_delay = negotiated.latency;
3004        let concluded_at = entry.concluded_at.unwrap_or_else(Instant::now);
3005        let epoch = entry.created_at;
3006        let tsbpd_time_base = tsbpd_time_base_at(epoch, concluded_at, entry.peer_timestamp_us);
3007
3008        if let Some(response) = entry.last_response.clone() {
3009            self.remember_accept(
3010                addr,
3011                RecentAccept {
3012                    peer_socket_id,
3013                    response,
3014                    accepted_at: concluded_at,
3015                },
3016            );
3017        }
3018
3019        // Register this connection's own route in the shared demux table
3020        // (issue #1029) *before* handing off to its driver task — the
3021        // routing pump must never see a datagram naming this connection's
3022        // Socket ID land in `unrouted_rx` again once this connection exists.
3023        let (tx, rx) = mpsc::channel(RX_CHANNEL_CAPACITY);
3024        let stats = Arc::new(Counters::default());
3025        lock(&self.routes).insert(
3026            own_socket_id,
3027            RouteEntry {
3028                addr,
3029                tx,
3030                stats: Arc::clone(&stats),
3031            },
3032        );
3033
3034        // Share the listener's Arc<UdpSocket> with the connection's driver.
3035        let conn = SrtSocket::spawn(ConnParams {
3036            udp: Arc::clone(&self.udp),
3037            peer_addr: addr,
3038            rx,
3039            stats,
3040            route_cleanup: RouteCleanup(Some((own_socket_id, Arc::clone(&self.routes)))),
3041            forwarder_guard: TaskGuard(None),
3042            life: Some(life),
3043            read_idle: self.io.timeouts.read_idle,
3044            write: self.io.timeouts.write,
3045            our_initial_seq,
3046            peer_initial_seq,
3047            peer_socket_id,
3048            tsbpd_time_base,
3049            tsbpd_delay,
3050            epoch,
3051            max_flow_window: negotiated.max_flow_window_size,
3052            mtu: negotiated.mtu,
3053            tlpkt_drop: negotiated.flags.tlpktdrop(),
3054            #[cfg(feature = "crypto")]
3055            crypto_passphrase: self
3056                .config
3057                .crypto
3058                .as_ref()
3059                .map(|c| c.passphrase.clone())
3060                .unwrap_or_default(),
3061            #[cfg(feature = "crypto")]
3062            crypto_salt: negotiated.salt,
3063            #[cfg(feature = "crypto")]
3064            crypto_even_sek: negotiated.sek.as_ref().map(|s| s.to_vec()),
3065            #[cfg(feature = "crypto")]
3066            crypto_thresholds: self.io.km_refresh_thresholds,
3067        });
3068        Some(Ok(conn))
3069    }
3070
3071    async fn flush_for_peer(&mut self, addr: std::net::SocketAddr) -> Result<()> {
3072        if let Some(queue) = self.outbound_queue.get_mut(&addr) {
3073            while let Some(bytes) = queue.pop_front() {
3074                send_bounded(&self.udp, &bytes, addr, self.io.timeouts.write, "send_to").await?;
3075            }
3076        }
3077        Ok(())
3078    }
3079
3080    async fn flush_all(&mut self) -> Result<()> {
3081        let addrs: Vec<std::net::SocketAddr> = self.outbound_queue.keys().copied().collect();
3082        for addr in addrs {
3083            self.flush_for_peer(addr).await?;
3084        }
3085        Ok(())
3086    }
3087}
3088
3089/// The single task that ever calls `recv_from` on a [`SrtListener`]'s
3090/// shared socket, demultiplexing every datagram the way libsrt does (item 2,
3091/// draft §4.3.1; libsrt's `CRcvQueue::worker` dispatches on Destination
3092/// Socket ID the same way): Destination Socket ID `0` always means "not yet
3093/// an established connection" and goes to `unrouted_tx` (`accept`'s own
3094/// input — every handshake packet this crate's Caller sends carries `0`
3095/// there, see `caller.rs`); any other ID must match a `routes` entry *and*
3096/// that entry's accepted source address, or the datagram is dropped — an ID
3097/// nothing accepted, or one accepted from a different address, has no
3098/// legitimate connection to reach. This is what makes it safe for the
3099/// listener's `accept` loop and every accepted connection's driver task to
3100/// run concurrently without racing each other for the same socket's
3101/// `recv_from`.
3102async fn routing_pump(
3103    udp: Arc<UdpSocket>,
3104    routes: RouteTable,
3105    unrouted_tx: mpsc::Sender<(std::net::SocketAddr, Bytes)>,
3106    unrouted_dropped: Arc<AtomicU64>,
3107    max_datagram: usize,
3108    cancel: CancellationToken,
3109) {
3110    let mut scratch = vec![0u8; max_datagram + 1];
3111    loop {
3112        let received = tokio::select! {
3113            _ = cancel.cancelled() => break,
3114            r = recv_datagram(&udp, &mut scratch, max_datagram, &unrouted_dropped) => r,
3115        };
3116        let (bytes, src) = match received {
3117            Ok(Some(v)) => v,
3118            Ok(None) => continue, // oversize: dropped and counted.
3119            Err(_) => break,      // socket error — end the pump.
3120        };
3121        match crate::packet::peek_dest_socket_id(&bytes) {
3122            Some(0) | None => {
3123                // `0` (candidate new connection) or too short to carry a
3124                // full header at all — either way, not a routable
3125                // established-connection packet; hand it to the handshake
3126                // task, which parses (and rejects malformed bytes) properly.
3127                if unrouted_tx.try_send((src, bytes)).is_err() {
3128                    if unrouted_tx.is_closed() {
3129                        // The handshake task is gone; nothing more this pump can do.
3130                        break;
3131                    }
3132                    unrouted_dropped.fetch_add(1, Ordering::Relaxed);
3133                }
3134            }
3135            Some(id) => {
3136                let route = lock(&routes).get(&id).cloned();
3137                // No `route` entry (no connection was ever accepted with
3138                // this ID), or one exists but from a different source
3139                // address, is never routed — spoofed-source packets
3140                // included.
3141                if let Some(entry) = route
3142                    && entry.addr == src
3143                    && entry.tx.try_send(bytes).is_err()
3144                    && !entry.tx.is_closed()
3145                {
3146                    // A closed channel would instead mean the
3147                    // connection's driver has already exited (it
3148                    // removes its own entry on the way out — see
3149                    // `RouteCleanup`), a benign race, not counted; a
3150                    // still-open-but-full channel is this connection's
3151                    // own backpressure (item 4).
3152                    entry.stats.rx_dropped.fetch_add(1, Ordering::Relaxed);
3153                }
3154            }
3155        }
3156    }
3157}
3158
3159// ===========================================================================
3160// Helpers
3161// ===========================================================================
3162
3163/// Builds a Handshake rejection packet (`Handshake Type` = `1000 + code`,
3164/// §4.3 Table 7) refusing an encryption request with
3165/// [`RejectionReason::Unsecure`] ("password required or unexpected", code
3166/// 1011) — the same wire shape `listener.rs` emits for its own rejections.
3167/// The adapter needs it because a peer can advertise encryption via the
3168/// `Encryption Field` / `KMREQ` flag bits without ever sending a Key Material
3169/// extension block for the engine to notice.
3170fn build_encryption_rejection(
3171    hp: &HandshakePacket<'_>,
3172    own_socket_id: u32,
3173    config: &HandshakeConfig,
3174) -> Result<Vec<u8>> {
3175    let hp_out = HandshakePacket {
3176        timestamp: crate::packet::SrtTimestamp::ZERO,
3177        dest_socket_id: crate::packet::SocketId::from_wire(hp.srt_socket_id),
3178        version: handshake_sm::HANDSHAKE_VERSION_5,
3179        encryption_field: EncryptionField::NoEncryption,
3180        extension_field: HandshakeExtensionFlags(0),
3181        initial_seq_number: 0,
3182        mtu: config.mtu,
3183        max_flow_window_size: config.max_flow_window_size,
3184        handshake_type: RejectionReason::Unsecure.to_handshake_type(),
3185        srt_socket_id: own_socket_id,
3186        syn_cookie: 0,
3187        peer_ip: config.local_ip,
3188        extensions: HandshakeExtensions(Vec::new()),
3189    };
3190    handshake_sm::build_bytes(hp_out)
3191}
3192
3193/// Runs `fut` for at most `limit`; expiry is `Error::Io { kind: TimedOut, context }`.
3194async fn bounded<T>(
3195    limit: Duration,
3196    context: &'static str,
3197    fut: impl core::future::Future<Output = Result<T>>,
3198) -> Result<T> {
3199    tokio::time::timeout(limit, fut)
3200        .await
3201        .map_err(|_| Error::Io {
3202            kind: std::io::ErrorKind::TimedOut,
3203            context,
3204        })?
3205}
3206
3207/// `send_to` bounded by `limit` (the [`IoConfig::write`] timeout).
3208async fn send_bounded(
3209    udp: &UdpSocket,
3210    bytes: &[u8],
3211    to: std::net::SocketAddr,
3212    limit: Duration,
3213    context: &'static str,
3214) -> Result<()> {
3215    bounded(limit, context, async {
3216        udp.send_to(bytes, to)
3217            .await
3218            .map(|_| ())
3219            .map_err(|e| io_err(context, e))
3220    })
3221    .await
3222}
3223
3224/// Maps an OS I/O failure to a structured [`Error::Io`], preserving the
3225/// `std::io::ErrorKind` (bind failures are then distinguishable from
3226/// mid-connection resets, etc.) and the call site that failed. `std::io::Error`
3227/// itself is not `Clone`/`Eq` (this crate's [`Error`] derives both), so only
3228/// its `kind()` is kept — see the `S4` release-audit finding.
3229fn io_err(context: &'static str, e: std::io::Error) -> Error {
3230    Error::Io {
3231        kind: e.kind(),
3232        context,
3233    }
3234}
3235
3236/// Wraps an engine/codec failure with the handshake stage it happened in,
3237/// keeping the underlying error as the source (r08-SRT-W12) rather than
3238/// flattening it to a generic invalid-field error.
3239fn handshake_err(stage: &'static str, source: Error) -> Error {
3240    Error::Handshake {
3241        stage,
3242        source: alloc::boxed::Box::new(source),
3243    }
3244}
3245
3246/// Mixes a [`std::net::SocketAddr`] into a `u64` for use as `derive_cookie`'s
3247/// `peer_key` input (§4.3.1.1: the cookie is "crafted based on host,
3248/// port..."). Not a spec-defined algorithm — any stable, well-distributed
3249/// mix of the peer's address is sufficient here: the secrecy of the cookie
3250/// rests on the keyed hash in [`derive_cookie`], not on this.
3251fn addr_to_u64(addr: &std::net::SocketAddr) -> u64 {
3252    let mut hasher = std::collections::hash_map::DefaultHasher::new();
3253    addr.hash(&mut hasher);
3254    hasher.finish()
3255}
3256
3257/// The `peer_key` a listener binds a SYN cookie to: the source address and the
3258/// Caller's own SRT Socket ID. §4.3.1.1's cookie is "crafted based on host,
3259/// port and current time"; binding the ID as well means a captured
3260/// CONCLUSION replayed with a rewritten Socket ID no longer validates, while
3261/// the same host may still reconnect from the same port under a fresh ID
3262/// (its INDUCTION issues a cookie for that ID).
3263fn cookie_peer_key(addr: &std::net::SocketAddr, caller_socket_id: u32) -> u64 {
3264    addr_to_u64(addr) ^ (u64::from(caller_socket_id) << 32)
3265}
3266
3267/// The current UNIX time, bucketed to 1-minute accuracy — the `time_bucket`
3268/// input `derive_cookie` expects (§4.3.1.1: "...and current time with 1
3269/// minute accuracy").
3270fn unix_time_bucket() -> u32 {
3271    let secs = std::time::SystemTime::now()
3272        .duration_since(std::time::UNIX_EPOCH)
3273        .unwrap_or_default()
3274        .as_secs();
3275    u32::try_from(secs / 60).unwrap_or(u32::MAX)
3276}
3277
3278/// A random `u64` from the OS randomness source (`getrandom`), used as
3279/// `derive_cookie`'s `secret` input and to draw the per-connection Socket ID
3280/// and ISN (SRT-W11). A failing OS source is reported, never panicked on.
3281fn random_u64() -> Result<u64> {
3282    let mut bytes = [0u8; 8];
3283    getrandom::fill(&mut bytes).map_err(|_| Error::Io {
3284        kind: std::io::ErrorKind::Other,
3285        context: "getrandom",
3286    })?;
3287    Ok(u64::from_ne_bytes(bytes))
3288}
3289
3290/// A random `u128` (two OS draws).
3291fn random_u128() -> Result<u128> {
3292    Ok((u128::from(random_u64()?) << 64) | u128::from(random_u64()?))
3293}
3294
3295/// The low 32 bits of a fresh random `u64`.
3296fn random_u32() -> Result<u32> {
3297    Ok(u32::try_from(random_u64()? & u64::from(u32::MAX)).unwrap_or(0))
3298}
3299
3300/// The largest SRT Socket ID this adapter will ever generate.
3301///
3302/// `draft-sharabayko-srt-01` §3/§4.3.1.1 gives the wire field only as "32
3303/// bits" (this crate's own `private/specs-verified/ietf/specs/ietf_draft_sharabayko_srt_01.txt`, e.g. its
3304/// Handshake Packet description — no transcription in this crate's `docs/`
3305/// narrows that range further; there is no `docs/` directory at all yet). A
3306/// real libsrt peer, though, only ever *allocates* an ID in `1..=`
3307/// [`MAX_SRT_SOCKET_ID`]: libsrt's `CUDTUnited::generateSocketID`
3308/// (`srtcore/core.cpp`) masks a freshly drawn 32-bit value down with `&
3309/// 0x3FFFFFFF` before use — bit 30 (`0x40000000`) is libsrt's own "this ID
3310/// names a socket group, not a plain socket" marker, and bit 31 would make
3311/// the ID negative when read back as libsrt's signed C `int`. Generating
3312/// outside that range is wire-legal per the draft but not a value any real
3313/// SRT implementation would ever send or expect, so this adapter matches
3314/// libsrt's allocation range rather than exercising the full 32 bits.
3315const MAX_SRT_SOCKET_ID: u32 = 0x3FFF_FFFF;
3316
3317/// A random SRT Socket ID for a new connection, drawn from the same
3318/// OS-seeded source as [`random_u64`], in `1..=`[`MAX_SRT_SOCKET_ID`] (see
3319/// its doc). Never `0` — that value marks "no socket assigned" elsewhere in
3320/// this adapter (see [`build_encryption_rejection`]'s `own_socket_id`
3321/// argument for a refused, pre-handshake peer) and is reserved for that
3322/// meaning here too — the `% MAX_SRT_SOCKET_ID` reduction followed by `+ 1`
3323/// makes both guarantees (never `0`, never above the cap) hold by
3324/// construction, with no retry loop needed.
3325fn random_socket_id() -> Result<u32> {
3326    Ok(random_u32()? % MAX_SRT_SOCKET_ID + 1)
3327}
3328
3329/// A random Initial Sequence Number in the legal 31-bit SRT sequence-number
3330/// range (`SEQ_NUMBER_MASK`, §3) for a new connection. Every new Caller
3331/// connect and every new accepted Listener connection must draw a fresh
3332/// value here rather than reuse a fixed/default `HandshakeConfig::initial_seq_number`
3333/// (SRT-W11): `draft-sharabayko-srt-01` §3/§4.3.1.1 expects the ISN
3334/// unpredictable per connection, same as the Socket ID above.
3335fn random_isn() -> Result<u32> {
3336    Ok(random_u32()? & SEQ_NUMBER_MASK)
3337}
3338
3339async fn resolve_one<A: tokio::net::ToSocketAddrs>(addr: A) -> Result<std::net::SocketAddr> {
3340    let mut addrs = tokio::net::lookup_host(addr)
3341        .await
3342        .map_err(|e| io_err("resolve", e))?;
3343    addrs.next().ok_or(Error::Io {
3344        kind: std::io::ErrorKind::AddrNotAvailable,
3345        context: "resolve: no addresses",
3346    })
3347}
3348
3349/// The fields of the peer's final handshake packet the adapter seeds its
3350/// engines from.
3351#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3352struct PeerHandshake {
3353    /// The peer's Initial Packet Sequence Number (§3.2.1).
3354    initial_seq_number: u32,
3355    /// The packet's `Timestamp` (§3), microseconds since the peer's
3356    /// connection start — `HSREQ_TIMESTAMP` of `TsbpdTimeBase = T_NOW -
3357    /// HSREQ_TIMESTAMP` (§4.5.1.1).
3358    timestamp_us: u32,
3359}
3360
3361/// Extract the peer's `initial_seq_number` and timestamp from a handshake
3362/// control packet's bytes. These seed ARQ and TSBPD sequence/time tracking for
3363/// the entire connection, so "the bytes didn't parse as a Handshake" must be a
3364/// distinct, caller-visible outcome from "the peer's ISN is genuinely 0" — the
3365/// two are otherwise indistinguishable to a caller that only sees a `u32`.
3366/// Returns [`Error::InvalidField`] rather than defaulting to `0` on any parse
3367/// failure.
3368fn peer_handshake(bytes: &[u8]) -> Result<PeerHandshake> {
3369    match SrtPacket::parse(bytes) {
3370        Ok(SrtPacket::Control(ControlPacket::Handshake(hp))) => Ok(PeerHandshake {
3371            initial_seq_number: hp.initial_seq_number,
3372            timestamp_us: hp.timestamp.value(),
3373        }),
3374        _ => Err(Error::InvalidField(InvalidField {
3375            field: "peer handshake",
3376            reason: "handshake reached Connected but its final packet did not re-parse as a \
3377                     Handshake control packet; refusing to seed ARQ/TSBPD with a fabricated ISN",
3378        })),
3379    }
3380}
3381
3382/// `TsbpdTimeBase` seed (§4.5.1.1, rule 12): `T_NOW - HSREQ_TIMESTAMP` with
3383/// `T_NOW` = 0 at the connection epoch (the instant the handshake packet
3384/// arrived), i.e. minus the peer's handshake timestamp. Signed: the
3385/// timestamp, counted from the peer's own start, is generally positive, so
3386/// the base is generally negative.
3387fn tsbpd_time_base_from(peer_timestamp_us: u32) -> i64 {
3388    -i64::from(peer_timestamp_us)
3389}
3390
3391/// [`tsbpd_time_base_from`] for a connection whose epoch is the instant the
3392/// handshake began: `T_NOW` is how long after `epoch` the peer's handshake
3393/// packet arrived.
3394fn tsbpd_time_base_at(epoch: Instant, arrived: Instant, peer_timestamp_us: u32) -> i64 {
3395    let t_now =
3396        i64::try_from(arrived.saturating_duration_since(epoch).as_micros()).unwrap_or(i64::MAX);
3397    t_now.saturating_add(tsbpd_time_base_from(peer_timestamp_us))
3398}
3399
3400#[cfg(test)]
3401mod socket_id_tests {
3402    use super::*;
3403
3404    /// Bite test: run against the unfixed `random_socket_id` (a bare
3405    /// `random_u64() as u32`, only ever excluding `0`) and this fails —
3406    /// values above `MAX_SRT_SOCKET_ID` come up immediately (bit 31 alone is
3407    /// set on ~50% of draws). Fixed, every draw is folded into
3408    /// `1..=MAX_SRT_SOCKET_ID` by construction.
3409    #[test]
3410    fn random_socket_id_stays_in_the_libsrt_allocation_range() {
3411        for _ in 0..10_000 {
3412            let id = random_socket_id().expect("OS randomness");
3413            assert!(id != 0, "socket id must never be 0");
3414            assert!(
3415                id <= MAX_SRT_SOCKET_ID,
3416                "socket id {id:#010x} exceeds the libsrt allocation range {MAX_SRT_SOCKET_ID:#010x}"
3417            );
3418        }
3419    }
3420}
3421
3422#[cfg(test)]
3423mod isn_tests {
3424    use broadcast_common::error::InvalidField;
3425
3426    use super::*;
3427    use crate::packet::{
3428        EncryptionField, HandshakeExtensionFlags, HandshakeExtensions, HandshakePacket,
3429        HandshakeType,
3430    };
3431
3432    fn handshake_bytes(initial_seq_number: u32) -> Vec<u8> {
3433        let hp = HandshakePacket {
3434            timestamp: crate::packet::SrtTimestamp::ZERO,
3435            dest_socket_id: crate::packet::SocketId::CONNECTION_REQUEST,
3436            version: 5,
3437            encryption_field: EncryptionField::NoEncryption,
3438            extension_field: HandshakeExtensionFlags(0),
3439            initial_seq_number,
3440            mtu: 1500,
3441            max_flow_window_size: 8192,
3442            handshake_type: HandshakeType::Conclusion,
3443            srt_socket_id: 42,
3444            syn_cookie: 0,
3445            peer_ip: [0; 4],
3446            extensions: HandshakeExtensions(Vec::new()),
3447        };
3448        crate::handshake_sm::build_bytes(hp).expect("build handshake bytes")
3449    }
3450
3451    #[test]
3452    fn peer_handshake_extracts_nonzero_isn() {
3453        let bytes = handshake_bytes(0xABCD_1234);
3454        assert_eq!(
3455            peer_handshake(&bytes).unwrap().initial_seq_number,
3456            0xABCD_1234
3457        );
3458    }
3459
3460    #[test]
3461    fn peer_handshake_distinguishes_genuine_zero_from_parse_failure() {
3462        // A genuine ISN of 0 is a valid, well-formed handshake and must
3463        // succeed as Ok(0) — not be conflated with "couldn't parse".
3464        let bytes = handshake_bytes(0);
3465        assert_eq!(peer_handshake(&bytes).unwrap().initial_seq_number, 0);
3466
3467        // Bytes that don't parse as a Handshake control packet at all
3468        // (too short to even carry the fixed SRT header) must error, never
3469        // silently produce a plausible-looking 0.
3470        let err = peer_handshake(&[0u8; 4]).unwrap_err();
3471        assert!(matches!(
3472            err,
3473            Error::InvalidField(InvalidField {
3474                field: "peer handshake",
3475                ..
3476            })
3477        ));
3478    }
3479
3480    #[test]
3481    fn peer_handshake_rejects_non_handshake_control_packet() {
3482        // A well-formed control packet of the WRONG type (Keep-Alive, not
3483        // Handshake) must also error rather than default to 0.
3484        let ka = ControlPacket::KeepAlive(KeepAlivePacket {
3485            timestamp: crate::packet::SrtTimestamp::ZERO,
3486            dest_socket_id: crate::packet::SocketId::from_wire(7),
3487            libsrt_pad: false,
3488        });
3489        let mut buf = alloc::vec![0u8; ka.serialized_len()];
3490        ka.serialize_into(&mut buf).expect("serialize keepalive");
3491        let err = peer_handshake(&buf).unwrap_err();
3492        assert!(matches!(
3493            err,
3494            Error::InvalidField(InvalidField {
3495                field: "peer handshake",
3496                ..
3497            })
3498        ));
3499    }
3500}
3501
3502// ===========================================================================
3503// Adapter security tests (r08-SRT-C2 / C6 / C7)
3504// ===========================================================================
3505
3506#[cfg(test)]
3507#[cfg(feature = "tokio")]
3508mod adapter_tests {
3509    use super::*;
3510    use crate::packet::{
3511        AckCif, AckPacket, DataPacket, DropReqPacket, EncryptionKeyField, HandshakeExtensionFlags,
3512        HandshakeExtensions, HandshakePacket, PacketPosition,
3513    };
3514    use broadcast_common::error::BufferTooShort;
3515
3516    const PEER: &str = "10.0.0.1:9999";
3517    /// TSBPD latency used by the test drivers (the spec minimum, §4.5.1).
3518    const LATENCY_MS: u64 = 120;
3519
3520    fn peer_addr() -> std::net::SocketAddr {
3521        PEER.parse().unwrap()
3522    }
3523
3524    /// A `Driver` wired to a throwaway bound socket and an unbounded delivery
3525    /// channel, with the same engine defaults `spawn` uses — so `ingress`,
3526    /// `tick_engines` and `staged` can be driven directly without a live
3527    /// handshake.
3528    async fn test_driver(max_flow_window: u32) -> (Driver, mpsc::Receiver<Bytes>) {
3529        let (driver, rx, _datagram_tx) = test_driver_with_ingress(max_flow_window).await;
3530        // The inbound-datagram sender is dropped here: the tests that use this
3531        // drive `ingress`/`tick_engines` directly, never `Driver::run`'s
3532        // select loop (which would see the closed channel as "upstream gone").
3533        (driver, rx)
3534    }
3535
3536    /// Like [`test_driver`], but also returns the live sender of the
3537    /// driver's inbound-datagram channel, so `Driver::run` can be spawned.
3538    async fn test_driver_with_ingress(
3539        max_flow_window: u32,
3540    ) -> (Driver, mpsc::Receiver<Bytes>, mpsc::Sender<Bytes>) {
3541        let udp = Arc::new(UdpSocket::bind("127.0.0.1:0").await.unwrap());
3542        // Make the socket's writability known up front. Without it the first
3543        // `send_to` yields to the reactor, and under a paused clock the
3544        // runtime would then auto-advance time to the (new) write-timeout
3545        // timer before the real send completes.
3546        udp.writable().await.unwrap();
3547        let (deliver, rx) = mpsc::channel(DELIVER_CHANNEL_CAPACITY);
3548        let (datagram_tx, datagram_rx) = mpsc::channel(RX_CHANNEL_CAPACITY);
3549        let driver = Driver::new(
3550            ConnParams {
3551                udp,
3552                peer_addr: peer_addr(),
3553                rx: datagram_rx,
3554                stats: Arc::new(Counters::default()),
3555                route_cleanup: RouteCleanup(None),
3556                forwarder_guard: TaskGuard(None),
3557                life: None,
3558                read_idle: IoConfig::default().timeouts.read_idle,
3559                write: IoConfig::default().timeouts.write,
3560                our_initial_seq: 0,
3561                peer_initial_seq: 0,
3562                peer_socket_id: 1,
3563                tsbpd_time_base: 0,
3564                tsbpd_delay: Duration::from_millis(LATENCY_MS),
3565                epoch: Instant::now(),
3566                max_flow_window,
3567                mtu: 1500,
3568                tlpkt_drop: true,
3569                #[cfg(feature = "crypto")]
3570                crypto_passphrase: Vec::new(),
3571                #[cfg(feature = "crypto")]
3572                crypto_salt: None,
3573                #[cfg(feature = "crypto")]
3574                crypto_even_sek: None,
3575                #[cfg(feature = "crypto")]
3576                crypto_thresholds: crate::km_refresh::KmRefreshThresholds::RECOMMENDED,
3577            },
3578            deliver,
3579        );
3580        (driver, rx, datagram_tx)
3581    }
3582
3583    fn data_bytes(seq: u32, timestamp: u32, payload: &[u8]) -> Vec<u8> {
3584        let dp = DataPacket {
3585            seq_number: seq,
3586            position: PacketPosition::Solo,
3587            in_order: true,
3588            key_flag: EncryptionKeyField::NotEncrypted,
3589            retransmitted: false,
3590            message_number: seq & crate::packet::data::MESSAGE_NUMBER_MASK,
3591            timestamp: crate::packet::SrtTimestamp::from_wire(timestamp),
3592            dest_socket_id: crate::packet::SocketId::from_wire(1),
3593            data: payload,
3594        };
3595        let mut buf = alloc::vec![0u8; dp.serialized_len()];
3596        dp.serialize_into(&mut buf).expect("serialize data");
3597        buf
3598    }
3599
3600    fn encrypted_data_bytes(seq: u32, timestamp: u32, payload: &[u8]) -> Vec<u8> {
3601        let mut buf = data_bytes(seq, timestamp, payload);
3602        // Flip the `KK` field of word 1 from `00b` to `01b` (even key).
3603        let word1 = u32::from_be_bytes([buf[4], buf[5], buf[6], buf[7]]);
3604        let word1 = (word1 & !(0b11 << 27)) | (u32::from(EncryptionKeyField::Even.to_bits()) << 27);
3605        buf[4..8].copy_from_slice(&word1.to_be_bytes());
3606        buf
3607    }
3608
3609    fn dropreq_bytes(first: u32, last: u32) -> Vec<u8> {
3610        let pkt = ControlPacket::DropReq(DropReqPacket {
3611            message_number: crate::packet::MessageNumber::try_new(0).expect("fits"),
3612            timestamp: crate::packet::SrtTimestamp::ZERO,
3613            dest_socket_id: crate::packet::SocketId::from_wire(1),
3614            first_seq: crate::packet::SeqNo::from_wire_masked(first),
3615            last_seq: crate::packet::SeqNo::from_wire_masked(last),
3616        });
3617        let mut buf = alloc::vec![0u8; pkt.serialized_len()];
3618        pkt.serialize_into(&mut buf).expect("serialize dropreq");
3619        buf
3620    }
3621
3622    fn induction_bytes(socket_id: u32) -> Vec<u8> {
3623        let hp = HandshakePacket {
3624            timestamp: crate::packet::SrtTimestamp::ZERO,
3625            dest_socket_id: crate::packet::SocketId::CONNECTION_REQUEST,
3626            version: crate::handshake_sm::HANDSHAKE_VERSION_4,
3627            encryption_field: crate::packet::EncryptionField::NoEncryption,
3628            extension_field: HandshakeExtensionFlags(
3629                crate::handshake_sm::INDUCTION_LEGACY_SOCKET_TYPE,
3630            ),
3631            initial_seq_number: 0,
3632            mtu: 1500,
3633            max_flow_window_size: 8192,
3634            handshake_type: crate::packet::HandshakeType::Induction,
3635            srt_socket_id: socket_id,
3636            syn_cookie: 0,
3637            peer_ip: [0; 4],
3638            extensions: HandshakeExtensions(Vec::new()),
3639        };
3640        let pkt = ControlPacket::Handshake(hp);
3641        let mut buf = alloc::vec![0u8; pkt.serialized_len()];
3642        pkt.serialize_into(&mut buf).expect("serialize induction");
3643        buf
3644    }
3645
3646    /// A CONCLUSION with no extensions and `cookie` — either a stray (cookie
3647    /// 0 never validates) or a probe with a chosen cookie.
3648    fn conclusion_bytes(socket_id: u32, cookie: u32) -> Vec<u8> {
3649        let hp = HandshakePacket {
3650            timestamp: crate::packet::SrtTimestamp::ZERO,
3651            dest_socket_id: crate::packet::SocketId::CONNECTION_REQUEST,
3652            version: crate::handshake_sm::HANDSHAKE_VERSION_5,
3653            encryption_field: crate::packet::EncryptionField::NoEncryption,
3654            extension_field: HandshakeExtensionFlags(0),
3655            initial_seq_number: 0,
3656            mtu: 1500,
3657            max_flow_window_size: 8192,
3658            handshake_type: crate::packet::HandshakeType::Conclusion,
3659            srt_socket_id: socket_id,
3660            syn_cookie: cookie,
3661            peer_ip: [0; 4],
3662            extensions: HandshakeExtensions(Vec::new()),
3663        };
3664        let pkt = ControlPacket::Handshake(hp);
3665        let mut buf = alloc::vec![0u8; pkt.serialized_len()];
3666        pkt.serialize_into(&mut buf).expect("serialize conclusion");
3667        buf
3668    }
3669
3670    /// Drives a real [`CallerHandshake`] through its INDUCTION against `core`
3671    /// and returns the CONCLUSION bytes it produces, leaving `core` with no
3672    /// queued handshake datagram for `src`.
3673    fn listener_conclusion(
3674        core: &mut ListenerCore,
3675        src: std::net::SocketAddr,
3676        caller_socket_id: u32,
3677    ) -> Vec<u8> {
3678        let mut caller = CallerHandshake::new(caller_socket_id, HandshakeConfig::default());
3679        let induction = caller.start().expect("caller induction");
3680        core.handle_datagram(src, &induction)
3681            .expect("the listener answers an induction");
3682        let answer = core
3683            .outbound_queue
3684            .get(&src)
3685            .and_then(|queue| queue.back())
3686            .expect("an INDUCTION response")
3687            .clone();
3688        core.outbound_queue.remove(&src);
3689        let parsed = ControlPacket::parse(&answer).expect("parse induction response");
3690        let mut conclusion = None;
3691        for outcome in caller.feed(&parsed).expect("caller feed") {
3692            if let HandshakeOutput::Send(bytes) = outcome {
3693                conclusion = Some(bytes);
3694            }
3695        }
3696        conclusion.expect("the caller sends a conclusion")
3697    }
3698
3699    /// Review-focus 2. UDP truncates a datagram larger than the receive buffer
3700    /// without telling the reader; a truncated DATA packet then parses as a
3701    /// shorter, valid packet and its payload is delivered corrupted. The
3702    /// forwarder must read `max + 1` bytes, drop anything longer than `max`,
3703    /// and count it.
3704    #[tokio::test]
3705    async fn an_oversize_datagram_is_dropped_and_counted_never_truncated() {
3706        let local = Arc::new(UdpSocket::bind("127.0.0.1:0").await.unwrap());
3707        let peer = UdpSocket::bind("127.0.0.1:0").await.unwrap();
3708        let stats = Arc::new(Counters::default());
3709        let (mut rx, _guard) = spawn_dedicated_socket_forwarder(
3710            Arc::clone(&local),
3711            peer.local_addr().unwrap(),
3712            Arc::clone(&stats),
3713            300,
3714        );
3715        let local_addr = local.local_addr().unwrap();
3716        peer.send_to(&[1u8; 250], local_addr).await.unwrap();
3717        peer.send_to(&[2u8; 400], local_addr).await.unwrap(); // > 300
3718        peer.send_to(&[3u8; 300], local_addr).await.unwrap(); // exactly max: accepted
3719        let a = rx.recv().await.unwrap();
3720        let b = rx.recv().await.unwrap();
3721        assert_eq!((a.len(), a[0]), (250, 1));
3722        assert_eq!(
3723            (b.len(), b[0]),
3724            (300, 3),
3725            "the 400-byte datagram must not appear, truncated or not"
3726        );
3727        assert_eq!(stats.rx_oversize.load(Ordering::Relaxed), 1);
3728    }
3729
3730    #[test]
3731    fn io_config_clamps_a_tiny_max_datagram() {
3732        assert_eq!(
3733            IoConfig::default().with_max_datagram(1).max_datagram,
3734            MIN_MAX_DATAGRAM
3735        );
3736        assert_eq!(IoConfig::default().max_datagram, 1500);
3737        assert_eq!(
3738            IoConfig::default()
3739                .with_max_datagram(usize::MAX)
3740                .max_datagram,
3741            MAX_MAX_DATAGRAM,
3742            "an absurd size is clamped, never overflows `max + 1`"
3743        );
3744    }
3745
3746    #[tokio::test(start_paused = true)]
3747    async fn an_idle_driver_deadline_is_the_ack_period_not_a_two_ms_tick() {
3748        let (driver, _rx) = test_driver(8192).await;
3749        let d = driver
3750            .poll_timeout()
3751            .expect("a connected driver always has a deadline");
3752        assert_eq!(d - driver.epoch, crate::arq::FULL_ACK_PERIOD);
3753    }
3754
3755    /// The old fixed 2 ms ticker ran `tick_engines` ~50 times per 100 ms of idle time; the
3756    /// deadline-driven loop wakes for the 10 ms ACK cadence only.
3757    #[tokio::test(start_paused = true)]
3758    async fn the_run_loop_wakes_at_deadlines_not_on_a_fixed_two_ms_tick() {
3759        let (mut driver, _rx, _tx) = test_driver_with_ingress(8192).await;
3760        // The loop really sends its ACKs: a loopback address accepts them, where
3761        // the default non-routable test peer errors on some hosts and ends the loop.
3762        driver.peer_addr = "127.0.0.1:1".parse().unwrap();
3763        let ticks = Arc::new(AtomicU64::new(0));
3764        driver.tick_counter = Some(Arc::clone(&ticks));
3765        let (_app_tx, app_rx) = mpsc::channel(8);
3766        let handle = tokio::spawn(driver.run(app_rx));
3767        // `advance` jumps the clock in ONE step, so walk it 1 ms at a time to let every timer fire in order.
3768        for _ in 0..100 {
3769            tokio::time::advance(Duration::from_millis(1)).await;
3770            tokio::task::yield_now().await;
3771        }
3772        let n = ticks.load(Ordering::Relaxed);
3773        assert!(
3774            (8..=14).contains(&n),
3775            "expected ~10 wake-ups in 100 ms (10 ms ACK cadence), got {n}"
3776        );
3777        handle.abort();
3778    }
3779
3780    /// A [`ListenerCore`] over a throwaway socket, never spawned: tests drive
3781    /// `handle_datagram`/`tick_pending` and read its state directly.
3782    async fn test_core(config: HandshakeConfig) -> ListenerCore {
3783        test_core_with_channels(config).await.0
3784    }
3785
3786    /// [`test_core`] plus the live ends of its channels: the unrouted-datagram
3787    /// sender and the accepted-connection receiver.
3788    async fn test_core_with_channels(
3789        config: HandshakeConfig,
3790    ) -> (
3791        ListenerCore,
3792        mpsc::Sender<(std::net::SocketAddr, Bytes)>,
3793        mpsc::Receiver<Result<SrtSocket>>,
3794    ) {
3795        let udp = Arc::new(UdpSocket::bind("127.0.0.1:0").await.unwrap());
3796        let (unrouted_tx, unrouted_rx) = mpsc::channel(UNROUTED_CHANNEL_CAPACITY);
3797        let (accepted_tx, accepted) = mpsc::channel(ACCEPT_BACKLOG);
3798        let core = ListenerCore {
3799            udp,
3800            config,
3801            io: IoConfig::default(),
3802            cookie_keys: CookieKeys::new(Instant::now()).unwrap(),
3803            pending: std::collections::HashMap::new(),
3804            outbound_queue: std::collections::HashMap::new(),
3805            recent_accepts: std::collections::HashMap::new(),
3806            routes: Arc::new(Mutex::new(std::collections::HashMap::new())),
3807            unrouted_rx,
3808            life: std::sync::Weak::new(),
3809            accepted_tx,
3810            overflow_dropped: Arc::new(AtomicU64::new(0)),
3811            send_errors: Arc::new(AtomicU64::new(0)),
3812            accepting: true,
3813            last_pending_tick: Instant::now(),
3814        };
3815        (core, unrouted_tx, accepted)
3816    }
3817
3818    /// #2860: remembered CONCLUSION responses stay at `MAX_RECENT_ACCEPTS`
3819    /// under a flood of accepted addresses.
3820    #[tokio::test(start_paused = true)]
3821    async fn recent_accepts_stop_at_the_cap_under_a_flood() {
3822        let mut core = test_core(HandshakeConfig::default()).await;
3823        for i in 0..u32::try_from(MAX_RECENT_ACCEPTS).unwrap() + 64 {
3824            let addr = format!("127.0.0.1:{}", 10_000 + i).parse().unwrap();
3825            core.remember_accept(
3826                addr,
3827                RecentAccept {
3828                    peer_socket_id: 1,
3829                    response: alloc::vec![0u8; 4],
3830                    accepted_at: Instant::now(),
3831                },
3832            );
3833        }
3834        assert_eq!(core.recent_accepts.len(), MAX_RECENT_ACCEPTS);
3835    }
3836
3837    #[tokio::test(start_paused = true)]
3838    async fn bounded_turns_a_stuck_future_into_a_timed_out_io_error() {
3839        let r: Result<()> = bounded(
3840            Duration::from_secs(3),
3841            "send",
3842            std::future::pending::<Result<()>>(),
3843        )
3844        .await;
3845        assert!(
3846            matches!(
3847                r,
3848                Err(Error::Io {
3849                    kind: std::io::ErrorKind::TimedOut,
3850                    context: "send"
3851                })
3852            ),
3853            "{r:?}"
3854        );
3855    }
3856
3857    #[tokio::test(start_paused = true)]
3858    async fn the_configured_read_idle_replaces_the_five_second_constant() {
3859        let (mut driver, _rx) = test_driver(8192).await;
3860        driver.read_idle = Duration::from_secs(2);
3861        assert!(!driver.peer_idle(Instant::now()));
3862        tokio::time::advance(Duration::from_secs(2)).await;
3863        assert!(
3864            driver.peer_idle(Instant::now()),
3865            "idle after the configured 2 s, not 5 s"
3866        );
3867    }
3868
3869    /// Real time, real socket: a paused clock would auto-advance past the
3870    /// timers while the first `send_to` waits on the reactor.
3871    #[tokio::test]
3872    async fn the_handshake_budget_comes_from_the_config() {
3873        // black hole: bound UDP socket that never answers
3874        let hole = UdpSocket::bind("127.0.0.1:0").await.unwrap();
3875        let budget = Duration::from_millis(400);
3876        let io = IoConfig::default().with_timeouts(SRT_TIMEOUTS.with_handshake(budget));
3877        let t0 = Instant::now();
3878        let err = SrtSocket::connect(
3879            hole.local_addr().unwrap(),
3880            SrtSocketConfig::default().with_io(io),
3881        )
3882        .await
3883        .expect_err("nobody answers");
3884        // The default retransmit budget (12 x 250 ms) would end an unanswered connect at ~3 s with
3885        // stage "caller retransmit budget"; only the configured deadline yields "caller connect".
3886        assert!(
3887            matches!(
3888                err,
3889                Error::HandshakeTimedOut {
3890                    stage: "caller connect"
3891                }
3892            ),
3893            "{err:?}"
3894        );
3895        let took = Instant::now() - t0;
3896        assert!(
3897            took >= budget && took < Duration::from_secs(2),
3898            "the configured {budget:?} deadline, got {took:?}"
3899        );
3900        drop(hole);
3901    }
3902
3903    // -----------------------------------------------------------------------
3904    // Each `Driver::poll_timeout` term, with every EARLIER term pushed out of
3905    // the way, so deleting any one of them changes the asserted deadline.
3906    // -----------------------------------------------------------------------
3907
3908    async fn quiet_driver() -> Driver {
3909        let (mut driver, _rx) = test_driver(8192).await;
3910        driver.peer_addr = "127.0.0.1:1".parse().unwrap();
3911        driver
3912    }
3913
3914    /// TSBPD release: a packet due at 120 ms, the Full ACK just ticked at
3915    /// 118 ms (next ACK 128 ms), so the release is the earliest deadline.
3916    #[tokio::test(start_paused = true)]
3917    async fn the_deadline_is_the_tsbpd_release_when_it_is_the_earliest_term() {
3918        let mut driver = quiet_driver().await;
3919        driver.ingress(Bytes::from(data_bytes(0, 0, b"p"))).unwrap();
3920        tokio::time::advance(Duration::from_millis(118)).await;
3921        driver.tick_engines();
3922        assert_eq!(
3923            driver.poll_timeout().unwrap(),
3924            driver.epoch + Duration::from_millis(LATENCY_MS),
3925            "the TSBPD release must be the next wake-up"
3926        );
3927    }
3928
3929    /// With no ACK deadline left (its timestamp cannot represent another
3930    /// period), the TSBPD release alone sets the wake-up.
3931    #[tokio::test(start_paused = true)]
3932    async fn the_tsbpd_release_alone_sets_the_deadline_without_an_ack_term() {
3933        let mut driver = quiet_driver().await;
3934        let _ = driver
3935            .receiver
3936            .tick(Timestamp::from_micros(u64::MAX - 1_000));
3937        assert!(driver.receiver.next_timeout().is_none());
3938        driver.ingress(Bytes::from(data_bytes(0, 0, b"p"))).unwrap();
3939        assert_eq!(
3940            driver.poll_timeout().unwrap(),
3941            driver.epoch + Duration::from_millis(LATENCY_MS)
3942        );
3943    }
3944
3945    /// With no earlier deadline, the Keep-Alive alone sets the wake-up.
3946    #[tokio::test(start_paused = true)]
3947    async fn the_keepalive_alone_sets_the_deadline_without_an_ack_term() {
3948        let mut driver = quiet_driver().await;
3949        let _ = driver
3950            .receiver
3951            .tick(Timestamp::from_micros(u64::MAX - 1_000));
3952        assert!(driver.receiver.next_timeout().is_none());
3953        assert!(driver.outbound_control.is_empty() && driver.outbound_data.is_empty());
3954        let now = Instant::now();
3955        driver.last_tx_at = now;
3956        driver.last_rx_at = now;
3957        assert_eq!(
3958            driver.poll_timeout().unwrap(),
3959            now + KEEPALIVE_PERIOD,
3960            "the keep-alive alone must be the next wake-up"
3961        );
3962    }
3963
3964    /// Pacing: a queued DATA packet whose slot is 3 ms away beats the 10 ms ACK.
3965    #[tokio::test(start_paused = true)]
3966    async fn the_deadline_is_the_pacing_slot_when_it_is_the_earliest_term() {
3967        let mut driver = quiet_driver().await;
3968        let now = Instant::now();
3969        driver
3970            .outbound_data
3971            .push_back(OutboundData::first_transmission(alloc::vec![0u8; 100]));
3972        driver.next_data_send_at = Some(now + Duration::from_millis(3));
3973        assert_eq!(
3974            driver.poll_timeout().unwrap(),
3975            now + Duration::from_millis(3),
3976            "the pacing slot must be the next wake-up"
3977        );
3978    }
3979
3980    /// Peer idle: a 4 ms read-idle limit beats the 10 ms ACK and the 1 s keep-alive.
3981    #[tokio::test(start_paused = true)]
3982    async fn the_deadline_is_the_peer_idle_expiry_when_it_is_the_earliest_term() {
3983        let mut driver = quiet_driver().await;
3984        driver.read_idle = Duration::from_millis(4);
3985        assert_eq!(
3986            driver.poll_timeout().unwrap(),
3987            driver.last_rx_at + Duration::from_millis(4),
3988            "the peer-idle expiry must be the next wake-up"
3989        );
3990    }
3991
3992    /// Keep-Alive: nothing sent for 995 ms and nothing queued, so the keep-alive
3993    /// at +5 ms beats the 10 ms ACK.
3994    #[tokio::test(start_paused = true)]
3995    async fn the_deadline_is_the_keepalive_when_it_is_the_earliest_term() {
3996        let mut driver = quiet_driver().await;
3997        let now = Instant::now();
3998        driver.last_tx_at = now - Duration::from_millis(995);
3999        assert!(driver.outbound_control.is_empty() && driver.outbound_data.is_empty());
4000        assert_eq!(
4001            driver.poll_timeout().unwrap(),
4002            now + Duration::from_millis(5),
4003            "the keep-alive must be the next wake-up"
4004        );
4005        // ... and it is NOT a term while something is queued.
4006        driver.outbound_control.push_back(alloc::vec![0u8; 16]);
4007        assert_eq!(
4008            driver.poll_timeout().unwrap(),
4009            driver.epoch + crate::arq::FULL_ACK_PERIOD
4010        );
4011    }
4012
4013    /// Wake the loop exactly as `run` would (at `poll_timeout`) for `window`
4014    /// of virtual time, returning how many DATA packets left the queue.
4015    async fn drain_for(driver: &mut Driver, window: Duration) -> usize {
4016        let start = Instant::now();
4017        let before = driver.outbound_data.len();
4018        while Instant::now() - start < window {
4019            let at = driver.poll_timeout().unwrap();
4020            tokio::time::advance(at - Instant::now()).await;
4021            driver.tick_engines();
4022            driver.flush_outbound().await.expect("flush");
4023        }
4024        before - driver.outbound_data.len()
4025    }
4026
4027    /// A backlog with NO inbound events and no application traffic (retransmit
4028    /// burst after a NAK, idle app) drains at wake-up granularity: the old
4029    /// one-packet-per-wake ceiling was ~10.5 Mbit/s.
4030    #[tokio::test(start_paused = true)]
4031    async fn an_idle_backlog_drains_faster_than_one_packet_per_wake() {
4032        let mut driver = quiet_driver().await;
4033        for _ in 0..3000 {
4034            driver.send_one(&[0u8; 1316]);
4035        }
4036        let sent = drain_for(&mut driver, Duration::from_millis(100)).await;
4037        let mbit_s = sent as f64 * 1316.0 * 8.0 / 0.1 / 1e6;
4038        assert!(
4039            mbit_s >= 20.0,
4040            "drained {sent} packets in 100 ms = {mbit_s:.1} Mbit/s"
4041        );
4042    }
4043
4044    /// Pacing still holds with catch-up: at 2.5 MB/s (20 Mbit/s) 100 ms is ~190
4045    /// packets plus at most one burst, never an instantaneous dump.
4046    #[tokio::test(start_paused = true)]
4047    async fn catch_up_never_exceeds_the_paced_rate_by_more_than_one_burst() {
4048        let mut driver = quiet_driver().await;
4049        for _ in 0..3000 {
4050            driver.send_one(&[0u8; 1316]);
4051        }
4052        driver.livecc = LiveCC::new(MaxBwConfig::Set(2_500_000));
4053        driver.livecc.on_data_packet(1316);
4054        let sent = drain_for(&mut driver, Duration::from_millis(100)).await;
4055        let allowed = (2_500_000.0_f64 * 0.1 / 1316.0).ceil() as usize + PACING_BURST_CAP + 1;
4056        assert!(
4057            sent <= allowed,
4058            "sent {sent} packets, paced allowance {allowed}"
4059        );
4060        assert!(sent >= 100, "pacing starved the drain: {sent}");
4061    }
4062
4063    // -----------------------------------------------------------------------
4064    // Listener: the deadline wiring and send-error handling
4065    // -----------------------------------------------------------------------
4066
4067    #[tokio::test]
4068    async fn the_listener_deadline_exists_only_while_a_handshake_is_pending() {
4069        let mut core = test_core(HandshakeConfig::default()).await;
4070        assert_eq!(core.poll_timeout(), None, "an idle listener has no timer");
4071        core.handle_datagram(peer_addr(), &induction_bytes(7))
4072            .expect("induction");
4073        assert_eq!(
4074            core.poll_timeout(),
4075            None,
4076            "an INDUCTION allocates no pending handshake (#2820)"
4077        );
4078        let src = peer_addr();
4079        let conclusion = listener_conclusion(&mut core, src, 7);
4080        core.handle_datagram(src, &conclusion)
4081            .expect("cookie-validated conclusion");
4082        assert!(core.pending.contains_key(&src));
4083        assert_eq!(
4084            core.poll_timeout(),
4085            Some(core.last_pending_tick + PENDING_TICK_INTERVAL)
4086        );
4087        core.accepting = false;
4088        assert_eq!(
4089            core.poll_timeout(),
4090            None,
4091            "a handle-less core serves nobody"
4092        );
4093    }
4094
4095    /// A lost INDUCTION response is recovered by the Caller re-sending its
4096    /// INDUCTION, which the stateless listener answers identically — not by a
4097    /// listener-side retransmit tick (#2820). No pending state is created.
4098    #[tokio::test]
4099    async fn a_repeated_induction_is_answered_again_without_state() {
4100        let config = HandshakeConfig {
4101            retransmit_after: Duration::from_millis(1),
4102            max_retries: 5,
4103            ..HandshakeConfig::default()
4104        };
4105        let mut core = test_core(config).await;
4106        let src = peer_addr();
4107        let induction = induction_bytes(7);
4108
4109        core.handle_datagram(src, &induction).expect("induction");
4110        let first = core
4111            .outbound_queue
4112            .get(&src)
4113            .and_then(|queue| queue.back())
4114            .cloned()
4115            .expect("an INDUCTION response");
4116        core.handle_datagram(src, &induction).expect("repeat");
4117        let second = core
4118            .outbound_queue
4119            .get(&src)
4120            .and_then(|queue| queue.back())
4121            .cloned()
4122            .expect("the repeat is answered too");
4123        assert_eq!(first, second, "the stateless answer is identical");
4124        assert!(core.pending.is_empty(), "neither answer allocated state");
4125    }
4126
4127    /// #2820: a CONCLUSION is validated against the key that issued its
4128    /// cookie even after that key has rotated, and against the previous
4129    /// one-minute bucket.
4130    #[tokio::test(start_paused = true)]
4131    async fn a_conclusion_cookie_survives_a_key_rotation_and_a_bucket_boundary() {
4132        let mut core = test_core(HandshakeConfig::default()).await;
4133        let src = peer_addr();
4134        let peer_key = cookie_peer_key(&src, 5);
4135        let bucket = unix_time_bucket();
4136        let old_secret = core.cookie_keys.current();
4137        let old_key_cookie = derive_cookie(peer_key, bucket, old_secret);
4138
4139        core.cookie_keys.drawn_at = Instant::now() - COOKIE_KEY_ROTATION;
4140        assert!(core.cookie_keys.rotate_if_due(Instant::now()));
4141        assert_ne!(core.cookie_keys.current(), old_secret);
4142
4143        assert!(
4144            core.validated_conclusion_ids(src, 5, old_key_cookie)
4145                .is_some(),
4146            "the previous key must still validate a cookie it issued"
4147        );
4148
4149        let previous_bucket_cookie =
4150            derive_cookie(peer_key, bucket.wrapping_sub(1), core.cookie_keys.current());
4151        assert!(
4152            core.validated_conclusion_ids(src, 5, previous_bucket_cookie)
4153                .is_some(),
4154            "a cookie issued a minute ago is still within its window"
4155        );
4156
4157        let truncated = conclusion_bytes(5, 0);
4158        core.handle_datagram(src, &truncated)
4159            .expect("an unvalidated conclusion is ignored");
4160        assert!(core.pending.is_empty());
4161    }
4162
4163    /// Send errors are counted, never queued: a flood of them must not touch
4164    /// the accept queue that finished connections depend on.
4165    #[tokio::test]
4166    async fn a_flood_of_send_errors_does_not_displace_completed_connections() {
4167        let (core, _tx, mut accepted) = test_core_with_channels(HandshakeConfig::default()).await;
4168        for _ in 0..(ACCEPT_BACKLOG * 20) {
4169            core.count_send_error(Err(Error::Io {
4170                kind: std::io::ErrorKind::HostUnreachable,
4171                context: "send_to",
4172            }));
4173        }
4174        assert_eq!(
4175            core.send_errors.load(Ordering::Relaxed),
4176            (ACCEPT_BACKLOG * 20) as u64
4177        );
4178        assert_eq!(
4179            core.accepted_tx.capacity(),
4180            ACCEPT_BACKLOG,
4181            "every accept-queue slot is still free for a real connection"
4182        );
4183        assert!(accepted.try_recv().is_err());
4184    }
4185
4186    fn drain_deliveries(rx: &mut mpsc::Receiver<Bytes>) -> Vec<Bytes> {
4187        let mut out = Vec::new();
4188        while let Ok(payload) = rx.try_recv() {
4189            out.push(payload);
4190        }
4191        out
4192    }
4193
4194    // -----------------------------------------------------------------------
4195    // Item 1 — encryption in the tokio adapter
4196    // -----------------------------------------------------------------------
4197
4198    #[tokio::test]
4199    async fn encrypted_data_packet_is_never_staged_or_delivered() {
4200        let (mut driver, mut rx) = test_driver(8192).await;
4201        let ts = 0u32;
4202        // The unencrypted packet at seq 0 is staged normally.
4203        driver
4204            .ingress(Bytes::from(data_bytes(0, ts, b"plain")))
4205            .expect("ingress plain");
4206        // An encrypted packet (KK != 0) must never reach `staged` or the app.
4207        driver
4208            .ingress(Bytes::from(encrypted_data_bytes(1, ts, b"ciphertext")))
4209            .expect("ingress encrypted");
4210
4211        assert!(
4212            !driver.staged.contains_key(&1),
4213            "a KK != 0 data packet must never be staged"
4214        );
4215        let delivered = drain_deliveries(&mut rx);
4216        assert!(
4217            delivered.iter().all(|p| &p[..] != b"ciphertext"),
4218            "ciphertext must never be delivered to the application"
4219        );
4220    }
4221
4222    // -----------------------------------------------------------------------
4223    // Issue #1062 — sequence/message-number wrap must not panic
4224    // -----------------------------------------------------------------------
4225
4226    /// Pre-fix, `send_one` incremented both counters with a plain
4227    /// `u32::wrapping_add(1)` (wraps at `u32::MAX`, not the wire field's own
4228    /// bit width). Starting both counters two steps below their real 31-bit
4229    /// (sequence) / 26-bit (message number) boundaries and sending four
4230    /// packets crosses both wraps; pre-fix this panicked inside
4231    /// `DataPacket::serialize_into`'s `.expect("buffer sized from
4232    /// serialized_len")` call sites in `arq::sender` with `FieldTooWide`
4233    /// (verified via a copied pre-fix `io.rs`, `git show HEAD:srt-runtime/src/io.rs`,
4234    /// never `git stash` — shared worktree — swapped back immediately after:
4235    /// `panicked ... buffer sized from serialized_len: FieldTooWide { what:
4236    /// "Packet Sequence Number", value: 2147483648, bits: 31 }`).
4237    #[tokio::test]
4238    async fn send_one_wraps_seq_and_message_number_without_panicking() {
4239        let (mut driver, _rx) = test_driver(8192).await;
4240        driver.next_send_seq = SEQ_NUMBER_MASK - 1;
4241        driver.next_message_number = crate::packet::data::MESSAGE_NUMBER_MASK - 1;
4242
4243        // Four sends: seq goes MASK-1, MASK, 0, 1 (wrapping at 2^31); message
4244        // number goes MASK-1, MASK, 1, 2 (wrapping at 2^26 but skipping 0 —
4245        // libsrt's `SRT_MSGNO_CONTROL` sentinel, see `next_message_number`).
4246        // Each call re-derives the wire bytes through the exact
4247        // `serialize_into` path the panic was in — reaching here without
4248        // panicking is the test.
4249        for _ in 0..4 {
4250            driver.send_one(b"payload");
4251        }
4252
4253        assert_eq!(
4254            driver.next_send_seq, 2,
4255            "sequence number must wrap at 2^31, not 2^32"
4256        );
4257        assert_eq!(
4258            driver.next_message_number, 3,
4259            "message number must wrap at 2^26 (skipping 0), not 2^32"
4260        );
4261
4262        // Every enqueued DATA packet must itself carry a legal (in-range)
4263        // seq/message number — not just the counter that produced it.
4264        for datagram in &driver.outbound_data {
4265            let dp = DataPacket::parse(&datagram.bytes).expect("parse enqueued data packet");
4266            assert!(dp.seq_number <= SEQ_NUMBER_MASK);
4267            assert!(dp.message_number <= crate::packet::data::MESSAGE_NUMBER_MASK);
4268        }
4269    }
4270
4271    // -----------------------------------------------------------------------
4272    // Item 6 — ACK/NAK must not queue behind a not-yet-due paced DATA packet
4273    // -----------------------------------------------------------------------
4274
4275    /// Pre-fix, a single FIFO `outbound` queue (each item tagged `is_data`)
4276    /// meant `flush_outbound` stopped at the first not-yet-due DATA packet
4277    /// and never looked past it — so an AckAck enqueued *behind* one (the
4278    /// ordinary case: `send_one` queues DATA, then the peer's own Ack —
4279    /// handled by `ingress` — queues the reply) sat there just as
4280    /// pacing-throttled as the DATA in front of it, even though §5.1.2 paces
4281    /// DATA only.
4282    #[tokio::test]
4283    async fn ackack_is_not_queued_behind_a_not_yet_due_paced_data_packet() {
4284        let (mut driver, _rx) = test_driver(8192).await;
4285        // `flush_outbound` does a real `send_to` below — a loopback address
4286        // accepts it without needing an actual listener there, unlike
4287        // `test_driver`'s default non-routable `PEER` test address.
4288        driver.peer_addr = "127.0.0.1:1".parse().unwrap();
4289        // A near-zero bandwidth cap pushes each DATA packet's pacing slot far
4290        // into the future. The very first send establishes that pacing
4291        // schedule (there is no deadline yet before anything has been sent);
4292        // the second one is the packet this test actually checks stays
4293        // queued behind its own not-yet-arrived slot.
4294        driver.livecc = LiveCC::new(MaxBwConfig::Set(1));
4295        driver.send_one(&[0u8; 200]);
4296        driver
4297            .flush_outbound()
4298            .await
4299            .expect("flush first data packet");
4300        driver.send_one(&[0u8; 200]);
4301        assert_eq!(driver.outbound_data.len(), 1, "second DATA must be queued");
4302        assert!(
4303            driver.next_paced_send_wait().is_some(),
4304            "the second DATA packet must not be immediately due"
4305        );
4306
4307        let ack = ControlPacket::Ack(AckPacket {
4308            ack_number: crate::packet::AckNumber::from_wire(1),
4309            timestamp: crate::packet::SrtTimestamp::ZERO,
4310            dest_socket_id: crate::packet::SocketId::from_wire(1),
4311            cif: AckCif::Full {
4312                last_ack_seq: crate::packet::SeqNo::from_wire_masked(0),
4313                rtt_us: 0,
4314                rtt_var_us: 0,
4315                avail_buf_size: 8192,
4316                pkt_recv_rate: 0,
4317                est_link_capacity: 0,
4318                recv_rate_bps: 0,
4319            },
4320        });
4321        let mut ack_bytes = alloc::vec![0u8; ack.serialized_len()];
4322        ack.serialize_into(&mut ack_bytes).expect("serialize ack");
4323        driver.ingress(Bytes::from(ack_bytes)).expect("ingress ack");
4324        assert_eq!(
4325            driver.outbound_control.len(),
4326            1,
4327            "the peer's Ack must have queued exactly one AckAck"
4328        );
4329
4330        driver.flush_outbound().await.expect("flush");
4331
4332        assert!(
4333            driver.outbound_control.is_empty(),
4334            "the AckAck must have been sent even though the DATA packet's \
4335             pacing slot had not arrived yet"
4336        );
4337        assert_eq!(
4338            driver.outbound_data.len(),
4339            1,
4340            "the still-not-due DATA packet must remain queued, untouched"
4341        );
4342    }
4343
4344    // -----------------------------------------------------------------------
4345    // Item 2 — one loss must not freeze delivery or grow memory
4346    // -----------------------------------------------------------------------
4347
4348    // Paused-clock tests: `Driver` reads `tokio::time::Instant`, so
4349    // `tokio::time::advance` moves its notion of "now" exactly and instantly —
4350    // no real sleeping, no dependence on scheduler timing.
4351
4352    #[tokio::test(start_paused = true)]
4353    async fn delivery_resumes_after_permanent_loss_once_latency_passes() {
4354        let (mut driver, mut rx) = test_driver(8192).await;
4355        let ts0 = 0u32; // the driver epoch is "now" under the paused clock
4356
4357        // seq 1 is lost and never retransmitted.
4358        for seq in [0u32, 2, 3] {
4359            driver
4360                .ingress(Bytes::from(data_bytes(
4361                    seq,
4362                    ts0,
4363                    &[u8::try_from(seq).unwrap()],
4364                )))
4365                .expect("ingress");
4366        }
4367        assert!(
4368            drain_deliveries(&mut rx).is_empty(),
4369            "play time not yet due"
4370        );
4371
4372        // §4.6 / rule 21: at the successor's play time (one latency after
4373        // send) the gap is skipped and packets 2 and 3 are DELIVERED — not
4374        // thrown away with the lost packet. Step the clock like the driver's
4375        // ticker would, finishing well inside the too-late threshold window.
4376        let mut delivered = Vec::new();
4377        for _ in 0..40 {
4378            tokio::time::advance(Duration::from_millis(10)).await;
4379            driver.tick_engines();
4380            delivered.extend(drain_deliveries(&mut rx));
4381            if delivered.len() >= 3 {
4382                break;
4383            }
4384        }
4385        let seqs: Vec<u8> = delivered.iter().map(|p| p[0]).collect();
4386        assert_eq!(
4387            seqs,
4388            vec![0, 2, 3],
4389            "the gap must be skipped at the successor's play time and its \
4390             packets delivered (live mode, §4.6/rule 21)"
4391        );
4392    }
4393
4394    /// r08-SRT-W2 (adapter side): when TSBPD gives up on a packet (§4.6), the
4395    /// ARQ receiver's ack point follows it — the "fake ACK" of Too-Late
4396    /// Packet Drop. Otherwise it keeps NAKing a packet nobody will ever
4397    /// deliver, the ACKs never let the peer free anything past it, and the
4398    /// flow window it measures arrivals against stalls at the lost packet.
4399    #[tokio::test(start_paused = true)]
4400    async fn a_tsbpd_skip_advances_the_arq_ack_point() {
4401        let (mut driver, mut rx) = test_driver(8192).await;
4402        for seq in [0u32, 2, 3] {
4403            driver
4404                .ingress(Bytes::from(data_bytes(
4405                    seq,
4406                    0,
4407                    &[u8::try_from(seq).unwrap()],
4408                )))
4409                .expect("ingress");
4410        }
4411        assert_eq!(driver.receiver.ack_point(), 1, "stalled at the gap");
4412        assert_eq!(driver.receiver.loss_list_len(), 1, "seq 1 is NAKed");
4413
4414        tokio::time::advance(Duration::from_millis(130)).await;
4415        driver.tick_engines();
4416        assert_eq!(
4417            drain_deliveries(&mut rx).len(),
4418            3,
4419            "0, 2, 3 delivered once the gap is skipped"
4420        );
4421        assert_eq!(
4422            driver.stats.too_late_dropped.load(Ordering::Relaxed),
4423            1,
4424            "the skipped sequence number is reported as dropped"
4425        );
4426        assert_eq!(
4427            driver.receiver.ack_point(),
4428            4,
4429            "the ack point must move past the packet TSBPD dropped"
4430        );
4431        assert_eq!(
4432            driver.receiver.loss_list_len(),
4433            0,
4434            "a dropped packet must not stay in the loss list (it would be NAKed forever)"
4435        );
4436    }
4437
4438    /// A delivered packet's payload is a view into the received datagram's own
4439    /// allocation (header sliced off the front) — one copy from the socket
4440    /// buffer, not a second `to_vec` per packet (r08-SRT-O4). Pointer identity
4441    /// is the deterministic evidence: a copy would live at a different address.
4442    #[tokio::test(start_paused = true)]
4443    async fn delivery_reuses_the_received_datagrams_allocation() {
4444        let (mut driver, mut rx) = test_driver(8192).await;
4445        let datagram = bytes::Bytes::from(data_bytes(0, 0, b"zero-copy payload"));
4446        let allocation = datagram.as_ptr() as usize;
4447        driver.ingress(datagram).expect("ingress");
4448        tokio::time::advance(Duration::from_millis(130)).await;
4449        driver.tick_engines();
4450        let mut delivered = drain_deliveries(&mut rx);
4451        assert_eq!(delivered.len(), 1);
4452        let payload = delivered.remove(0);
4453        assert_eq!(&payload[..], b"zero-copy payload");
4454        assert_eq!(
4455            payload.as_ptr() as usize,
4456            allocation + SRT_HEADER_LEN,
4457            "the payload must be a view into the received datagram, not a copy"
4458        );
4459    }
4460
4461    #[tokio::test(start_paused = true)]
4462    async fn dropreq_unblocks_delivery_immediately() {
4463        let (mut driver, mut rx) = test_driver(8192).await;
4464        let ts0 = 0u32;
4465
4466        for seq in [0u32, 2, 3] {
4467            driver
4468                .ingress(Bytes::from(data_bytes(
4469                    seq,
4470                    ts0,
4471                    &[u8::try_from(seq).unwrap()],
4472                )))
4473                .expect("ingress");
4474        }
4475        assert!(
4476            drain_deliveries(&mut rx).is_empty(),
4477            "play time not yet due"
4478        );
4479
4480        // The peer announces it will never send seq 1.
4481        driver
4482            .ingress(Bytes::from(dropreq_bytes(1, 1)))
4483            .expect("ingress dropreq");
4484
4485        tokio::time::advance(Duration::from_millis(140)).await;
4486        driver.tick_engines();
4487
4488        let delivered = drain_deliveries(&mut rx);
4489        let seqs: Vec<u8> = delivered.iter().map(|p| p[0]).collect();
4490        assert_eq!(seqs, vec![0, 2, 3], "DROPREQ must unblock the gap");
4491    }
4492
4493    #[tokio::test(start_paused = true)]
4494    async fn dropreq_ahead_of_the_ack_point_does_not_stall_the_flow_window() {
4495        const WINDOW: u32 = 64;
4496        let (mut driver, mut rx) = test_driver(WINDOW).await;
4497        for seq in [0u32, 5] {
4498            driver
4499                .ingress(Bytes::from(data_bytes(
4500                    seq,
4501                    0,
4502                    &[u8::try_from(seq).unwrap()],
4503                )))
4504                .expect("ingress");
4505        }
4506        driver
4507            .ingress(Bytes::from(dropreq_bytes(3, 4)))
4508            .expect("ingress dropreq");
4509        for seq in [1u32, 2] {
4510            driver
4511                .ingress(Bytes::from(data_bytes(
4512                    seq,
4513                    0,
4514                    &[u8::try_from(seq).unwrap()],
4515                )))
4516                .expect("ingress");
4517        }
4518        tokio::time::advance(Duration::from_millis(130)).await;
4519        driver.tick_engines();
4520        let first: Vec<u8> = drain_deliveries(&mut rx).iter().map(|p| p[0]).collect();
4521        assert_eq!(first, vec![0, 1, 2, 5]);
4522
4523        let far = 3 + WINDOW + 1;
4524        for seq in 6..=far {
4525            driver
4526                .ingress(Bytes::from(data_bytes(
4527                    seq,
4528                    130_000,
4529                    &[u8::try_from(seq).unwrap()],
4530                )))
4531                .expect("ingress");
4532        }
4533        tokio::time::advance(Duration::from_millis(130)).await;
4534        driver.tick_engines();
4535        let second: Vec<u8> = drain_deliveries(&mut rx).iter().map(|p| p[0]).collect();
4536        let expected: Vec<u8> = (6..=far).map(|s| u8::try_from(s).unwrap()).collect();
4537        assert_eq!(
4538            second,
4539            expected,
4540            "ARQ ack point stuck at {} while TSBPD cursor is at {}",
4541            driver.receiver.ack_point(),
4542            driver.tsbpd.next_release()
4543        );
4544    }
4545
4546    #[tokio::test(start_paused = true)]
4547    async fn a_dropreq_wider_than_the_flow_window_is_ignored_by_the_driver() {
4548        const WINDOW: u32 = 64;
4549        let (mut driver, mut rx) = test_driver(WINDOW).await;
4550        driver
4551            .ingress(Bytes::from(data_bytes(0, 0, &[0])))
4552            .expect("ingress");
4553        driver
4554            .ingress(Bytes::from(dropreq_bytes(1, 0x3FFF_FFFF)))
4555            .expect("ingress dropreq");
4556        driver
4557            .ingress(Bytes::from(data_bytes(1, 0, &[1])))
4558            .expect("ingress");
4559        tokio::time::advance(Duration::from_millis(130)).await;
4560        driver.tick_engines();
4561        let delivered: Vec<u8> = drain_deliveries(&mut rx).iter().map(|p| p[0]).collect();
4562        assert_eq!(delivered, vec![0, 1]);
4563        assert_eq!(driver.receiver.ack_point(), 2);
4564        assert_eq!(driver.tsbpd.next_release(), 2);
4565    }
4566
4567    #[cfg(feature = "crypto")]
4568    #[tokio::test]
4569    async fn km_refresh_with_both_keys_installs_both_parities() {
4570        let (mut driver, _rx) = test_driver(8192).await;
4571        driver.crypto_passphrase = b"audit-d-passphrase".to_vec().into();
4572        let salt = [0x5Au8; crate::crypto::SALT_LEN];
4573        let (even, odd) = ([0x11u8; 16], [0x22u8; 16]);
4574        let kek = crate::crypto::derive_kek(&driver.crypto_passphrase, &salt, 16).unwrap();
4575        let mut both = even.to_vec();
4576        both.extend_from_slice(&odd);
4577        let (icv, wrapped) = crate::crypto::wrap_sek(&kek, &both).unwrap();
4578        let km = crate::packet::KeyMaterial {
4579            kk: crate::packet::KmKeyFlag::Both,
4580            keki: 0,
4581            cipher: crate::packet::Cipher::AesCtr,
4582            auth: crate::packet::KmAuth::None,
4583            se: crate::packet::StreamEncapsulation::MpegTsSrt,
4584            salt: &salt,
4585            icv,
4586            x_sek: &wrapped[..16],
4587            o_sek: Some(&wrapped[16..]),
4588        };
4589        let mut km_buf = vec![0u8; km.serialized_len()];
4590        km.serialize_into(&mut km_buf).unwrap();
4591        let ud = ControlPacket::UserDefined(crate::packet::UserDefinedPacket {
4592            control_type: crate::packet::ControlType::UserDefined.to_bits(),
4593            subtype: crate::packet::handshake::EXT_TYPE_KMREQ,
4594            type_specific_info: 0,
4595            timestamp: crate::packet::SrtTimestamp::ZERO,
4596            dest_socket_id: crate::packet::SocketId::from_wire(1),
4597            cif: &km_buf,
4598        });
4599        let mut out = vec![0u8; ud.serialized_len()];
4600        ud.serialize_into(&mut out).unwrap();
4601        driver.ingress(Bytes::from(out)).expect("ingress KM");
4602        assert!(
4603            driver.rx_keys.even.is_some() && driver.rx_keys.odd.is_some(),
4604            "KK=Both carries both SEKs: even installed = {}, odd installed = {}",
4605            driver.rx_keys.even.is_some(),
4606            driver.rx_keys.odd.is_some()
4607        );
4608    }
4609
4610    #[cfg(feature = "crypto")]
4611    fn refresh_test_thresholds() -> crate::km_refresh::KmRefreshThresholds {
4612        crate::km_refresh::KmRefreshThresholds::new(20, 5).unwrap()
4613    }
4614
4615    /// #2840: a peer re-sending the same Key Material message back to back
4616    /// gets one answer, not one PBKDF2 run per datagram; a repeat after the
4617    /// interval is answered from the KEK cache instead of deriving again.
4618    #[cfg(feature = "crypto")]
4619    #[tokio::test(start_paused = true)]
4620    async fn repeat_kmreq_is_rate_limited_and_reuses_the_kek() {
4621        let (mut driver, _rx) = test_driver(8192).await;
4622        driver.crypto_passphrase = b"rate-limit-passphrase".to_vec().into();
4623        let salt = [0x6Bu8; crate::crypto::SALT_LEN];
4624        let sek = [0x5Au8; 16];
4625        let kek = crate::crypto::derive_kek(&driver.crypto_passphrase, &salt, sek.len()).unwrap();
4626        let (icv, wrapped) = crate::crypto::wrap_sek(&kek, &sek).unwrap();
4627        let km = crate::packet::KeyMaterial {
4628            kk: crate::packet::KmKeyFlag::Even,
4629            keki: 0,
4630            cipher: crate::packet::Cipher::AesCtr,
4631            auth: crate::packet::KmAuth::None,
4632            se: crate::packet::StreamEncapsulation::MpegTsSrt,
4633            salt: &salt,
4634            icv,
4635            x_sek: &wrapped,
4636            o_sek: None,
4637        };
4638        let mut km_buf = vec![0u8; km.serialized_len()];
4639        km.serialize_into(&mut km_buf).unwrap();
4640        let ud = ControlPacket::UserDefined(crate::packet::UserDefinedPacket {
4641            control_type: crate::packet::ControlType::UserDefined.to_bits(),
4642            subtype: crate::packet::handshake::EXT_TYPE_KMREQ,
4643            type_specific_info: 0,
4644            timestamp: crate::packet::SrtTimestamp::ZERO,
4645            dest_socket_id: crate::packet::SocketId::from_wire(1),
4646            cif: &km_buf,
4647        });
4648        let mut request = vec![0u8; ud.serialized_len()];
4649        ud.serialize_into(&mut request).unwrap();
4650
4651        driver
4652            .ingress(Bytes::from(request.clone()))
4653            .expect("ingress");
4654        assert_eq!(driver.outbound_control.len(), 1, "first KMREQ answered");
4655        assert_eq!(driver.kek_cache.derivations(), 1);
4656        assert!(driver.rx_keys.even.is_some());
4657
4658        driver.outbound_control.clear();
4659        driver
4660            .ingress(Bytes::from(request.clone()))
4661            .expect("ingress");
4662        assert!(
4663            driver.outbound_control.is_empty(),
4664            "a repeat inside KMREQ_MIN_INTERVAL must be dropped"
4665        );
4666        assert_eq!(driver.kek_cache.derivations(), 1, "no derivation on a drop");
4667
4668        tokio::time::advance(KMREQ_MIN_INTERVAL).await;
4669        driver.ingress(Bytes::from(request)).expect("ingress");
4670        assert_eq!(
4671            driver.outbound_control.len(),
4672            1,
4673            "after the interval: answered"
4674        );
4675        assert_eq!(
4676            driver.kek_cache.derivations(),
4677            1,
4678            "the same Salt and KLen must reuse the derived KEK"
4679        );
4680    }
4681
4682    #[cfg(feature = "crypto")]
4683    async fn encrypted_pair() -> (Driver, mpsc::Receiver<Bytes>, Driver, mpsc::Receiver<Bytes>) {
4684        let (mut a, a_rx) = test_driver(8192).await;
4685        let (mut b, b_rx) = test_driver(8192).await;
4686        let salt = [0x3Cu8; crate::crypto::SALT_LEN];
4687        let sek = vec![0x42u8; 16];
4688        for d in [&mut a, &mut b] {
4689            d.crypto_passphrase = b"refresh-passphrase".to_vec().into();
4690            d.crypto_key_len = sek.len();
4691            d.tx_keys.install(KeyParity::Even, sek.clone(), salt);
4692            d.rx_keys.install(KeyParity::Even, sek.clone(), salt);
4693            d.km_refresh =
4694                crate::km_refresh::KmRefreshDriver::new(refresh_test_thresholds(), KeyParity::Even);
4695        }
4696        (a, a_rx, b, b_rx)
4697    }
4698
4699    #[cfg(feature = "crypto")]
4700    fn is_kmreq(datagram: &[u8]) -> bool {
4701        matches!(
4702            SrtPacket::parse(datagram),
4703            Ok(SrtPacket::Control(ControlPacket::UserDefined(u)))
4704                if u.subtype == crate::packet::handshake::EXT_TYPE_KMREQ
4705        )
4706    }
4707
4708    #[cfg(feature = "crypto")]
4709    fn pump(from: &mut Driver, to: &mut Driver, kmreqs_to_drop: &mut usize) {
4710        let datagrams: Vec<Vec<u8>> = from
4711            .outbound_control
4712            .drain(..)
4713            .chain(from.outbound_data.drain(..).map(|d| d.bytes))
4714            .collect();
4715        for datagram in datagrams {
4716            if is_kmreq(&datagram) && *kmreqs_to_drop > 0 {
4717                *kmreqs_to_drop -= 1;
4718                continue;
4719            }
4720            to.ingress(Bytes::from(datagram)).expect("ingress");
4721        }
4722    }
4723
4724    #[cfg(feature = "crypto")]
4725    const REFRESH_TEST_PACKETS: u8 = 100;
4726    #[cfg(feature = "crypto")]
4727    const DRAIN_STEPS: u8 = 10;
4728    #[cfg(feature = "crypto")]
4729    const REFRESH_TEST_STEP: Duration = Duration::from_millis(20);
4730
4731    #[cfg(feature = "crypto")]
4732    fn payloads(rx: &mut mpsc::Receiver<Bytes>) -> Vec<u8> {
4733        drain_deliveries(rx).iter().map(|p| p[0]).collect()
4734    }
4735
4736    #[cfg(feature = "crypto")]
4737    #[tokio::test(start_paused = true)]
4738    async fn a_lost_refresh_kmreq_is_resent_and_no_data_is_lost_across_the_switchover() {
4739        let (mut a, _a_rx, mut b, mut b_rx) = encrypted_pair().await;
4740        let mut kmreqs_to_drop = 1;
4741        let mut no_drop = 0;
4742        let mut delivered = Vec::new();
4743        for i in 0..REFRESH_TEST_PACKETS + DRAIN_STEPS {
4744            if i < REFRESH_TEST_PACKETS {
4745                a.send_one(&[i]);
4746            }
4747            pump(&mut a, &mut b, &mut kmreqs_to_drop);
4748            pump(&mut b, &mut a, &mut no_drop);
4749            tokio::time::advance(REFRESH_TEST_STEP).await;
4750            a.tick_engines();
4751            b.tick_engines();
4752            delivered.extend(payloads(&mut b_rx));
4753        }
4754        assert_eq!(kmreqs_to_drop, 0, "the first KMREQ was dropped");
4755        assert_eq!(
4756            delivered,
4757            (0..REFRESH_TEST_PACKETS).collect::<Vec<u8>>(),
4758            "every packet across the refresh is delivered and decrypted"
4759        );
4760        assert_eq!(a.tx_parity, KeyParity::Odd, "the switchover happened");
4761        assert!(a.km_pending.is_none(), "the KMRSP confirmed the refresh");
4762    }
4763
4764    #[cfg(feature = "crypto")]
4765    #[tokio::test(start_paused = true)]
4766    async fn the_sender_keeps_the_old_key_while_the_refresh_is_unconfirmed() {
4767        let (mut a, _a_rx, mut b, mut b_rx) = encrypted_pair().await;
4768        let mut kmreqs_to_drop = usize::MAX;
4769        let mut no_drop = 0;
4770        let mut delivered = Vec::new();
4771        for i in 0..REFRESH_TEST_PACKETS + DRAIN_STEPS {
4772            if i < REFRESH_TEST_PACKETS {
4773                a.send_one(&[i]);
4774            }
4775            pump(&mut a, &mut b, &mut kmreqs_to_drop);
4776            pump(&mut b, &mut a, &mut no_drop);
4777            tokio::time::advance(REFRESH_TEST_STEP).await;
4778            a.tick_engines();
4779            b.tick_engines();
4780            delivered.extend(payloads(&mut b_rx));
4781        }
4782        assert_eq!(a.tx_parity, KeyParity::Even, "no KMRSP, no switch");
4783        assert!(a.km_pending.is_some());
4784        assert_eq!(
4785            delivered,
4786            (0..REFRESH_TEST_PACKETS).collect::<Vec<u8>>(),
4787            "traffic under the old key keeps flowing while the refresh is unconfirmed"
4788        );
4789    }
4790
4791    #[cfg(feature = "crypto")]
4792    #[tokio::test(start_paused = true)]
4793    async fn both_directions_refreshing_together_keep_decrypting() {
4794        let (mut a, mut a_rx, mut b, mut b_rx) = encrypted_pair().await;
4795        let mut no_drop = 0;
4796        let mut from_a = Vec::new();
4797        let mut from_b = Vec::new();
4798        for i in 0..REFRESH_TEST_PACKETS + DRAIN_STEPS {
4799            if i < REFRESH_TEST_PACKETS {
4800                a.send_one(&[i]);
4801                b.send_one(&[i]);
4802            }
4803            pump(&mut a, &mut b, &mut no_drop);
4804            pump(&mut b, &mut a, &mut no_drop);
4805            tokio::time::advance(REFRESH_TEST_STEP).await;
4806            a.tick_engines();
4807            b.tick_engines();
4808            from_a.extend(payloads(&mut b_rx));
4809            from_b.extend(payloads(&mut a_rx));
4810        }
4811        let expected: Vec<u8> = (0..REFRESH_TEST_PACKETS).collect();
4812        assert_eq!(from_a, expected, "A to B survives both sides refreshing");
4813        assert_eq!(from_b, expected, "B to A survives both sides refreshing");
4814        assert_eq!(a.tx_parity, KeyParity::Odd);
4815        assert_eq!(b.tx_parity, KeyParity::Odd);
4816    }
4817
4818    #[tokio::test]
4819    async fn staged_never_exceeds_the_flow_window() {
4820        const WINDOW: u32 = 64;
4821        let (mut driver, mut rx) = test_driver(WINDOW).await;
4822        let ts = 0u32;
4823
4824        // seq 0 is the delivery cursor and never arrives; feed window+100
4825        // packets past the gap.
4826        for seq in 1..=(WINDOW + 100) {
4827            driver
4828                .ingress(Bytes::from(data_bytes(
4829                    seq,
4830                    ts,
4831                    &[u8::try_from(seq).unwrap()],
4832                )))
4833                .expect("ingress");
4834            assert!(
4835                driver.staged.len() <= usize::try_from(WINDOW).unwrap(),
4836                "staged grew to {} past a gap (window {WINDOW})",
4837                driver.staged.len()
4838            );
4839        }
4840        drain_deliveries(&mut rx);
4841    }
4842
4843    // -----------------------------------------------------------------------
4844    // Item 3 — bound listener pending state
4845    // -----------------------------------------------------------------------
4846
4847    #[tokio::test]
4848    async fn listener_pending_is_capped_under_a_source_flood() {
4849        let mut listener = test_core(HandshakeConfig::default()).await;
4850
4851        for i in 0..5000u32 {
4852            let src = std::net::SocketAddr::from(([198, 18, (i >> 8) as u8, i as u8], 40_000));
4853            let _ = listener.handle_datagram(src, &induction_bytes(i));
4854        }
4855
4856        assert!(
4857            listener.pending.len() <= 1024,
4858            "pending grew to {} — must be capped at MAX_PENDING",
4859            listener.pending.len()
4860        );
4861        assert_eq!(
4862            listener.pending.len(),
4863            0,
4864            "a spoofed INDUCTION flood must allocate no handshake state (#2820)"
4865        );
4866    }
4867
4868    #[tokio::test]
4869    async fn stray_conclusions_do_not_hold_listener_handshake_slots() {
4870        let mut listener = test_core(HandshakeConfig::default()).await;
4871        // Cookie 0 is never issued (`derive_cookie` forces the low bit), so a
4872        // CONCLUSION carrying it must allocate nothing.
4873        let stray = conclusion_bytes(5, 0);
4874        for i in 0..2000u32 {
4875            let src = std::net::SocketAddr::from(([198, 18, (i >> 8) as u8, i as u8], 40_000));
4876            let _ = listener.handle_datagram(src, &stray);
4877        }
4878        for _ in 0..1000 {
4879            listener.tick_pending();
4880        }
4881        assert_eq!(
4882            listener.pending.len(),
4883            0,
4884            "stray CONCLUSIONs left {} handshake slots allocated for good",
4885            listener.pending.len()
4886        );
4887        let honest = std::net::SocketAddr::from(([203, 0, 113, 9], 4000));
4888        let conclusion = listener_conclusion(&mut listener, honest, 7);
4889        listener
4890            .handle_datagram(honest, &conclusion)
4891            .expect("an honest caller");
4892        assert!(listener.pending.contains_key(&honest));
4893    }
4894
4895    #[tokio::test(start_paused = true)]
4896    async fn pending_entries_expire_while_other_sources_keep_sending() {
4897        let config = HandshakeConfig {
4898            retransmit_after: Duration::from_millis(1),
4899            max_retries: 2,
4900            ..HandshakeConfig::default()
4901        };
4902        let mut listener = test_core(config).await;
4903
4904        // A handshake left awaiting its CONCLUSION — the same state a
4905        // validated CONCLUSION's allocation passes through — stalled by
4906        // inserting it directly (no public path leaves it there).
4907        let stalling_src = std::net::SocketAddr::from(([203, 0, 113, 1], 1234));
4908        let peer_key = addr_to_u64(&stalling_src);
4909        let bucket = unix_time_bucket();
4910        let secret = listener.cookie_keys.current();
4911        let cookie = derive_cookie(peer_key, bucket, secret);
4912        let (own_socket_id, our_initial_seq) = listener.connection_ids(peer_key, bucket, secret);
4913        let mut stalled_config = listener.config.clone();
4914        stalled_config.initial_seq_number = our_initial_seq;
4915        listener.pending.insert(
4916            stalling_src,
4917            PendingListener {
4918                handshake: ListenerHandshake::awaiting_conclusion(
4919                    own_socket_id,
4920                    cookie,
4921                    stalled_config,
4922                ),
4923                params: None,
4924                peer_initial_seq: 0,
4925                peer_timestamp_us: 0,
4926                concluded_at: None,
4927                created_at: Instant::now(),
4928                last_response: None,
4929                our_initial_seq,
4930            },
4931        );
4932
4933        // Continuous traffic from *other* sources must not keep the stalling
4934        // entry alive: the timer-driven tick expires it.
4935        for i in 0..10u32 {
4936            let src = std::net::SocketAddr::from(([198, 51, (i >> 8) as u8, i as u8], 40_000));
4937            let _ = listener.handle_datagram(src, &induction_bytes(100 + i));
4938            tokio::time::advance(Duration::from_millis(10)).await;
4939            listener.tick_pending();
4940        }
4941
4942        assert!(
4943            !listener.pending.contains_key(&stalling_src),
4944            "a stalled handshake must expire even under continuous traffic"
4945        );
4946    }
4947
4948    // -----------------------------------------------------------------------
4949    // Item 2 (BLOCKER) — dropping an accepted socket must not leak its route
4950    // -----------------------------------------------------------------------
4951
4952    /// Pre-fix, `Driver::run`'s route-table cleanup sat at the tail of its
4953    /// `loop`, reached only on a *normal* exit — `SrtSocket::Drop` instead
4954    /// calls `handle.abort()`, which cancels the task at its next await point
4955    /// and drops its future (the `Driver` included) without ever running
4956    /// that inline code. The entry then sat in `routes` forever: a harmless
4957    /// no-op for the new ID-keyed demux's correctness (a stale entry's key is
4958    /// a dead Socket ID no live peer packet names), but an unbounded
4959    /// per-listener memory leak across repeated accept/drop cycles.
4960    /// `RouteCleanup`'s `Drop` impl runs on both an abort and a normal
4961    /// return, since it fires whenever the guard itself — owned by the
4962    /// `Driver`, and so by the task's future — is dropped.
4963    #[tokio::test]
4964    async fn dropping_an_accepted_socket_removes_its_route_entry() {
4965        let mut listener = SrtListener::bind(
4966            "127.0.0.1:0",
4967            SrtSocketConfig::new(HandshakeConfig::default()),
4968        )
4969        .await
4970        .expect("bind");
4971        let listener_addr = listener.local_addr().expect("local addr");
4972
4973        let accept_jh = tokio::spawn(async move {
4974            let s = listener.accept().await.expect("accept");
4975            (listener, s)
4976        });
4977        let caller = SrtSocket::connect(
4978            listener_addr,
4979            SrtSocketConfig::new(HandshakeConfig::default()),
4980        )
4981        .await
4982        .expect("connect");
4983        let (listener, accepted) = accept_jh.await.expect("join accept");
4984
4985        assert_eq!(
4986            lock(&listener.routes).len(),
4987            1,
4988            "the freshly accepted connection must have registered exactly one route"
4989        );
4990
4991        drop(accepted); // SrtSocket::Drop aborts the driver task.
4992        drop(caller);
4993
4994        // The abort is not synchronous with `drop` — the aborted task's
4995        // `Drop` impls (including `RouteCleanup`) run at the task's own next
4996        // poll. Yield to the (current-thread) runtime until it has had that
4997        // poll; no wall-clock sleep, bounded by an iteration count.
4998        let mut cleaned = false;
4999        for _ in 0..1_000 {
5000            tokio::task::yield_now().await;
5001            if lock(&listener.routes).is_empty() {
5002                cleaned = true;
5003                break;
5004            }
5005        }
5006        assert!(
5007            cleaned,
5008            "route table still has {} entries after the accepted socket was \
5009             dropped — the route leaked (pre-fix: `Driver::run`'s cleanup only \
5010             ran on a normal loop exit, never on `SrtSocket::Drop`'s task abort)",
5011            lock(&listener.routes).len()
5012        );
5013    }
5014
5015    // -----------------------------------------------------------------------
5016    // r08-SRT-W6 — liveness: keep-alive, idle timeout, bounded send buffer
5017    // -----------------------------------------------------------------------
5018
5019    fn control_kinds(driver: &Driver) -> Vec<&'static str> {
5020        driver
5021            .outbound_control
5022            .iter()
5023            .map(|b| match ControlPacket::parse(b).expect("control packet") {
5024                ControlPacket::KeepAlive(_) => "keepalive",
5025                ControlPacket::Ack(_) => "ack",
5026                ControlPacket::Nak(_) => "nak",
5027                ControlPacket::AckAck(_) => "ackack",
5028                _ => "other",
5029            })
5030            .collect()
5031    }
5032
5033    fn keepalive_bytes() -> Vec<u8> {
5034        let ka = ControlPacket::KeepAlive(KeepAlivePacket {
5035            timestamp: crate::packet::SrtTimestamp::ZERO,
5036            dest_socket_id: crate::packet::SocketId::from_wire(1),
5037            libsrt_pad: true,
5038        });
5039        let mut buf = alloc::vec![0u8; ka.serialized_len()];
5040        ka.serialize_into(&mut buf).expect("serialize keepalive");
5041        buf
5042    }
5043
5044    /// A connection that has sent nothing for [`KEEPALIVE_PERIOD`] (§3.2.3:
5045    /// one second) queues a Keep-Alive — not a millisecond earlier — and the
5046    /// timer restarts from the last packet actually sent.
5047    #[tokio::test(start_paused = true)]
5048    async fn an_idle_connection_sends_a_keepalive_after_one_second() {
5049        let (mut driver, _rx) = test_driver(8192).await;
5050        // A loopback address accepts the real `send_to` in `flush_outbound`.
5051        driver.peer_addr = "127.0.0.1:1".parse().unwrap();
5052
5053        tokio::time::advance(KEEPALIVE_PERIOD - Duration::from_millis(1)).await;
5054        driver.tick_engines();
5055        assert!(
5056            !control_kinds(&driver).contains(&"keepalive"),
5057            "no Keep-Alive before a full idle second: {:?}",
5058            control_kinds(&driver)
5059        );
5060        driver.outbound_control.clear();
5061
5062        tokio::time::advance(Duration::from_millis(1)).await;
5063        driver.tick_engines();
5064        assert_eq!(
5065            control_kinds(&driver)
5066                .iter()
5067                .filter(|k| **k == "keepalive")
5068                .count(),
5069            1,
5070            "exactly one Keep-Alive once the second has elapsed: {:?}",
5071            control_kinds(&driver)
5072        );
5073        let ka = driver
5074            .outbound_control
5075            .iter()
5076            .find_map(|b| match ControlPacket::parse(b) {
5077                Ok(ControlPacket::KeepAlive(ka)) => Some(ka),
5078                _ => None,
5079            })
5080            .expect("keepalive");
5081        assert_eq!(
5082            ka.dest_socket_id,
5083            crate::packet::SocketId::from_wire(1),
5084            "addressed to the peer's socket id"
5085        );
5086
5087        // Sending it restarts the idle clock: half a second later, no more.
5088        driver.flush_outbound().await.expect("flush");
5089        tokio::time::advance(KEEPALIVE_PERIOD / 2).await;
5090        driver.tick_engines();
5091        assert!(!control_kinds(&driver).contains(&"keepalive"));
5092    }
5093
5094    /// Traffic in *either* direction counts: a connection that is sending data
5095    /// is not idle, so no Keep-Alive is added on top.
5096    #[tokio::test(start_paused = true)]
5097    async fn queued_data_suppresses_the_keepalive() {
5098        let (mut driver, _rx) = test_driver(8192).await;
5099        tokio::time::advance(KEEPALIVE_PERIOD).await;
5100        driver.send_one(b"payload");
5101        driver.tick_engines();
5102        assert!(!control_kinds(&driver).contains(&"keepalive"));
5103    }
5104
5105    /// A received Keep-Alive only proves the peer is alive: it is not
5106    /// answered. (It used to be echoed; with each side now sending its own
5107    /// Keep-Alives, two adapters would bounce one back and forth forever.)
5108    #[tokio::test(start_paused = true)]
5109    async fn a_received_keepalive_is_not_answered() {
5110        let (mut driver, _rx) = test_driver(8192).await;
5111        driver
5112            .ingress(Bytes::from(keepalive_bytes()))
5113            .expect("ingress");
5114        assert!(
5115            driver.outbound_control.is_empty(),
5116            "a Keep-Alive must not be echoed: {:?}",
5117            control_kinds(&driver)
5118        );
5119        assert!(!driver.peer_shutdown);
5120    }
5121
5122    /// Five silent seconds (any packet resets it) end the connection.
5123    #[tokio::test(start_paused = true)]
5124    async fn the_peer_idle_timeout_is_five_silent_seconds() {
5125        let (mut driver, _rx) = test_driver(8192).await;
5126        // The default (libsrt's SRTO_PEERIDLETIMEO) is five seconds.
5127        const PEER_IDLE_TIMEOUT: Duration = Duration::from_secs(5);
5128        assert_eq!(IoConfig::default().timeouts.read_idle, PEER_IDLE_TIMEOUT);
5129        tokio::time::advance(PEER_IDLE_TIMEOUT - Duration::from_millis(1)).await;
5130        assert!(!driver.peer_idle(Instant::now()));
5131        tokio::time::advance(Duration::from_millis(1)).await;
5132        assert!(driver.peer_idle(Instant::now()));
5133
5134        // Any datagram from the peer — even a Keep-Alive — resets it.
5135        driver
5136            .ingress(Bytes::from(keepalive_bytes()))
5137            .expect("ingress");
5138        assert!(!driver.peer_idle(Instant::now()));
5139        tokio::time::advance(PEER_IDLE_TIMEOUT - Duration::from_millis(1)).await;
5140        assert!(!driver.peer_idle(Instant::now()));
5141    }
5142
5143    /// The sender never holds more than a flow window of unacknowledged
5144    /// packets: the window closes when full and reopens when an ACK frees it.
5145    #[tokio::test]
5146    async fn the_send_window_closes_when_a_full_window_is_unacknowledged() {
5147        const WINDOW: u32 = 8;
5148        let (mut driver, _rx) = test_driver(WINDOW).await;
5149        for sent in 0..WINDOW {
5150            assert!(driver.send_window_open(), "open after {sent} sends");
5151            driver.send_one(b"x");
5152        }
5153        assert!(!driver.send_window_open(), "a full window closes it");
5154
5155        let ack = ControlPacket::Ack(AckPacket {
5156            ack_number: crate::packet::AckNumber::ZERO,
5157            timestamp: crate::packet::SrtTimestamp::ZERO,
5158            dest_socket_id: crate::packet::SocketId::from_wire(1),
5159            cif: AckCif::Light {
5160                last_ack_seq: crate::packet::SeqNo::from_wire_masked(driver.next_send_seq),
5161            },
5162        });
5163        let mut ack_bytes = alloc::vec![0u8; ack.serialized_len()];
5164        ack.serialize_into(&mut ack_bytes).expect("serialize ack");
5165        driver.ingress(Bytes::from(ack_bytes)).expect("ingress ack");
5166        assert!(driver.send_window_open(), "the ACK freed the window");
5167    }
5168
5169    /// `Driver::run` honours the window: with a peer that never acknowledges
5170    /// anything, only one flow window of the application's payloads is ever
5171    /// taken off the hand-off channel; the rest wait in it (where
5172    /// `SrtSocket::send` would block) instead of growing the send buffer.
5173    #[tokio::test(start_paused = true)]
5174    async fn run_stops_taking_app_payloads_once_the_window_is_full() {
5175        const WINDOW: u32 = 8;
5176        const QUEUED: usize = 24;
5177        let (mut driver, _rx, _datagrams) = test_driver_with_ingress(WINDOW).await;
5178        driver.peer_addr = "127.0.0.1:1".parse().unwrap();
5179        let (app_tx, app_rx) = mpsc::channel::<Bytes>(SEND_CHANNEL_CAPACITY);
5180        for _ in 0..QUEUED {
5181            app_tx
5182                .try_send(Bytes::from(alloc::vec![0u8; 100]))
5183                .expect("queue payload");
5184        }
5185        let handle = tokio::spawn(driver.run(app_rx));
5186        // Well inside the idle timeout, step the driver's clock a while.
5187        for _ in 0..50 {
5188            tokio::time::advance(Duration::from_millis(10)).await;
5189            tokio::task::yield_now().await;
5190        }
5191        let still_queued = app_tx.max_capacity() - app_tx.capacity();
5192        assert_eq!(
5193            still_queued,
5194            QUEUED - usize::try_from(WINDOW).unwrap(),
5195            "the driver must stop draining at one flow window"
5196        );
5197        handle.abort();
5198    }
5199
5200    // -----------------------------------------------------------------------
5201    // r08-SRT-W12 — typed errors
5202    // -----------------------------------------------------------------------
5203
5204    /// A datagram that is not an SRT packet is reported with its stage and
5205    /// the underlying codec error, not flattened to a generic invalid field.
5206    #[tokio::test]
5207    async fn listener_parse_failure_keeps_its_stage_and_cause() {
5208        let mut listener = test_core(HandshakeConfig::default()).await;
5209        let err = listener
5210            .handle_datagram(peer_addr(), &[0u8; 4])
5211            .expect_err("a 4-byte datagram is not an SRT packet");
5212        let Error::Handshake { stage, source } = err else {
5213            panic!("expected Error::Handshake, got {err:?}");
5214        };
5215        assert_eq!(stage, "parse");
5216        assert!(
5217            matches!(
5218                *source,
5219                Error::BufferTooShort(BufferTooShort { have: 4, .. })
5220            ),
5221            "the cause must be preserved, got {source:?}"
5222        );
5223    }
5224
5225    /// A rejection the engine produces surfaces as `Error::Rejected` with the
5226    /// reason — a feed after the handshake already finished is the engine's
5227    /// own out-of-sequence error, wrapped with its stage.
5228    #[tokio::test]
5229    async fn listener_feed_failure_is_wrapped_with_the_engine_error() {
5230        let mut listener = test_core(HandshakeConfig::default()).await;
5231        let src = peer_addr();
5232        let conclusion = listener_conclusion(&mut listener, src, 7);
5233        listener
5234            .handle_datagram(src, &conclusion)
5235            .expect("a cookie-validated conclusion completes the handshake");
5236        // A CONCLUSION from a different Caller Socket ID after this one
5237        // connected is out of sequence for the engine.
5238        let err = listener
5239            .handle_datagram(src, &conclusion_bytes(9, 0))
5240            .expect_err("a stray CONCLUSION on a connected entry");
5241        let Error::Handshake { stage, source } = err else {
5242            panic!("expected Error::Handshake, got {err:?}");
5243        };
5244        assert_eq!(stage, "listener feed");
5245        assert!(matches!(*source, Error::HandshakeOutOfSequence { .. }));
5246    }
5247
5248    // -----------------------------------------------------------------------
5249    // #1134 — a poisoned lock must not cascade
5250    // -----------------------------------------------------------------------
5251
5252    /// A connection task that panics while holding the route table's lock
5253    /// poisons it. Dropping a `RouteCleanup` (it runs in `Drop`, including
5254    /// while unwinding) and the routing pump's lookups must keep working, not
5255    /// panic a second time.
5256    #[test]
5257    fn a_poisoned_route_table_does_not_panic_the_cleanup_guard() {
5258        let routes: RouteTable = Arc::new(Mutex::new(std::collections::HashMap::new()));
5259        {
5260            let routes = Arc::clone(&routes);
5261            let panicked = std::thread::spawn(move || {
5262                let _held = routes.lock().expect("lock");
5263                panic!("a connection task panicked holding the route table lock");
5264            })
5265            .join();
5266            assert!(panicked.is_err());
5267        }
5268        assert!(routes.is_poisoned(), "the lock must really be poisoned");
5269
5270        let (tx, _rx) = mpsc::channel(1);
5271        lock(&routes).insert(
5272            7,
5273            RouteEntry {
5274                addr: peer_addr(),
5275                tx,
5276                stats: Arc::new(Counters::default()),
5277            },
5278        );
5279        assert_eq!(lock(&routes).len(), 1);
5280        drop(RouteCleanup(Some((7, Arc::clone(&routes)))));
5281        assert!(
5282            lock(&routes).is_empty(),
5283            "the guard must still remove its entry"
5284        );
5285    }
5286
5287    // -----------------------------------------------------------------------
5288    // r08-SRT-W9 — the time base is seeded from the handshake
5289    // -----------------------------------------------------------------------
5290
5291    /// `TsbpdTimeBase = T_NOW - HSREQ_TIMESTAMP` with `T_NOW = 0` at the
5292    /// epoch is minus the peer's handshake timestamp (rule 12).
5293    #[test]
5294    fn the_time_base_is_minus_the_peer_handshake_timestamp() {
5295        assert_eq!(tsbpd_time_base_from(0), 0);
5296        assert_eq!(tsbpd_time_base_from(3_000_000), -3_000_000);
5297        assert_eq!(tsbpd_time_base_from(u32::MAX), -i64::from(u32::MAX));
5298    }
5299
5300    /// A peer whose clock already reads 30 s when the handshake completes
5301    /// (its first data packet carries `Timestamp` ~30 s) is delivered one
5302    /// latency after arrival — not 30 s later, which is what a hard-coded
5303    /// zero base did (the packet's play time was `0 + 30 s + latency`).
5304    #[tokio::test(start_paused = true)]
5305    async fn a_peer_far_into_its_own_clock_is_not_delayed_by_its_timestamp() {
5306        const PEER_CLOCK_US: u32 = 30_000_000;
5307        let udp = Arc::new(UdpSocket::bind("127.0.0.1:0").await.unwrap());
5308        let (deliver, mut rx) = mpsc::channel(DELIVER_CHANNEL_CAPACITY);
5309        let (_datagram_tx, datagram_rx) = mpsc::channel(RX_CHANNEL_CAPACITY);
5310        let mut driver = Driver::new(
5311            ConnParams {
5312                udp,
5313                peer_addr: peer_addr(),
5314                rx: datagram_rx,
5315                stats: Arc::new(Counters::default()),
5316                route_cleanup: RouteCleanup(None),
5317                forwarder_guard: TaskGuard(None),
5318                life: None,
5319                read_idle: IoConfig::default().timeouts.read_idle,
5320                write: IoConfig::default().timeouts.write,
5321                our_initial_seq: 0,
5322                peer_initial_seq: 0,
5323                peer_socket_id: 1,
5324                tsbpd_time_base: tsbpd_time_base_from(PEER_CLOCK_US),
5325                tsbpd_delay: Duration::from_millis(LATENCY_MS),
5326                epoch: Instant::now(),
5327                max_flow_window: 8192,
5328                mtu: 1500,
5329                tlpkt_drop: true,
5330                #[cfg(feature = "crypto")]
5331                crypto_passphrase: Vec::new(),
5332                #[cfg(feature = "crypto")]
5333                crypto_salt: None,
5334                #[cfg(feature = "crypto")]
5335                crypto_even_sek: None,
5336                #[cfg(feature = "crypto")]
5337                crypto_thresholds: crate::km_refresh::KmRefreshThresholds::RECOMMENDED,
5338            },
5339            deliver,
5340        );
5341        driver
5342            .ingress(Bytes::from(data_bytes(0, PEER_CLOCK_US, b"first")))
5343            .expect("ingress");
5344        assert!(drain_deliveries(&mut rx).is_empty(), "not due on arrival");
5345        tokio::time::advance(Duration::from_millis(LATENCY_MS)).await;
5346        driver.tick_engines();
5347        assert_eq!(
5348            drain_deliveries(&mut rx),
5349            vec![b"first".to_vec()],
5350            "delivered one latency after arrival"
5351        );
5352    }
5353
5354    // -----------------------------------------------------------------------
5355    // Pacing schedule (issue #1061), deterministically
5356    // -----------------------------------------------------------------------
5357
5358    /// Under a paused clock the token-bucket schedule is exact: the first DATA
5359    /// packet goes at once, the next not a nanosecond before one pacing period
5360    /// later, and a burst after an idle gap is not penalized (it sends
5361    /// immediately, then resumes the period).
5362    #[tokio::test(start_paused = true)]
5363    async fn data_leaves_one_packet_per_pacing_period() {
5364        let (mut driver, _rx) = test_driver(8192).await;
5365        driver.peer_addr = "127.0.0.1:1".parse().unwrap();
5366        const BACKLOG: usize = 60;
5367        for _ in 0..BACKLOG {
5368            driver.send_one(&[0u8; 1316]);
5369        }
5370        let period = driver.livecc.on_ack_received();
5371        assert!(period > Duration::ZERO, "the default MAX_BW paces DATA");
5372
5373        driver.flush_outbound().await.expect("flush");
5374        assert_eq!(
5375            driver.outbound_data.len(),
5376            BACKLOG - 1,
5377            "the first packet goes at once"
5378        );
5379
5380        tokio::time::advance(period - Duration::from_nanos(1)).await;
5381        driver.flush_outbound().await.expect("flush");
5382        assert_eq!(
5383            driver.outbound_data.len(),
5384            BACKLOG - 1,
5385            "one nanosecond short of the slot"
5386        );
5387
5388        tokio::time::advance(Duration::from_nanos(1)).await;
5389        driver.flush_outbound().await.expect("flush");
5390        assert_eq!(
5391            driver.outbound_data.len(),
5392            BACKLOG - 2,
5393            "the slot arrived: one more"
5394        );
5395
5396        // A long stall does not let the backlog out in one burst: the late
5397        // wake claims at most `PACING_BURST_CAP` packets of catch-up (it used
5398        // to send exactly one and lose the rest of the credit).
5399        tokio::time::advance(period * 100).await;
5400        let before = driver.outbound_data.len();
5401        driver.flush_outbound().await.expect("flush");
5402        let sent = before - driver.outbound_data.len();
5403        assert_eq!(
5404            sent, PACING_BURST_CAP,
5405            "a stalled wake must send exactly the burst cap"
5406        );
5407        assert!(!driver.outbound_data.is_empty());
5408        assert!(driver.next_paced_send_wait().is_some());
5409    }
5410
5411    /// r08-SRT-O2: a retransmission feeds LiveCC the packet's *payload* length
5412    /// (the datagram less its fixed header), exactly as a first transmission
5413    /// does — read from the length instead of re-parsing the packet.
5414    #[tokio::test(start_paused = true)]
5415    async fn a_retransmission_is_accounted_by_its_payload_length() {
5416        use crate::packet::number::SeqNo;
5417        use crate::packet::{LossListEntry, NakPacket};
5418        let (mut driver, _rx) = test_driver(8192).await;
5419        driver.send_one(&[0u8; 1000]); // seq 0
5420        let nak = ControlPacket::Nak(NakPacket {
5421            timestamp: crate::packet::SrtTimestamp::ZERO,
5422            dest_socket_id: crate::packet::SocketId::from_wire(1),
5423            entries: alloc::vec![LossListEntry::Single(
5424                SeqNo::try_new(0).expect("fits 31 bits")
5425            )],
5426        });
5427        let mut bytes = alloc::vec![0u8; nak.serialized_len()];
5428        nak.serialize_into(&mut bytes).expect("serialize nak");
5429        driver.ingress(Bytes::from(bytes)).expect("ingress nak");
5430        driver.tick_engines();
5431        assert_eq!(
5432            driver.outbound_data.len(),
5433            2,
5434            "the packet and its retransmit"
5435        );
5436
5437        // The reference sees two 1000-byte payloads; a header-inclusive length
5438        // (1016) would leave the average two bytes higher.
5439        let mut reference = LiveCC::new(DEFAULT_MAX_BW);
5440        reference.on_data_packet(1000);
5441        reference.on_data_packet(1000);
5442        assert_eq!(
5443            driver.livecc.avg_payload_size(),
5444            reference.avg_payload_size()
5445        );
5446    }
5447
5448    /// #2819: one NAK naming the whole send buffer cannot queue more
5449    /// retransmissions than the negotiated flow window, and a second NAK
5450    /// before the queue drains adds no duplicates.
5451    #[tokio::test(start_paused = true)]
5452    async fn a_nak_naming_the_whole_buffer_is_capped_at_the_flow_window() {
5453        use crate::packet::number::SeqNo;
5454        use crate::packet::{LossListEntry, NakPacket};
5455        const WINDOW: u32 = 4;
5456        const BUFFERED: u32 = 8;
5457        let (mut driver, _rx) = test_driver(WINDOW).await;
5458        driver.peer_addr = "127.0.0.1:1".parse().unwrap();
5459        for _ in 0..BUFFERED {
5460            driver.send_one(&[0u8; 100]);
5461        }
5462        driver.outbound_data.clear(); // the first transmissions are on the wire
5463
5464        let nak = || {
5465            let nak = ControlPacket::Nak(NakPacket {
5466                timestamp: crate::packet::SrtTimestamp::ZERO,
5467                dest_socket_id: crate::packet::SocketId::from_wire(1),
5468                entries: alloc::vec![LossListEntry::Range(
5469                    SeqNo::try_new(0).expect("fits 31 bits"),
5470                    SeqNo::try_new(BUFFERED - 1).expect("fits 31 bits"),
5471                )],
5472            });
5473            let mut bytes = alloc::vec![0u8; nak.serialized_len()];
5474            nak.serialize_into(&mut bytes).expect("serialize nak");
5475            bytes
5476        };
5477
5478        driver.ingress(Bytes::from(nak())).expect("ingress nak");
5479        driver.tick_engines();
5480        assert_eq!(
5481            driver.outbound_data.len(),
5482            WINDOW as usize,
5483            "the outbound queue is capped at the flow window"
5484        );
5485        assert_eq!(
5486            driver.sender.pending_retransmit_count(),
5487            (BUFFERED - WINDOW) as usize
5488        );
5489
5490        driver.ingress(Bytes::from(nak())).expect("ingress nak");
5491        driver.tick_engines();
5492        assert_eq!(
5493            driver.outbound_data.len(),
5494            WINDOW as usize,
5495            "a repeated NAK must not queue a second copy"
5496        );
5497
5498        for _ in 0..WINDOW {
5499            driver.flush_outbound().await.expect("flush");
5500            if let Some(wait) = driver.next_paced_send_wait() {
5501                tokio::time::advance(wait).await;
5502            }
5503        }
5504        assert!(driver.outbound_data.is_empty());
5505        driver.tick_engines();
5506        assert!(
5507            driver.outbound_data.is_empty(),
5508            "the dropped retransmissions are still inside MIN_RETRANSMIT_INTERVAL"
5509        );
5510        tokio::time::advance(Duration::from_millis(20)).await;
5511        driver.tick_engines();
5512        assert_eq!(
5513            driver.outbound_data.len(),
5514            (BUFFERED - WINDOW) as usize,
5515            "the remainder is offered once the interval has passed"
5516        );
5517    }
5518
5519    /// When the application handle is gone and the driver ends cooperatively
5520    /// (not by abort), it still tells the peer it is leaving (§3.2.7). (Real
5521    /// clock, bounded real waits: a paused clock would auto-advance past the
5522    /// `recv` timeout before the loopback datagram is delivered.)
5523    #[tokio::test]
5524    async fn a_driver_ending_because_its_handle_is_gone_sends_shutdown() {
5525        let peer = UdpSocket::bind("127.0.0.1:0").await.unwrap();
5526        let (mut driver, _rx, _datagrams) = test_driver_with_ingress(8192).await;
5527        driver.peer_addr = peer.local_addr().unwrap();
5528        let (app_tx, app_rx) = mpsc::channel::<Bytes>(SEND_CHANNEL_CAPACITY);
5529        let handle = tokio::spawn(driver.run(app_rx));
5530        drop(app_tx);
5531        tokio::time::timeout(Duration::from_secs(5), handle)
5532            .await
5533            .expect("the driver must end once its handle is gone")
5534            .expect("join");
5535
5536        let mut buf = [0u8; 2048];
5537        let shutdown = loop {
5538            let n = tokio::time::timeout(Duration::from_secs(5), peer.recv(&mut buf))
5539                .await
5540                .expect("no SHUTDOWN reached the peer")
5541                .expect("recv");
5542            if let Ok(SrtPacket::Control(ControlPacket::Shutdown(s))) = SrtPacket::parse(&buf[..n])
5543            {
5544                break s;
5545            }
5546        };
5547        assert_eq!(
5548            shutdown.dest_socket_id,
5549            crate::packet::SocketId::from_wire(1),
5550            "addressed to the peer's socket id"
5551        );
5552    }
5553
5554    /// A hostile `retransmit_after` must not make the handshake timer's
5555    /// period zero (which would panic the connect).
5556    #[tokio::test]
5557    async fn an_absurd_retransmit_period_does_not_panic_the_connect() {
5558        let silent = UdpSocket::bind("127.0.0.1:0").await.unwrap();
5559        for step in [Duration::ZERO, Duration::from_micros(1), Duration::MAX] {
5560            let config = HandshakeConfig {
5561                retransmit_after: step,
5562                ..HandshakeConfig::default()
5563            };
5564            // Nobody answers; the point is only that it neither panics nor
5565            // fails immediately.
5566            let outcome = tokio::time::timeout(
5567                Duration::from_millis(150),
5568                SrtSocket::connect(silent.local_addr().unwrap(), SrtSocketConfig::new(config)),
5569            )
5570            .await;
5571            assert!(
5572                outcome.is_err(),
5573                "step={step:?}: still waiting for the peer"
5574            );
5575        }
5576    }
5577
5578    // -----------------------------------------------------------------------
5579    // Stale sequence numbers, and the negotiated TLPKTDROP flag
5580    // -----------------------------------------------------------------------
5581
5582    /// Packets behind the delivery cursor are never staged: with the cursor at
5583    /// 3, a hundred thousand distinct stale sequence numbers (each stamped
5584    /// with a far-future timestamp, so TSBPD would hold them) leave `staged`
5585    /// empty and are counted as late. They used to be staged, ignored by
5586    /// TSBPD and never removed.
5587    #[tokio::test(start_paused = true)]
5588    async fn stale_sequence_numbers_are_never_staged() {
5589        let (mut driver, mut rx) = test_driver(8192).await;
5590        for seq in 0..3u32 {
5591            driver
5592                .ingress(Bytes::from(data_bytes(
5593                    seq,
5594                    0,
5595                    &[u8::try_from(seq).unwrap()],
5596                )))
5597                .expect("ingress");
5598        }
5599        tokio::time::advance(Duration::from_millis(130)).await;
5600        driver.tick_engines();
5601        assert_eq!(drain_deliveries(&mut rx).len(), 3);
5602        assert_eq!(driver.tsbpd.next_release(), 3);
5603
5604        const STALE: u32 = 100_000;
5605        for back in 1..=STALE {
5606            // 2^31 - back is `back` behind the cursor at 0..3 in circular order.
5607            let seq = (1u32 << 31) - back;
5608            driver
5609                .ingress(Bytes::from(data_bytes(seq, u32::MAX, b"x")))
5610                .expect("ingress");
5611        }
5612        assert!(
5613            driver.staged.is_empty(),
5614            "{} stale packets staged",
5615            driver.staged.len()
5616        );
5617        assert_eq!(
5618            driver.stats.late_dropped.load(Ordering::Relaxed),
5619            u64::from(STALE)
5620        );
5621        // A duplicate of something already delivered is late too.
5622        driver
5623            .ingress(Bytes::from(data_bytes(1, 0, b"dup")))
5624            .expect("ingress");
5625        assert!(driver.staged.is_empty());
5626    }
5627
5628    /// Without a negotiated TLPKTDROP the receiver never skips a gap: it waits
5629    /// for the retransmission, delivers nothing past the hole however long it
5630    /// takes, and never moves its ack point past it (which would tell the
5631    /// sender a packet that never arrived was received).
5632    #[tokio::test(start_paused = true)]
5633    async fn without_negotiated_tlpktdrop_a_gap_is_waited_out_not_skipped() {
5634        let (mut driver, mut rx) = test_driver(8192).await;
5635        driver.tsbpd = TsbpdScheduler::new(
5636            0,
5637            0,
5638            Duration::from_millis(LATENCY_MS),
5639            DEFAULT_DRIFT_US,
5640            false,
5641            None,
5642        );
5643        for seq in [0u32, 2, 3] {
5644            driver
5645                .ingress(Bytes::from(data_bytes(
5646                    seq,
5647                    0,
5648                    &[u8::try_from(seq).unwrap()],
5649                )))
5650                .expect("ingress");
5651        }
5652        // Far beyond the latency (and the too-late threshold).
5653        for _ in 0..50 {
5654            tokio::time::advance(Duration::from_millis(100)).await;
5655            driver.tick_engines();
5656        }
5657        let delivered = drain_deliveries(&mut rx);
5658        assert_eq!(
5659            delivered.iter().map(|p| p[0]).collect::<Vec<_>>(),
5660            vec![0],
5661            "nothing may pass the hole"
5662        );
5663        assert_eq!(driver.receiver.ack_point(), 1, "never ACK past a gap");
5664        assert_eq!(driver.receiver.loss_list_len(), 1, "still asking for seq 1");
5665
5666        // The retransmission arrives: everything flows, in order.
5667        driver
5668            .ingress(Bytes::from(data_bytes(1, 0, &[1])))
5669            .expect("ingress");
5670        driver.tick_engines();
5671        let delivered = drain_deliveries(&mut rx);
5672        assert_eq!(
5673            delivered.iter().map(|p| p[0]).collect::<Vec<_>>(),
5674            vec![1, 2, 3]
5675        );
5676        assert_eq!(driver.receiver.ack_point(), 4);
5677    }
5678
5679    /// The negotiated flag, not a constant, decides: a connection negotiated
5680    /// with TLPKTDROP skips (the existing live-mode tests), one without does
5681    /// not — pinned through `Driver::new`'s own configuration.
5682    #[tokio::test]
5683    async fn the_driver_honours_the_negotiated_tlpktdrop_flag() {
5684        for negotiated in [true, false] {
5685            let udp = Arc::new(UdpSocket::bind("127.0.0.1:0").await.unwrap());
5686            let (deliver, _rx) = mpsc::channel(1);
5687            let (_tx, datagram_rx) = mpsc::channel(1);
5688            let driver = Driver::new(
5689                ConnParams {
5690                    udp,
5691                    peer_addr: peer_addr(),
5692                    rx: datagram_rx,
5693                    stats: Arc::new(Counters::default()),
5694                    route_cleanup: RouteCleanup(None),
5695                    forwarder_guard: TaskGuard(None),
5696                    life: None,
5697                    read_idle: IoConfig::default().timeouts.read_idle,
5698                    write: IoConfig::default().timeouts.write,
5699                    our_initial_seq: 0,
5700                    peer_initial_seq: 0,
5701                    peer_socket_id: 1,
5702                    tsbpd_time_base: 0,
5703                    tsbpd_delay: Duration::from_millis(LATENCY_MS),
5704                    epoch: Instant::now(),
5705                    max_flow_window: 8192,
5706                    mtu: 1500,
5707                    tlpkt_drop: negotiated,
5708                    #[cfg(feature = "crypto")]
5709                    crypto_passphrase: Vec::new(),
5710                    #[cfg(feature = "crypto")]
5711                    crypto_salt: None,
5712                    #[cfg(feature = "crypto")]
5713                    crypto_even_sek: None,
5714                    #[cfg(feature = "crypto")]
5715                    crypto_thresholds: crate::km_refresh::KmRefreshThresholds::RECOMMENDED,
5716                },
5717                deliver,
5718            );
5719            assert_eq!(driver.tsbpd.tlpktdrop_enabled(), negotiated);
5720        }
5721    }
5722
5723    // -----------------------------------------------------------------------
5724    // #1142 / O5 — the cookie key is secret, 128 bits, and rotates
5725    // -----------------------------------------------------------------------
5726
5727    /// `{:?}` of a listener (and of its key holder) never prints the cookie
5728    /// key, in decimal or hex.
5729    #[tokio::test]
5730    async fn listener_debug_never_prints_the_cookie_key() {
5731        let listener = test_core(HandshakeConfig::default()).await;
5732        let key = listener.cookie_keys.current();
5733        assert!(
5734            key > u128::from(u64::MAX),
5735            "a 128-bit key, not a 64-bit one"
5736        );
5737        for dump in [
5738            alloc::format!("{listener:?}"),
5739            alloc::format!("{listener:#?}"),
5740            alloc::format!("{listener:x?}"),
5741        ] {
5742            for needle in [
5743                alloc::format!("{key}"),
5744                alloc::format!("{key:x}"),
5745                alloc::format!("{:x}", key >> 64),
5746            ] {
5747                assert!(!dump.contains(&needle), "key leaked as {needle:?}: {dump}");
5748            }
5749            assert!(dump.contains("redacted"), "{dump}");
5750        }
5751    }
5752
5753    fn induction_cookie(listener: &mut ListenerCore, src: std::net::SocketAddr) -> u32 {
5754        listener
5755            .handle_datagram(src, &induction_bytes(7))
5756            .expect("induction");
5757        let response = listener
5758            .outbound_queue
5759            .get_mut(&src)
5760            .and_then(VecDeque::pop_back)
5761            .expect("an INDUCTION response");
5762        match SrtPacket::parse(&response).expect("parse") {
5763            SrtPacket::Control(ControlPacket::Handshake(hp)) => hp.syn_cookie,
5764            other => panic!("expected a handshake, got {other:?}"),
5765        }
5766    }
5767
5768    /// The key is replaced exactly once a minute is up; cookies issued after
5769    /// differ from those before for the same peer.
5770    #[tokio::test]
5771    async fn the_cookie_key_rotates_every_minute() {
5772        let mut listener = test_core(HandshakeConfig::default()).await;
5773        let t0 = listener.cookie_keys.drawn_at;
5774        let first = listener.cookie_keys.current();
5775
5776        assert!(
5777            !listener
5778                .cookie_keys
5779                .rotate_if_due(t0 + COOKIE_KEY_ROTATION - Duration::from_millis(1))
5780        );
5781        assert_eq!(listener.cookie_keys.current(), first, "not yet due");
5782
5783        let src = peer_addr();
5784        let before = induction_cookie(&mut listener, src);
5785        listener.pending.clear();
5786        assert!(listener.cookie_keys.rotate_if_due(t0 + COOKIE_KEY_ROTATION));
5787        assert_ne!(
5788            listener.cookie_keys.current(),
5789            first,
5790            "a fresh key was drawn"
5791        );
5792        assert_eq!(
5793            listener.cookie_keys.drawn_at,
5794            t0 + COOKIE_KEY_ROTATION,
5795            "the next rotation is measured from this one"
5796        );
5797        let after = induction_cookie(&mut listener, src);
5798        assert_ne!(
5799            before, after,
5800            "the same peer gets a different cookie after rotation"
5801        );
5802    }
5803
5804    /// A handshake begun under the previous key still completes after the key
5805    /// rotates: its pending entry keeps the cookie it was issued.
5806    #[tokio::test]
5807    async fn a_handshake_begun_before_a_rotation_still_completes() {
5808        use crate::caller::CallerHandshake;
5809        let mut listener = test_core(HandshakeConfig::default()).await;
5810        let src = peer_addr();
5811        let mut caller = CallerHandshake::new(0x0000_0777, HandshakeConfig::default());
5812        let induction = caller.start().expect("start");
5813        listener
5814            .handle_datagram(src, &induction)
5815            .expect("induction");
5816        let response = listener
5817            .outbound_queue
5818            .get_mut(&src)
5819            .and_then(VecDeque::pop_back)
5820            .expect("response");
5821
5822        let t0 = listener.cookie_keys.drawn_at;
5823        assert!(listener.cookie_keys.rotate_if_due(t0 + COOKIE_KEY_ROTATION));
5824
5825        let conclusion = caller
5826            .feed_bytes(&response)
5827            .expect("feed")
5828            .into_iter()
5829            .find_map(|o| match o {
5830                HandshakeOutput::Send(b) => Some(b),
5831                _ => None,
5832            })
5833            .expect("CONCLUSION");
5834        listener
5835            .handle_datagram(src, &conclusion)
5836            .expect("the CONCLUSION must be accepted across the rotation");
5837        assert!(
5838            listener.pending[&src].params.is_some(),
5839            "the handshake must have completed"
5840        );
5841        // The connection epoch is when the CONCLUSION arrived, and a repeat
5842        // does not move it.
5843        let concluded = listener.pending[&src].concluded_at.expect("recorded");
5844        listener
5845            .handle_datagram(src, &conclusion)
5846            .expect("a repeated CONCLUSION");
5847        assert_eq!(listener.pending[&src].concluded_at, Some(concluded));
5848    }
5849
5850    fn test_life() -> Arc<ListenerLife> {
5851        Arc::new(ListenerLife {
5852            cancel: CancellationToken::new(),
5853            tasks: TaskTracker::new(),
5854        })
5855    }
5856
5857    fn conclusion_with_encryption(socket_id: u32, encryption_field: EncryptionField) -> Vec<u8> {
5858        let hp = HandshakePacket {
5859            timestamp: crate::packet::SrtTimestamp::ZERO,
5860            dest_socket_id: crate::packet::SocketId::CONNECTION_REQUEST,
5861            version: crate::handshake_sm::HANDSHAKE_VERSION_5,
5862            encryption_field,
5863            extension_field: HandshakeExtensionFlags(0),
5864            initial_seq_number: 0,
5865            mtu: 1500,
5866            max_flow_window_size: 8192,
5867            handshake_type: crate::packet::HandshakeType::Conclusion,
5868            srt_socket_id: socket_id,
5869            syn_cookie: 0,
5870            peer_ip: [0; 4],
5871            extensions: HandshakeExtensions(Vec::new()),
5872        };
5873        let pkt = ControlPacket::Handshake(hp);
5874        let mut buf = alloc::vec![0u8; pkt.serialized_len()];
5875        pkt.serialize_into(&mut buf).expect("serialize conclusion");
5876        buf
5877    }
5878
5879    fn conclusion_with_extension_flags(
5880        socket_id: u32,
5881        extension_field: HandshakeExtensionFlags,
5882    ) -> Vec<u8> {
5883        let hp = HandshakePacket {
5884            timestamp: crate::packet::SrtTimestamp::ZERO,
5885            dest_socket_id: crate::packet::SocketId::CONNECTION_REQUEST,
5886            version: crate::handshake_sm::HANDSHAKE_VERSION_5,
5887            encryption_field: EncryptionField::NoEncryption,
5888            extension_field,
5889            initial_seq_number: 0,
5890            mtu: 1500,
5891            max_flow_window_size: 8192,
5892            handshake_type: crate::packet::HandshakeType::Conclusion,
5893            srt_socket_id: socket_id,
5894            syn_cookie: 0,
5895            peer_ip: [0; 4],
5896            extensions: HandshakeExtensions(Vec::new()),
5897        };
5898        let pkt = ControlPacket::Handshake(hp);
5899        let mut buf = alloc::vec![0u8; pkt.serialized_len()];
5900        pkt.serialize_into(&mut buf).expect("serialize conclusion");
5901        buf
5902    }
5903
5904    /// §4.3.1.1: an INDUCTION reply cookie is bound to the source address —
5905    /// a CONCLUSION replayed from another port validates nothing.
5906    #[tokio::test]
5907    async fn cookie_replay_from_another_source_is_not_accepted() {
5908        let mut core = test_core(HandshakeConfig::default()).await;
5909        let src_a: std::net::SocketAddr = "127.0.0.1:40001".parse().unwrap();
5910        let src_b: std::net::SocketAddr = "127.0.0.1:40002".parse().unwrap();
5911        let conclusion = listener_conclusion(&mut core, src_a, 7);
5912        core.outbound_queue.clear();
5913
5914        core.handle_datagram(src_b, &conclusion)
5915            .expect("a replayed conclusion is ignored");
5916        assert!(
5917            core.pending.is_empty(),
5918            "a cookie issued to another source must allocate no state"
5919        );
5920        assert!(
5921            core.outbound_queue.get(&src_b).is_none_or(|q| q.is_empty()),
5922            "no response may go to the replayer"
5923        );
5924
5925        core.handle_datagram(src_a, &conclusion)
5926            .expect("the genuine source connects");
5927        assert_eq!(
5928            core.pending[&src_a].handshake.state(),
5929            ListenerHandshakeState::Connected
5930        );
5931    }
5932
5933    /// A Listener without crypto refuses an encrypted INDUCTION with a
5934    /// well-formed REJ_UNSECURE handshake packet.
5935    #[tokio::test]
5936    async fn listener_refuses_an_encrypted_request_with_a_rejection_packet() {
5937        let mut core = test_core(HandshakeConfig::default()).await;
5938        let src = peer_addr();
5939        let caller_id = 0x0000_0777;
5940        core.handle_datagram(
5941            src,
5942            &conclusion_with_encryption(caller_id, EncryptionField::Aes128),
5943        )
5944        .expect("encrypted conclusion");
5945        let answer = core
5946            .outbound_queue
5947            .get(&src)
5948            .and_then(|queue| queue.back())
5949            .cloned()
5950            .expect("a rejection answer");
5951        let ControlPacket::Handshake(hp) = ControlPacket::parse(&answer).expect("parse") else {
5952            panic!("expected handshake");
5953        };
5954        assert_eq!(
5955            hp.handshake_type,
5956            RejectionReason::Unsecure.to_handshake_type()
5957        );
5958        assert_eq!(hp.srt_socket_id, 0);
5959        assert_eq!(
5960            hp.dest_socket_id,
5961            crate::packet::SocketId::from_wire(caller_id)
5962        );
5963        assert_eq!(answer.len(), 64, "SRT header (16) + fixed CIF (48)");
5964        assert!(core.pending.is_empty());
5965    }
5966
5967    /// A CONCLUSION carrying the KMREQ extension bit is refused even when its
5968    /// Encryption Field is zero.
5969    #[tokio::test]
5970    async fn listener_refuses_a_kmreq_flag_on_a_conclusion() {
5971        use crate::packet::handshake::HS_EXT_FLAG_KMREQ;
5972        let mut core = test_core(HandshakeConfig::default()).await;
5973        let src = peer_addr();
5974        let caller_id = 0x0000_0778;
5975        core.handle_datagram(
5976            src,
5977            &conclusion_with_extension_flags(caller_id, HandshakeExtensionFlags(HS_EXT_FLAG_KMREQ)),
5978        )
5979        .expect("conclusion");
5980        let answer = core
5981            .outbound_queue
5982            .get(&src)
5983            .and_then(|queue| queue.back())
5984            .cloned()
5985            .expect("a rejection answer");
5986        let ControlPacket::Handshake(hp) = ControlPacket::parse(&answer).expect("parse") else {
5987            panic!("expected handshake");
5988        };
5989        assert_eq!(
5990            hp.handshake_type,
5991            RejectionReason::Unsecure.to_handshake_type()
5992        );
5993        assert_eq!(
5994            hp.dest_socket_id,
5995            crate::packet::SocketId::from_wire(caller_id)
5996        );
5997    }
5998
5999    /// The remembered CONCLUSION answer is answered while fresh and dropped at
6000    /// exactly `RECENT_ACCEPT_TTL`.
6001    #[tokio::test(start_paused = true)]
6002    async fn remembered_conclusion_answer_expires_at_the_ttl() {
6003        let mut core = test_core(HandshakeConfig::default()).await;
6004        let src = peer_addr();
6005        let response = alloc::vec![1u8, 2, 3, 4];
6006        core.remember_accept(
6007            src,
6008            RecentAccept {
6009                peer_socket_id: 7,
6010                response: response.clone(),
6011                accepted_at: Instant::now(),
6012            },
6013        );
6014        core.handle_datagram(src, &conclusion_bytes(7, 123))
6015            .expect("repeat");
6016        assert_eq!(
6017            core.outbound_queue.get(&src).and_then(|q| q.back()),
6018            Some(&response)
6019        );
6020        core.outbound_queue.clear();
6021
6022        core.recent_accepts
6023            .get_mut(&src)
6024            .expect("entry")
6025            .accepted_at = Instant::now() - RECENT_ACCEPT_TTL;
6026        core.handle_datagram(src, &conclusion_bytes(7, 123))
6027            .expect("expired repeat");
6028        assert!(
6029            core.outbound_queue.get(&src).is_none_or(|q| q.is_empty()),
6030            "a cached answer must not outlive its TTL"
6031        );
6032    }
6033
6034    /// The pending-handshake tick re-sends an unanswered INDUCTION response.
6035    #[tokio::test]
6036    async fn tick_pending_retransmits_a_pending_handshake() {
6037        let config = HandshakeConfig {
6038            retransmit_after: Duration::from_millis(10),
6039            max_retries: 5,
6040            ..HandshakeConfig::default()
6041        };
6042        let mut core = test_core(config.clone()).await;
6043        let src = peer_addr();
6044        let mut handshake = ListenerHandshake::new(0x1234, 0xCAFE, config);
6045        let outputs = handshake
6046            .feed_bytes(&induction_bytes(7))
6047            .expect("induction");
6048        let expected = outputs
6049            .into_iter()
6050            .find_map(|o| match o {
6051                HandshakeOutput::Send(bytes) => Some(bytes),
6052                _ => None,
6053            })
6054            .expect("an INDUCTION response");
6055        core.pending.insert(
6056            src,
6057            PendingListener {
6058                handshake,
6059                params: None,
6060                peer_initial_seq: 0,
6061                peer_timestamp_us: 0,
6062                concluded_at: None,
6063                created_at: Instant::now(),
6064                last_response: None,
6065                our_initial_seq: 0,
6066            },
6067        );
6068        core.outbound_queue.clear();
6069        core.tick_pending();
6070        assert_eq!(
6071            core.outbound_queue.get(&src).and_then(|q| q.back()),
6072            Some(&expected),
6073            "the tick must queue the retransmit"
6074        );
6075    }
6076
6077    #[tokio::test(start_paused = true)]
6078    async fn tick_pending_reaps_expired_recent_accepts() {
6079        let mut core = test_core(HandshakeConfig::default()).await;
6080        let stale = peer_addr();
6081        let fresh: std::net::SocketAddr = "10.0.0.2:9999".parse().unwrap();
6082        core.recent_accepts.insert(
6083            stale,
6084            RecentAccept {
6085                peer_socket_id: 1,
6086                response: alloc::vec![1],
6087                accepted_at: Instant::now() - RECENT_ACCEPT_TTL,
6088            },
6089        );
6090        core.recent_accepts.insert(
6091            fresh,
6092            RecentAccept {
6093                peer_socket_id: 2,
6094                response: alloc::vec![2],
6095                accepted_at: Instant::now(),
6096            },
6097        );
6098        core.tick_pending();
6099        assert!(!core.recent_accepts.contains_key(&stale));
6100        assert!(core.recent_accepts.contains_key(&fresh));
6101    }
6102
6103    #[tokio::test(start_paused = true)]
6104    async fn remember_accept_reaps_expired_entries() {
6105        let mut core = test_core(HandshakeConfig::default()).await;
6106        let stale = peer_addr();
6107        core.recent_accepts.insert(
6108            stale,
6109            RecentAccept {
6110                peer_socket_id: 1,
6111                response: alloc::vec![1],
6112                accepted_at: Instant::now() - RECENT_ACCEPT_TTL,
6113            },
6114        );
6115        let fresh: std::net::SocketAddr = "10.0.0.2:9999".parse().unwrap();
6116        core.remember_accept(
6117            fresh,
6118            RecentAccept {
6119                peer_socket_id: 2,
6120                response: alloc::vec![2],
6121                accepted_at: Instant::now(),
6122            },
6123        );
6124        assert!(!core.recent_accepts.contains_key(&stale));
6125        assert!(core.recent_accepts.contains_key(&fresh));
6126    }
6127
6128    /// `flush_all` actually drains every queued per-peer datagram.
6129    #[tokio::test]
6130    async fn flush_all_sends_every_queued_datagram() {
6131        let (mut core, _tx, _accepted) = test_core_with_channels(HandshakeConfig::default()).await;
6132        let peer = UdpSocket::bind("127.0.0.1:0").await.unwrap();
6133        let peer_addr = peer.local_addr().unwrap();
6134        core.outbound_queue
6135            .entry(peer_addr)
6136            .or_default()
6137            .push_back(alloc::vec![1u8, 2, 3]);
6138        core.flush_all().await.expect("flush");
6139        assert!(core.outbound_queue.values().all(|q| q.is_empty()));
6140        let mut buf = [0u8; 8];
6141        let (n, _) = tokio::time::timeout(Duration::from_secs(2), peer.recv_from(&mut buf))
6142            .await
6143            .expect("no datagram")
6144            .expect("recv_from");
6145        assert_eq!(&buf[..n], &[1, 2, 3]);
6146    }
6147
6148    /// `drain_completed` skips an entry whose negotiated parameters were never
6149    /// recorded (the defensive branch), rather than handing it over.
6150    #[tokio::test]
6151    async fn drain_completed_skips_an_entry_without_parameters() {
6152        let life = test_life();
6153        let (mut core, _tx, _accepted) = test_core_with_channels(HandshakeConfig::default()).await;
6154        core.life = Arc::downgrade(&life);
6155        let src = peer_addr();
6156        let conclusion = listener_conclusion(&mut core, src, 7);
6157        core.handle_datagram(src, &conclusion)
6158            .expect("cookie-validated conclusion");
6159        assert!(core.pending.contains_key(&src));
6160        core.pending.get_mut(&src).expect("pending").params = None;
6161        assert!(core.drain_completed().is_none());
6162    }
6163
6164    /// The listener counters read the shared atomics, and `Debug` names the
6165    /// listener and its address.
6166    #[tokio::test]
6167    async fn listener_accessors_and_debug_report_the_live_values() {
6168        let (_accepted_tx, accepted) = mpsc::channel::<Result<SrtSocket>>(1);
6169        let listener = SrtListener {
6170            _life: test_life(),
6171            local: "127.0.0.1:1234".parse().unwrap(),
6172            accepted,
6173            routes: Arc::new(Mutex::new(std::collections::HashMap::new())),
6174            unrouted_dropped: Arc::new(AtomicU64::new(7)),
6175            overflow_dropped: Arc::new(AtomicU64::new(8)),
6176            send_errors: Arc::new(AtomicU64::new(9)),
6177        };
6178        assert_eq!(listener.unrouted_dropped(), 7);
6179        assert_eq!(listener.accept_overflow_dropped(), 8);
6180        assert_eq!(listener.send_errors(), 9);
6181        let rendered = alloc::format!("{listener:?}");
6182        assert!(rendered.contains("SrtListener"), "{rendered}");
6183        assert!(rendered.contains("1234"), "{rendered}");
6184    }
6185
6186    #[tokio::test]
6187    async fn local_crypto_enabled_reflects_the_configuration() {
6188        let mut core = test_core(HandshakeConfig::default()).await;
6189        assert!(!core.local_crypto_enabled());
6190        #[cfg(feature = "crypto")]
6191        {
6192            core.config.crypto = Some(crate::handshake_sm::CryptoConfig::new(
6193                b"pw".to_vec(),
6194                [0u8; 16],
6195                vec![0u8; 16],
6196            ));
6197            assert!(core.local_crypto_enabled());
6198        }
6199    }
6200
6201    #[test]
6202    fn with_handshake_stores_the_config() {
6203        let config = HandshakeConfig::default()
6204            .with_srt_version(0x0105_0001)
6205            .with_max_retries(4);
6206        let socket_config = SrtSocketConfig::default().with_handshake(config.clone());
6207        assert_eq!(socket_config.handshake, config);
6208    }
6209
6210    /// The Retransmit-free helper `with_handshake` above also leaves the I/O
6211    /// config untouched; `SrtSocketConfig::new` is its equivalent.
6212    #[test]
6213    fn socket_config_new_keeps_the_default_io() {
6214        let config = HandshakeConfig::default().with_mtu(1400);
6215        let socket_config = SrtSocketConfig::new(config.clone());
6216        assert_eq!(socket_config.handshake, config);
6217        assert_eq!(socket_config.io, IoConfig::default());
6218    }
6219
6220    /// A dedicated-socket forwarder only passes datagrams from the peer.
6221    #[tokio::test]
6222    async fn forwarder_rejects_datagrams_from_another_source() {
6223        let local = Arc::new(UdpSocket::bind("127.0.0.1:0").await.unwrap());
6224        let peer = UdpSocket::bind("127.0.0.1:0").await.unwrap();
6225        let intruder = UdpSocket::bind("127.0.0.1:0").await.unwrap();
6226        let stats = Arc::new(Counters::default());
6227        let (mut rx, _guard) = spawn_dedicated_socket_forwarder(
6228            Arc::clone(&local),
6229            peer.local_addr().unwrap(),
6230            stats,
6231            1500,
6232        );
6233        let local_addr = local.local_addr().unwrap();
6234        intruder.send_to(b"injected", local_addr).await.unwrap();
6235        peer.send_to(b"genuine", local_addr).await.unwrap();
6236        let got = tokio::time::timeout(Duration::from_secs(2), rx.recv())
6237            .await
6238            .expect("no genuine datagram")
6239            .expect("recv");
6240        assert_eq!(&got[..], b"genuine");
6241        assert!(
6242            tokio::time::timeout(Duration::from_millis(200), rx.recv())
6243                .await
6244                .is_err(),
6245            "a datagram from a third source must never be forwarded"
6246        );
6247    }
6248
6249    /// An ACKACK measures the RTT from the matching ACK's send time.
6250    #[tokio::test(start_paused = true)]
6251    async fn ackack_updates_the_receiver_rtt() {
6252        let (mut driver, _rx) = test_driver(8192).await;
6253        assert_eq!(driver.receiver.rtt(), crate::arq::rtt::INITIAL_RTT);
6254        driver
6255            .ingress(Bytes::from(data_bytes(0, 0, b"x")))
6256            .expect("data");
6257        tokio::time::advance(Duration::from_millis(10)).await;
6258        driver.tick_engines();
6259        let ack = driver
6260            .outbound_control
6261            .iter()
6262            .find_map(|bytes| match ControlPacket::parse(bytes) {
6263                Ok(ControlPacket::Ack(a)) => Some(a),
6264                _ => None,
6265            })
6266            .expect("a full ACK");
6267        let ackack = crate::packet::misc::AckAckPacket {
6268            ack_number: ack.ack_number,
6269            timestamp: crate::packet::SrtTimestamp::ZERO,
6270            dest_socket_id: crate::packet::SocketId::from_wire(1),
6271            libsrt_pad: false,
6272        };
6273        let mut bytes = alloc::vec![0u8; ControlPacket::AckAck(ackack).serialized_len()];
6274        ControlPacket::AckAck(ackack)
6275            .serialize_into(&mut bytes)
6276            .expect("serialize ackack");
6277        tokio::time::advance(Duration::from_millis(20)).await;
6278        driver.ingress(Bytes::from(bytes)).expect("ackack");
6279        assert!(
6280            driver.receiver.rtt() < crate::arq::rtt::INITIAL_RTT,
6281            "the RTT sample must lower the estimate, got {:?}",
6282            driver.receiver.rtt()
6283        );
6284        assert!(driver.receiver.rtt() > Duration::from_millis(10));
6285    }
6286
6287    /// A single-sequence DROPREQ is well-formed and must stop the NAK.
6288    #[tokio::test(start_paused = true)]
6289    async fn single_sequence_dropreq_stops_the_nak() {
6290        let (mut driver, _rx) = test_driver(8192).await;
6291        driver
6292            .ingress(Bytes::from(data_bytes(0, 1_000_000_000, b"a")))
6293            .expect("data 0");
6294        driver
6295            .ingress(Bytes::from(data_bytes(2, 1_000_000_000, b"c")))
6296            .expect("data 2");
6297        tokio::time::advance(Duration::from_millis(10)).await;
6298        driver.tick_engines();
6299        assert!(driver.receiver.loss_list_len() > 0, "seq 1 is missing");
6300        driver
6301            .ingress(Bytes::from(dropreq_bytes(1, 1)))
6302            .expect("dropreq 1..=1");
6303        assert_eq!(
6304            driver.receiver.loss_list_len(),
6305            0,
6306            "a single-sequence DROPREQ must clear the loss list"
6307        );
6308    }
6309
6310    /// The Keep-Alive carries the connection clock, not a zero timestamp.
6311    #[tokio::test(start_paused = true)]
6312    async fn keepalive_carries_the_connection_clock() {
6313        let (mut driver, _rx) = test_driver(8192).await;
6314        tokio::time::advance(Duration::from_secs(3)).await;
6315        driver.tick_engines();
6316        let keepalive = driver
6317            .outbound_control
6318            .iter()
6319            .find_map(|bytes| match SrtPacket::parse(bytes) {
6320                Ok(SrtPacket::Control(ControlPacket::KeepAlive(ka))) => Some(ka),
6321                _ => None,
6322            })
6323            .expect("a keep-alive");
6324        assert!(
6325            keepalive.timestamp.value() >= 3_000_000,
6326            "keep-alive timestamp {} ~= 0",
6327            keepalive.timestamp.value()
6328        );
6329    }
6330
6331    /// An expired pacing slot is dropped, not replayed as credit.
6332    #[tokio::test(start_paused = true)]
6333    async fn idle_pacing_credit_expires_at_the_exact_deadline() {
6334        let (mut driver, _rx) = test_driver(8192).await;
6335        assert!(driver.outbound_data.is_empty());
6336        driver.next_data_send_at = Some(Instant::now());
6337        driver.flush_outbound().await.expect("flush");
6338        assert!(driver.next_data_send_at.is_none());
6339    }
6340
6341    #[tokio::test]
6342    async fn task_guard_aborts_its_task_on_drop() {
6343        use core::sync::atomic::AtomicBool;
6344        struct MarkOnDrop(Arc<AtomicBool>);
6345        impl Drop for MarkOnDrop {
6346            fn drop(&mut self) {
6347                self.0.store(true, Ordering::SeqCst);
6348            }
6349        }
6350        let dropped = Arc::new(AtomicBool::new(false));
6351        let marker = MarkOnDrop(Arc::clone(&dropped));
6352        let guard = TaskGuard(Some(tokio::spawn(async move {
6353            let _marker = marker;
6354            std::future::pending::<()>().await;
6355        })));
6356        drop(guard);
6357        let mut aborted = false;
6358        for _ in 0..1_000 {
6359            tokio::task::yield_now().await;
6360            if dropped.load(Ordering::SeqCst) {
6361                aborted = true;
6362                break;
6363            }
6364        }
6365        assert!(aborted, "dropping a TaskGuard must abort its task");
6366    }
6367
6368    #[cfg(feature = "crypto")]
6369    #[test]
6370    fn key_set_clear_empties_the_slot() {
6371        let mut keys = KeySet::default();
6372        keys.install(KeyParity::Even, alloc::vec![1u8; 16], [0u8; 16]);
6373        assert!(!keys.is_empty());
6374        keys.clear(KeyParity::Even);
6375        assert!(keys.is_empty());
6376    }
6377
6378    #[cfg(feature = "crypto")]
6379    #[tokio::test]
6380    async fn key_refresh_does_not_clear_the_active_parity() {
6381        let (mut driver, _rx) = test_driver(8192).await;
6382        driver
6383            .tx_keys
6384            .install(KeyParity::Even, alloc::vec![1u8; 16], [0u8; 16]);
6385        driver
6386            .tx_keys
6387            .install(KeyParity::Odd, alloc::vec![2u8; 16], [0u8; 16]);
6388        driver.tx_parity = KeyParity::Even;
6389        driver.retire_deferred = Some(KeyParity::Even);
6390        driver.advance_key_refresh();
6391        assert!(
6392            driver.tx_keys.get(KeyParity::Even).is_some(),
6393            "the active parity must never be retired"
6394        );
6395    }
6396
6397    #[cfg(feature = "crypto")]
6398    #[tokio::test]
6399    async fn key_refresh_clears_a_retired_parity() {
6400        let (mut driver, _rx) = test_driver(8192).await;
6401        driver
6402            .tx_keys
6403            .install(KeyParity::Even, alloc::vec![1u8; 16], [0u8; 16]);
6404        driver
6405            .tx_keys
6406            .install(KeyParity::Odd, alloc::vec![2u8; 16], [0u8; 16]);
6407        driver.tx_parity = KeyParity::Even;
6408        driver.retire_deferred = Some(KeyParity::Odd);
6409        driver.advance_key_refresh();
6410        assert!(
6411            driver.tx_keys.get(KeyParity::Odd).is_none(),
6412            "a retired (non-active) parity is wiped"
6413        );
6414        assert!(driver.tx_keys.get(KeyParity::Even).is_some());
6415    }
6416
6417    #[cfg(feature = "crypto")]
6418    #[tokio::test]
6419    async fn announce_key_uses_the_default_sek_length_when_unset() {
6420        let (mut driver, _rx) = test_driver(8192).await;
6421        driver.crypto_passphrase = zeroize::Zeroizing::new(b"pw".to_vec());
6422        assert_eq!(driver.crypto_key_len, 0);
6423        driver.announce_key(KeyParity::Even);
6424        let installed = driver.tx_keys.get(KeyParity::Even).expect("installed");
6425        assert_eq!(installed.0.len(), DEFAULT_SEK_LEN);
6426        assert_eq!(DEFAULT_SEK_LEN, 16);
6427    }
6428
6429    #[cfg(feature = "crypto")]
6430    #[tokio::test]
6431    async fn resend_pending_km_repeats_a_due_key_material_request() {
6432        let (mut driver, _rx) = test_driver(8192).await;
6433        driver.km_pending = Some(PendingKm {
6434            parity: KeyParity::Even,
6435            salt: [0u8; 16],
6436            datagram: alloc::vec![9u8, 9],
6437            resend_at: Instant::now() - Duration::from_millis(1),
6438        });
6439        driver.resend_pending_km();
6440        assert_eq!(driver.outbound_control.len(), 1);
6441        assert_eq!(driver.outbound_control[0], alloc::vec![9u8, 9]);
6442    }
6443}
6444
6445#[cfg(test)]
6446mod cookie_binding_tests {
6447    use super::*;
6448
6449    #[test]
6450    fn addr_to_u64_distinguishes_host_and_port() {
6451        let a: std::net::SocketAddr = "127.0.0.1:4001".parse().unwrap();
6452        let b: std::net::SocketAddr = "127.0.0.1:4002".parse().unwrap();
6453        let c: std::net::SocketAddr = "127.0.0.2:4001".parse().unwrap();
6454        assert_ne!(addr_to_u64(&a), addr_to_u64(&b));
6455        assert_ne!(addr_to_u64(&a), addr_to_u64(&c));
6456        assert_eq!(addr_to_u64(&a), addr_to_u64(&a));
6457    }
6458
6459    #[test]
6460    fn cookie_peer_key_binds_the_address_and_the_socket_id() {
6461        let a: std::net::SocketAddr = "127.0.0.1:4001".parse().unwrap();
6462        let b: std::net::SocketAddr = "127.0.0.1:4002".parse().unwrap();
6463        assert_ne!(cookie_peer_key(&a, 1), cookie_peer_key(&a, 2));
6464        assert_ne!(cookie_peer_key(&a, 1), cookie_peer_key(&b, 1));
6465        assert_eq!(cookie_peer_key(&a, 1), cookie_peer_key(&a, 1));
6466    }
6467
6468    #[test]
6469    fn unix_time_bucket_tracks_the_current_minute() {
6470        let before = std::time::SystemTime::now()
6471            .duration_since(std::time::UNIX_EPOCH)
6472            .expect("after the epoch")
6473            .as_secs()
6474            / 60;
6475        let bucket = u64::from(unix_time_bucket());
6476        assert!(
6477            bucket.abs_diff(before) <= 1,
6478            "bucket {bucket} is not the current minute ({before})"
6479        );
6480    }
6481}