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