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