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 std::hash::{Hash, Hasher};
70use std::sync::atomic::{AtomicU64, Ordering};
71use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
72
73use alloc::collections::VecDeque;
74use core::time::Duration;
75
76use bytes::Bytes;
77use tokio::net::UdpSocket;
78use tokio::sync::mpsc;
79use tokio::time::Instant;
80use tokio_util::sync::CancellationToken;
81use tokio_util::task::TaskTracker;
82
83use crate::arq::seq::{seq_diff, seq_in_closed_range, seq_lt, seq_next};
84use crate::arq::{Receiver as ArqReceiver, Sender as ArqSender};
85use crate::caller::CallerHandshake;
86use crate::error::{Error, Result};
87use crate::handshake_sm::{self, HandshakeConfig, HandshakeOutput, RejectionReason, derive_cookie};
88use crate::listener::{ListenerHandshake, ListenerHandshakeState};
89use crate::livecc::{LiveCC, MaxBwConfig};
90use crate::packet::data::next_message_number;
91use crate::packet::misc::{KeepAlivePacket, ShutdownPacket};
92use crate::packet::{
93    ControlPacket, DropReqPacket, EncryptionField, EncryptionKeyField, HandshakeExtensionFlags,
94    HandshakeExtensions, HandshakePacket, HandshakeType, SEQ_NUMBER_MASK, SRT_HEADER_LEN,
95    SrtPacket,
96};
97use crate::tsbpd::{TickOutcome, TsbpdScheduler};
98
99// ===========================================================================
100// Constants
101// ===========================================================================
102
103/// Default for [`IoConfig::max_datagram`]: one Ethernet MTU of UDP payload.
104const DEFAULT_MAX_DATAGRAM: usize = 1500;
105/// Smallest accepted [`IoConfig::max_datagram`]: a full SRT header (16 bytes)
106/// plus room for a control CIF. A smaller request is clamped up to this (and a
107/// larger one down to [`MAX_MAX_DATAGRAM`]).
108pub const MIN_MAX_DATAGRAM: usize = 64;
109/// Largest accepted [`IoConfig::max_datagram`]: the biggest UDP payload.
110pub const MAX_MAX_DATAGRAM: usize = 65_535;
111
112/// Timeouts and sizes for the tokio adapter ([`SrtSocket::connect_with`],
113/// [`SrtListener::bind_with`]).
114///
115/// Every field has a documented default; use the `with_*` builders so new
116/// fields can be added without breaking callers.
117#[derive(Debug, Clone, Copy, PartialEq, Eq)]
118#[non_exhaustive]
119pub struct IoConfig {
120    /// Largest datagram accepted from the network (bytes). Default 1500. A
121    /// larger datagram is dropped and counted in [`SocketStats::rx_oversize`]
122    /// (UDP would otherwise truncate it silently). Values below
123    /// [`MIN_MAX_DATAGRAM`] are clamped up to it.
124    pub max_datagram: usize,
125    /// Bound on resolving the remote address and binding the local socket.
126    /// Default 10 s.
127    pub connect: Duration,
128    /// Budget for the whole caller handshake. Default 5 s (the previous
129    /// `HANDSHAKE_TIMEOUT` constant).
130    pub handshake: Duration,
131    /// Longest silence from a connected peer before the connection is torn
132    /// down. Default 5 s: libsrt's `SRTO_PEERIDLETIMEO` default of 5000 ms (the
133    /// previous `PEER_IDLE_TIMEOUT` constant).
134    pub read_idle: Duration,
135    /// Longest a single `send_to` may take. Default 5 s.
136    pub write: Duration,
137}
138
139impl Default for IoConfig {
140    fn default() -> Self {
141        IoConfig {
142            max_datagram: DEFAULT_MAX_DATAGRAM,
143            connect: Duration::from_secs(10),
144            handshake: Duration::from_secs(5),
145            read_idle: Duration::from_secs(5),
146            write: Duration::from_secs(5),
147        }
148    }
149}
150
151impl IoConfig {
152    /// Set [`max_datagram`](Self::max_datagram), clamped up to [`MIN_MAX_DATAGRAM`].
153    #[must_use]
154    pub fn with_max_datagram(mut self, n: usize) -> Self {
155        self.max_datagram = n.clamp(MIN_MAX_DATAGRAM, MAX_MAX_DATAGRAM);
156        self
157    }
158
159    /// Set [`connect`](Self::connect).
160    #[must_use]
161    pub fn with_connect(mut self, d: Duration) -> Self {
162        self.connect = d;
163        self
164    }
165
166    /// Set [`handshake`](Self::handshake).
167    #[must_use]
168    pub fn with_handshake(mut self, d: Duration) -> Self {
169        self.handshake = d;
170        self
171    }
172
173    /// Set [`read_idle`](Self::read_idle).
174    #[must_use]
175    pub fn with_read_idle(mut self, d: Duration) -> Self {
176        self.read_idle = d;
177        self
178    }
179
180    /// Set [`write`](Self::write).
181    #[must_use]
182    pub fn with_write(mut self, d: Duration) -> Self {
183        self.write = d;
184        self
185    }
186}
187
188/// Reads one datagram into the reusable `scratch` buffer (length
189/// `max + 1`) and returns it as an exactly-sized `Bytes`, or `None` for an
190/// oversize datagram (which has been counted and dropped).
191///
192/// The copy-out is deliberate: a `Bytes` that was a view into a shared receive
193/// chunk would keep the WHOLE chunk alive for as long as that one packet is
194/// staged behind a gap, queued for the application or held by it (on a shared
195/// listener socket, interleaved connections multiply that). One small
196/// allocation per datagram bounds retained memory to the datagrams actually
197/// held; the payload is still not copied again on its way to the application
198/// (`Driver::release` slices it).
199async fn recv_datagram(
200    udp: &UdpSocket,
201    scratch: &mut [u8],
202    max: usize,
203    oversize: &AtomicU64,
204) -> std::io::Result<Option<(Bytes, std::net::SocketAddr)>> {
205    // `scratch` is `max + 1` long: a datagram of max+1 bytes proves "larger
206    // than max" (UDP would otherwise truncate it silently).
207    let (n, src) = udp.recv_from(scratch).await?;
208    if n > max {
209        oversize.fetch_add(1, Ordering::Relaxed);
210        return Ok(None);
211    }
212    Ok(Some((Bytes::copy_from_slice(&scratch[..n]), src)))
213}
214
215/// One [`RouteTable`] entry: the accepted connection's ingress channel, plus
216/// the source address it was accepted from. libsrt demultiplexes its
217/// multiplexed listener socket by Destination Socket ID, not source address
218/// (draft §4.3.1; `CRcvQueue::worker` dispatches on it in `srtcore/core.cpp`)
219/// — the address is kept here only to *check* it against the datagram that
220/// claims this ID (see [`routing_pump`]), so a spoofed ID from
221/// the wrong peer cannot be injected into someone else's session.
222#[derive(Debug, Clone)]
223struct RouteEntry {
224    addr: std::net::SocketAddr,
225    tx: mpsc::Sender<Bytes>,
226    /// Shared with that connection's [`Driver`]/[`SrtSocket`], so a drop
227    /// here (channel full) is counted where [`SrtSocket::stats`] can see it.
228    stats: Arc<Counters>,
229}
230
231/// Shared per-socket demultiplexing table (issue #1029): maps an accepted
232/// connection's own Socket ID to its [`RouteEntry`]. A [`SrtListener`]'s
233/// single bound socket is used by every connection it has accepted, so —
234/// unlike a [`SrtSocket::connect`]'s own dedicated, unshared socket — the
235/// listener needs exactly one task reading the socket and routing each
236/// datagram, never one `recv_from` call per connection racing another's on
237/// the same socket (see the module doc on [`SrtListener`]).
238type RouteTable = Arc<Mutex<std::collections::HashMap<u32, RouteEntry>>>;
239
240/// Lock `mutex`, recovering the guard if a previous holder panicked.
241///
242/// A poisoned lock must never turn into a second panic — least of all inside
243/// a `Drop` (see [`RouteCleanup`]) or the routing pump, which would then take
244/// the whole listener down for one panicking connection task. Every critical
245/// section here is a single `HashMap` insert/remove/get that cannot leave the
246/// map half-updated, so the state behind a poisoned lock is still consistent
247/// (issue #1134).
248fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
249    mutex.lock().unwrap_or_else(PoisonError::into_inner)
250}
251
252/// RAII guard that removes this connection's entry from the listener's shared
253/// [`RouteTable`] when dropped. A stale route was a real leak: dropping a
254/// listener-accepted [`SrtSocket`] runs `Drop::drop` → `handle.abort()`,
255/// which cancels the driver task at its next await point and drops its
256/// future (and everything the future owns) without ever reaching the
257/// explicit cleanup that used to sit at the tail of [`Driver::run`]'s loop —
258/// that code only ran on a *normal* return, never on abort. A `Drop` impl
259/// runs either way, since it fires when this guard's owner (the future) is
260/// dropped, not only when the function body finishes.
261struct RouteCleanup(Option<(u32, RouteTable)>);
262
263impl Drop for RouteCleanup {
264    fn drop(&mut self) {
265        if let Some((id, routes)) = self.0.take() {
266            lock(&routes).remove(&id);
267        }
268    }
269}
270
271/// Aborts the wrapped background task when dropped. A [`SrtSocket::connect`]ed
272/// caller's dedicated-socket forwarder task (`spawn_dedicated_socket_forwarder`)
273/// holds its own `Arc<UdpSocket>` clone and loops on `recv_from` forever —
274/// dropping the `Driver`'s own reference alone does not stop it, so without
275/// this guard the forwarder keeps the local port bound indefinitely after the
276/// `SrtSocket` is dropped, and a later attempt to bind that same port fails
277/// with `AddrInUse` (item 3). `None` for a listener-accepted connection,
278/// which has no per-connection forwarder to abort.
279struct TaskGuard(Option<tokio::task::JoinHandle<()>>);
280
281impl Drop for TaskGuard {
282    fn drop(&mut self) {
283        if let Some(handle) = self.0.take() {
284            handle.abort();
285        }
286    }
287}
288
289/// Capacity of a per-connection inbound-datagram channel (the dedicated
290/// forwarder for a [`SrtSocket::connect`]ed caller, or a [`SrtListener`]'s
291/// per-accepted-connection route) — bounded so a peer that floods faster than
292/// the driver task's tick loop can drain does not grow this queue (and this
293/// process's memory) without bound; excess datagrams are dropped, not
294/// buffered (item 4).
295const RX_CHANNEL_CAPACITY: usize = 4096;
296/// Capacity of a [`SrtListener`]'s candidate-new-connection queue (datagrams
297/// the routing pump could not match to any accepted connection). Bounded for
298/// the same reason as [`RX_CHANNEL_CAPACITY`] — a handshake flood must not
299/// grow this queue without bound even though [`MAX_PENDING`] already caps how
300/// many of those candidates get to hold engine state.
301const UNROUTED_CHANNEL_CAPACITY: usize = 1024;
302/// Capacity of the delivered-payload channel from a connection's driver task
303/// to its [`SrtSocket`] handle. Bounded so a slow/stalled application that
304/// never calls [`SrtSocket::recv`] cannot make TSBPD-released payloads pile
305/// up in memory without bound purely from network input — matching this
306/// adapter's live (TLPKTDROP) delivery philosophy of dropping rather than
307/// buffering forever (when TLPKTDROP was negotiated, §4.6).
308const DELIVER_CHANNEL_CAPACITY: usize = 4096;
309/// Capacity of the application-to-driver payload channel
310/// ([`SrtSocket::send`]). Bounded so the application is paced by the driver
311/// instead of queueing without limit; the driver additionally stops draining
312/// it while the sender holds a full flow window of unacknowledged packets
313/// (see `Driver::send_window_open`).
314const SEND_CHANNEL_CAPACITY: usize = 1024;
315
316/// Floor on how soon [`Driver::poll_timeout`] may ask to be woken: never a
317/// deadline in the past, and a 1 ms minimum cannot spin (it matches tokio's
318/// timer granularity).
319const MIN_WAKE: Duration = Duration::from_millis(1);
320/// Most DATA packets one `flush_outbound` pass sends, and the most pacing
321/// periods of catch-up credit a late wake may claim: with the ~1 ms timer
322/// granularity (`MIN_WAKE`) this lifts the idle-backlog drain ceiling from
323/// ~1000 packets/s to `PACING_BURST_CAP` x 1000 packets/s without ever
324/// dumping more than this many packets at once.
325const PACING_BURST_CAP: usize = 16;
326/// Initial TSBPD drift (zero: the scheduler estimates it from there).
327const DEFAULT_DRIFT_US: i64 = 0;
328/// Default max bandwidth (1 Gbps).
329const DEFAULT_MAX_BW: MaxBwConfig = MaxBwConfig::Set(125_000_000);
330/// How often an unanswered handshake request is re-sent. libsrt re-sends its
331/// handshake request every 250 ms until it is answered; the previous 15 s
332/// (three five-second receive timeouts) made one lost INDUCTION cost the
333/// whole connect budget.
334const HANDSHAKE_RETRANSMIT_PERIOD: Duration = Duration::from_millis(250);
335/// Floor on the handshake tick period, so an absurd
336/// [`HandshakeConfig::retransmit_after_ticks`] cannot make it zero (a zero
337/// `tokio::time::interval` period panics).
338const MIN_HANDSHAKE_TICK: Duration = Duration::from_millis(1);
339/// Keep-Alive period (`draft-sharabayko-srt-01` §3.2.3: "The default timeout
340/// for a keep-alive packet to be sent is 1 second", measured from the last
341/// time any packet — control or data — was sent).
342const KEEPALIVE_PERIOD: Duration = Duration::from_secs(1);
343/// Upper bound on concurrently in-progress listener handshakes. Every new
344/// source address that sends an INDUCTION allocates a [`PendingListener`]
345/// entry; without a cap, a flood of (possibly spoofed) handshake packets from
346/// many sources exhausts memory before any of them times out.
347const MAX_PENDING: usize = 1024;
348/// How often [`SrtListener::accept`] drives pending-handshake expiry and
349/// retransmits, independent of receive activity.
350const PENDING_TICK_INTERVAL: Duration = Duration::from_millis(100);
351/// How often the SYN-cookie key is replaced (§4.3.1.1 buckets the cookie's
352/// time input to one minute).
353const COOKIE_KEY_ROTATION: Duration = Duration::from_secs(60);
354/// How long an accepted connection's CONCLUSION response is remembered so a
355/// repeated CONCLUSION (the response was lost) can be answered again — a
356/// little longer than the Caller's own default connect budget ([`IoConfig::handshake`]).
357const RECENT_ACCEPT_TTL: Duration = Duration::from_secs(10);
358/// Cap on remembered CONCLUSION responses (one per recently accepted source
359/// address), the same bound as [`MAX_PENDING`].
360const MAX_RECENT_ACCEPTS: usize = MAX_PENDING;
361
362// ===========================================================================
363// Outbound queue
364// ===========================================================================
365//
366// Two separate queues, not one queue tagged per-item: §5.1.2 paces DATA
367// packets only — ACK/NAK/ACKACK/Keep-Alive control feedback must never be
368// throttled behind the pacing delay, or loss recovery (which rides on that
369// same control traffic) stalls along with it. A single FIFO queue with an
370// `is_data` tag on each item got this half right (pacing never delayed a
371// control packet that had already reached the *front*) but not the other
372// half: `flush_outbound` stopped at the first not-yet-due DATA packet and
373// never looked past it, so a control packet enqueued *behind* one — the
374// common case, since `tick_engines` queues retransmits before this cycle's
375// ACK/NAK — sat there just as throttled as if pacing applied to it too. Two
376// queues make that structurally impossible: control is always drained in
377// full before data pacing is even considered.
378
379/// Per-connection counters for datagrams a bounded internal channel dropped
380/// because it was full (item 4) — this adapter's own internal backpressure,
381/// distinct from wire-level loss ARQ/TLPKTDROP already account for. Shared
382/// (via `Arc`) between a [`Driver`] and the [`SrtSocket`] handle so
383/// [`SrtSocket::stats`] reads live counts, not a snapshot frozen at spawn.
384#[derive(Debug, Default)]
385struct Counters {
386    rx_dropped: AtomicU64,
387    deliver_dropped: AtomicU64,
388    late_dropped: AtomicU64,
389    rx_oversize: AtomicU64,
390}
391
392/// A snapshot of one connection's `Counters`, returned by
393/// [`SrtSocket::stats`].
394#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
395#[non_exhaustive]
396pub struct SocketStats {
397    /// Inbound datagrams dropped because the per-connection ingress channel
398    /// was full (the peer sent faster than this connection's driver task
399    /// could drain).
400    pub rx_dropped: u64,
401    /// TSBPD-released payloads dropped because the application wasn't
402    /// calling [`SrtSocket::recv`] fast enough to keep the delivery channel
403    /// from filling.
404    pub deliver_dropped: u64,
405    /// DATA packets ignored because they were not ahead of the delivery
406    /// cursor: duplicates, retransmissions of what was already delivered or
407    /// given up on, and stale sequence numbers (never staged).
408    pub late_dropped: u64,
409    /// Datagrams larger than [`IoConfig::max_datagram`], dropped rather than
410    /// truncated.
411    pub rx_oversize: u64,
412}
413
414// ===========================================================================
415// SrtSocket — a handle to an established SRT connection
416// ===========================================================================
417
418/// What [`SrtSocket::spawn`] needs to build one connection's engines and
419/// driver task.
420struct ConnParams {
421    udp: Arc<UdpSocket>,
422    peer_addr: std::net::SocketAddr,
423    rx: mpsc::Receiver<Bytes>,
424    stats: Arc<Counters>,
425    route_cleanup: RouteCleanup,
426    forwarder_guard: TaskGuard,
427    /// For a listener-accepted connection: keeps the listener's tasks (and so
428    /// its socket) alive for as long as this connection is.
429    life: Option<Arc<ListenerLife>>,
430    /// [`IoConfig::read_idle`] for this connection.
431    read_idle: Duration,
432    /// [`IoConfig::write`] for this connection.
433    write: Duration,
434    our_initial_seq: u32,
435    peer_initial_seq: u32,
436    peer_socket_id: u32,
437    /// `TsbpdTimeBase` (§4.5.1.1, rule 12): `T_NOW - HSREQ_TIMESTAMP`, with
438    /// `T_NOW` measured from `epoch` — so `-(the peer's handshake timestamp)`
439    /// when `epoch` is the instant that handshake packet arrived.
440    tsbpd_time_base: i64,
441    tsbpd_delay_ms: u64,
442    epoch: Instant,
443    /// The negotiated Maximum Flow Window Size (§3.2.1): the smaller of the
444    /// two sides' values.
445    max_flow_window: u32,
446    /// The negotiated MTU (§3.2.1): the smaller of the two sides' values.
447    mtu: u32,
448    /// Whether Too-Late Packet Drop was negotiated (the `TLPKTDROP` flag both
449    /// sides advertised, §3.2.1.1.1): only then may the receiver skip a gap.
450    tlpkt_drop: bool,
451}
452
453/// A handle to an established SRT connection over UDP.
454///
455/// Created by [`SrtSocket::connect`] (caller role) or
456/// [`SrtListener::accept`] (listener role). The protocol itself runs on a
457/// background [`tokio`] task the handle owns; [`send`](Self::send) enqueues an
458/// application payload and [`recv`](Self::recv) awaits a delivered one.
459/// Dropping the handle sends the peer a SHUTDOWN (§3.2.7) and aborts the
460/// driver task.
461#[derive(Debug)]
462pub struct SrtSocket {
463    peer_addr: std::net::SocketAddr,
464    /// Application payloads flowing to the driver task for transmission.
465    to_driver: mpsc::Sender<Bytes>,
466    /// TSBPD/ARQ-delivered payloads flowing back from the driver task.
467    from_driver: mpsc::Receiver<Bytes>,
468    /// The driver task; aborted on drop.
469    driver: Option<tokio::task::JoinHandle<()>>,
470    stats: Arc<Counters>,
471    /// The connection's socket, kept to send the SHUTDOWN from `Drop`.
472    udp: Arc<UdpSocket>,
473    /// The peer's SRT Socket ID — the SHUTDOWN's Destination Socket ID.
474    peer_socket_id: u32,
475    /// The connection epoch, for the SHUTDOWN's wire timestamp.
476    epoch: Instant,
477    /// Keeps a listener's background tasks alive while this accepted
478    /// connection is; `None` for a [`connect`](Self::connect)ed caller.
479    /// Declared last so it drops after the SHUTDOWN in `Drop`.
480    _life: Option<Arc<ListenerLife>>,
481}
482
483impl SrtSocket {
484    /// Connect to a remote SRT peer as a Caller.
485    ///
486    /// # Encryption
487    /// A [`HandshakeConfig`] with `crypto` set is refused with
488    /// [`Error::EncryptionUnsupported`] before any network I/O: this
489    /// adapter's data path does not encrypt, so an encrypted connection must
490    /// not be silently downgraded to plaintext. The sans-IO engines still
491    /// negotiate keys; the adapter will support encryption once its data path
492    /// does.
493    ///
494    /// # Errors
495    /// [`Error::Rejected`] carries the peer's [`RejectionReason`];
496    /// [`Error::HandshakeTimedOut`] means the peer never answered within the
497    /// handshake budget; [`Error::Handshake`] wraps an engine failure with the
498    /// stage it happened in.
499    pub async fn connect<A: tokio::net::ToSocketAddrs>(
500        remote_addr: A,
501        config: HandshakeConfig,
502    ) -> Result<Self> {
503        Self::connect_with(remote_addr, config, IoConfig::default()).await
504    }
505
506    /// Like [`Self::connect`], with explicit timeouts and datagram size.
507    pub async fn connect_with<A: tokio::net::ToSocketAddrs>(
508        remote_addr: A,
509        config: HandshakeConfig,
510        io: IoConfig,
511    ) -> Result<Self> {
512        refuse_crypto(&config)?;
513        let local = std::net::SocketAddr::from(([0, 0, 0, 0], 0));
514        Self::connect_from_with(local, remote_addr, config, io).await
515    }
516
517    /// Connect from a specific local address.
518    ///
519    /// # Encryption
520    /// Like [`Self::connect`], refuses a `crypto`-enabled
521    /// [`HandshakeConfig`] with [`Error::EncryptionUnsupported`] before any I/O.
522    pub async fn connect_from<A: tokio::net::ToSocketAddrs>(
523        local_addr: std::net::SocketAddr,
524        remote_addr: A,
525        config: HandshakeConfig,
526    ) -> Result<Self> {
527        Self::connect_from_with(local_addr, remote_addr, config, IoConfig::default()).await
528    }
529
530    /// Like [`Self::connect_from`], with explicit timeouts and datagram size.
531    pub async fn connect_from_with<A: tokio::net::ToSocketAddrs>(
532        local_addr: std::net::SocketAddr,
533        remote_addr: A,
534        config: HandshakeConfig,
535        io: IoConfig,
536    ) -> Result<Self> {
537        refuse_crypto(&config)?;
538        let max_datagram = io.max_datagram.clamp(MIN_MAX_DATAGRAM, MAX_MAX_DATAGRAM);
539        let socket = bounded(io.connect, "bind", async {
540            UdpSocket::bind(local_addr)
541                .await
542                .map_err(|e| io_err("bind", e))
543        })
544        .await?;
545        let peer = bounded(io.connect, "resolve", resolve_one(remote_addr)).await?;
546        let socket = Arc::new(socket);
547
548        // Both this Caller's own Socket ID and its ISN must be freshly
549        // generated per connection, not carried over from `config` (whose
550        // `initial_seq_number` a caller may leave at its `0` default) —
551        // `draft-sharabayko-srt-01` §3/§4.3.1.1 expects both random, and a
552        // fixed or predictable pair lets an off-path party that knows the
553        // 4-tuple guess a live connection's wire identifiers outright.
554        let own_socket_id = random_socket_id()?;
555        let mut config = config;
556        config.initial_seq_number = random_isn()?;
557        let mut hs = CallerHandshake::new(own_socket_id, config.clone());
558
559        // Send INDUCTION.
560        let induction = hs.start().map_err(|e| handshake_err("caller start", e))?;
561        send_bounded(&socket, &induction, peer, io.write, "send induction").await?;
562
563        // Re-send an unanswered request every `HANDSHAKE_RETRANSMIT_PERIOD`
564        // (the engine counts `retransmit_after_ticks` ticks per retransmit),
565        // and give up at `IoConfig::handshake` whatever the retry budget says.
566        let tick_period = (HANDSHAKE_RETRANSMIT_PERIOD / config.retransmit_after_ticks.max(1))
567            .max(MIN_HANDSHAKE_TICK);
568        let mut ticker = tokio::time::interval_at(Instant::now() + tick_period, tick_period);
569        ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
570        let deadline = Instant::now() + io.handshake;
571        let mut scratch = vec![0u8; max_datagram + 1];
572        // The handshake loop has no `SocketStats` yet; oversize datagrams are
573        // simply ignored (the real peer retransmits).
574        let hs_oversize = AtomicU64::new(0);
575
576        loop {
577            enum Event {
578                Datagram(Bytes, std::net::SocketAddr),
579                Oversize,
580                Tick,
581                Deadline,
582            }
583            let event = tokio::select! {
584                r = recv_datagram(&socket, &mut scratch, max_datagram, &hs_oversize) => {
585                    match r.map_err(|e| io_err("recv hs", e))? {
586                        Some((bytes, src)) => Event::Datagram(bytes, src),
587                        None => Event::Oversize,
588                    }
589                }
590                _ = ticker.tick() => Event::Tick,
591                _ = tokio::time::sleep_until(deadline) => Event::Deadline,
592            };
593
594            let (outputs, received) = match event {
595                Event::Deadline => {
596                    return Err(Error::HandshakeTimedOut {
597                        stage: "caller connect",
598                    });
599                }
600                Event::Oversize => continue,
601                Event::Tick => (hs.tick(), None),
602                Event::Datagram(bytes, src) => {
603                    // A packet from anyone but the peer we're connecting to
604                    // (some unrelated traffic that happened to land on this
605                    // freshly bound port) must not fail the connect — ignore
606                    // it and keep waiting for the real peer.
607                    if src != peer {
608                        continue;
609                    }
610                    // Likewise, a packet that isn't a well-formed Handshake
611                    // control packet right now (a stray Keep-Alive, a
612                    // resent/duplicate reply, garbage) must not fail the
613                    // connect either — only a genuine handshake rejection or
614                    // timeout does that.
615                    let Ok(outputs) = hs.feed_bytes(&bytes) else {
616                        continue;
617                    };
618                    (outputs, Some(bytes))
619                }
620            };
621
622            for outcome in outputs {
623                match outcome {
624                    HandshakeOutput::Send(bytes) => {
625                        send_bounded(&socket, &bytes, peer, io.write, "send hs").await?;
626                    }
627                    HandshakeOutput::Connected(params) => {
628                        // `Connected` only ever comes out of `feed_bytes`, so
629                        // the datagram that completed the handshake is still
630                        // in `buf`. The peer's ISN (seeds ARQ/TSBPD sequence
631                        // tracking) and handshake timestamp (seeds the TSBPD
632                        // time base, rule 12) are carried in those bytes; the
633                        // peer's SRT Socket ID (the wire `dest_socket_id`
634                        // for every outgoing packet) is the negotiated
635                        // `params.peer_socket_id` — the two ids are unrelated
636                        // values (§3).
637                        //
638                        // `peer_handshake` errors (rather than defaulting to
639                        // 0) if the very bytes that just drove the handshake
640                        // state machine to `Connected` fail to re-parse as a
641                        // Handshake control packet — an internal
642                        // inconsistency. A silent `0` fallback would be
643                        // indistinguishable from a genuine ISN of 0 and would
644                        // seed ARQ/TSBPD sequence tracking wrong for the life
645                        // of the connection.
646                        let received = received.ok_or(Error::InvalidField {
647                            what: "handshake",
648                            reason: "Connected without a received datagram",
649                        })?;
650                        let peer_hs = peer_handshake(&received)?;
651                        let epoch = Instant::now();
652                        // This socket is exclusively this connection's own
653                        // (bound fresh in `connect_from`, never shared) — no
654                        // demux table needed, just a forwarder task unifying
655                        // it with the same `Driver::rx` path a
656                        // listener-accepted connection uses (issue #1029).
657                        let stats = Arc::new(Counters::default());
658                        let (rx, forwarder) = spawn_dedicated_socket_forwarder(
659                            Arc::clone(&socket),
660                            peer,
661                            Arc::clone(&stats),
662                            max_datagram,
663                        );
664                        return Ok(SrtSocket::spawn(ConnParams {
665                            udp: socket,
666                            peer_addr: peer,
667                            rx,
668                            stats,
669                            route_cleanup: RouteCleanup(None),
670                            forwarder_guard: TaskGuard(Some(forwarder)),
671                            life: None,
672                            read_idle: io.read_idle,
673                            write: io.write,
674                            our_initial_seq: config.initial_seq_number,
675                            peer_initial_seq: peer_hs.initial_seq_number,
676                            peer_socket_id: params.peer_socket_id,
677                            tsbpd_time_base: tsbpd_time_base_from(peer_hs.timestamp_us),
678                            tsbpd_delay_ms: u64::from(params.latency_ms),
679                            epoch,
680                            max_flow_window: params.max_flow_window_size,
681                            mtu: params.mtu,
682                            tlpkt_drop: params.flags.tlpktdrop(),
683                        }));
684                    }
685                    HandshakeOutput::Rejected(reason) => return Err(Error::Rejected(reason)),
686                    HandshakeOutput::TimedOut => {
687                        return Err(Error::HandshakeTimedOut {
688                            stage: "caller retransmit budget",
689                        });
690                    }
691                }
692            }
693        }
694    }
695
696    /// Build the engine state, spawn its background driver task, and return
697    /// the [`SrtSocket`] handle wired to it.
698    fn spawn(p: ConnParams) -> Self {
699        let (to_driver, app_out) = mpsc::channel::<Bytes>(SEND_CHANNEL_CAPACITY);
700        let (deliver, from_driver) = mpsc::channel(DELIVER_CHANNEL_CAPACITY);
701
702        let udp = Arc::clone(&p.udp);
703        let (peer_addr, peer_socket_id, epoch) = (p.peer_addr, p.peer_socket_id, p.epoch);
704        let stats = Arc::clone(&p.stats);
705        let life = p.life.clone();
706        let driver = Driver::new(p, deliver);
707        let handle = tokio::spawn(driver.run(app_out));
708
709        SrtSocket {
710            peer_addr,
711            to_driver,
712            from_driver,
713            driver: Some(handle),
714            stats,
715            udp,
716            peer_socket_id,
717            epoch,
718            _life: life,
719        }
720    }
721
722    /// Enqueue a payload for transmission to the peer.
723    ///
724    /// Returns once the payload is handed to the driver task — actual
725    /// transmission, ACK/NAK handling, and retransmission all happen on that
726    /// task. Waits (applying backpressure) while the sender already holds a
727    /// full flow window of unacknowledged packets or the hand-off queue is
728    /// full. Fails only if the driver task has stopped (peer shut down, went
729    /// silent, or a connection error).
730    pub async fn send(&mut self, payload: &[u8]) -> Result<()> {
731        self.send_bytes(Bytes::copy_from_slice(payload)).await
732    }
733
734    /// Like [`send`](Self::send) but takes ownership of an already-built
735    /// [`Bytes`], so the hand-off to the driver task does not copy it.
736    pub async fn send_bytes(&mut self, payload: Bytes) -> Result<()> {
737        self.to_driver.send(payload).await.map_err(|_| Error::Io {
738            kind: std::io::ErrorKind::BrokenPipe,
739            context: "send",
740        })
741    }
742
743    /// The peer's socket address.
744    pub fn peer_addr(&self) -> std::net::SocketAddr {
745        self.peer_addr
746    }
747
748    /// Receive the next payload, waiting until one is available.
749    /// Returns `None` once the peer has shut down (or the driver task has
750    /// stopped) and no further payloads will arrive.
751    pub async fn recv(&mut self) -> Result<Option<Bytes>> {
752        Ok(self.from_driver.recv().await)
753    }
754
755    /// A snapshot of this connection's internal-backpressure drop counters
756    /// (item 4) — datagrams or delivered payloads this adapter's own bounded
757    /// channels dropped because they were full, not wire-level loss.
758    pub fn stats(&self) -> SocketStats {
759        SocketStats {
760            rx_dropped: self.stats.rx_dropped.load(Ordering::Relaxed),
761            deliver_dropped: self.stats.deliver_dropped.load(Ordering::Relaxed),
762            late_dropped: self.stats.late_dropped.load(Ordering::Relaxed),
763            rx_oversize: self.stats.rx_oversize.load(Ordering::Relaxed),
764        }
765    }
766}
767
768impl Drop for SrtSocket {
769    fn drop(&mut self) {
770        if let Some(handle) = self.driver.take() {
771            // Tell a still-connected peer we are leaving (§3.2.7) so it can
772            // close at once instead of waiting out its idle timeout. Not when
773            // the driver already ended: the peer shut down (or went silent)
774            // and has nothing left to be told.
775            if !handle.is_finished() {
776                let timestamp = crate::arq::duration_to_wire_us(
777                    Instant::now().saturating_duration_since(self.epoch),
778                );
779                send_shutdown(&self.udp, self.peer_addr, self.peer_socket_id, timestamp);
780            }
781            handle.abort();
782        }
783    }
784}
785
786/// The SHUTDOWN datagram (§3.2.7) for a peer.
787fn shutdown_datagram(peer_socket_id: u32, timestamp: u32) -> Option<Vec<u8>> {
788    let pkt = ControlPacket::Shutdown(ShutdownPacket {
789        timestamp,
790        dest_socket_id: peer_socket_id,
791        libsrt_pad: true,
792    });
793    let mut buf = vec![0u8; pkt.serialized_len()];
794    pkt.serialize_into(&mut buf).ok()?;
795    Some(buf)
796}
797
798/// Best-effort, non-blocking SHUTDOWN (§3.2.7) to `peer`, for `Drop`, where
799/// nothing can be awaited. A failure (socket buffer full, peer unreachable, or
800/// a socket that was never polled for writability) is ignored: the peer's idle
801/// timeout is the fallback.
802fn send_shutdown(udp: &UdpSocket, peer: std::net::SocketAddr, peer_socket_id: u32, timestamp: u32) {
803    if let Some(buf) = shutdown_datagram(peer_socket_id, timestamp) {
804        let _ = udp.try_send_to(&buf, peer);
805    }
806}
807
808// ===========================================================================
809// Driver — the per-connection background task
810// ===========================================================================
811
812/// One packet held by the receive staging buffer until TSBPD releases it: the
813/// whole datagram, header included. Keeping the datagram's own allocation —
814/// rather than copying the payload out of it — means a received packet is
815/// copied once (socket buffer to this `Vec`) and then handed to the
816/// application with the header drained off the front, never copied into a
817/// second allocation.
818type StagedDatagram = Bytes;
819
820/// The engine state driven by one connection's background task. Owns the
821/// socket, the sans-IO ARQ/TSBPD/LiveCC engines, and the outbound queue; runs
822/// the RX / app-send / next-deadline select loop in [`Driver::run`].
823struct Driver {
824    udp: Arc<UdpSocket>,
825    peer_addr: std::net::SocketAddr,
826    peer_socket_id: u32,
827    /// Shared with the [`SrtSocket`] handle (for [`SrtSocket::stats`]) and
828    /// whichever task feeds `rx` (the dedicated forwarder, or the listener's
829    /// routing pump via its `RouteEntry`), so a drop on either side of that
830    /// channel is counted in the one place the application can read it.
831    stats: Arc<Counters>,
832
833    // Inbound datagrams for *this* connection only (issue #1029). Fed by
834    // exactly one upstream demultiplexer: a per-connection forwarder task
835    // reading a dedicated socket ([`SrtSocket::connect_from`]), or the
836    // [`SrtListener`]'s single shared-socket routing pump. Never
837    // `udp.recv_from` directly — that would race every other task reading
838    // the same socket for whichever datagram arrives next, handing some of
839    // this connection's own traffic to a different connection (or the
840    // listener's own accept loop) at random. Bounded (item 4): a peer that
841    // floods faster than this task's tick loop drains gets its excess
842    // datagrams dropped, not buffered without bound.
843    rx: mpsc::Receiver<Bytes>,
844    // For a listener-accepted connection: removes this connection's entry
845    // from the shared route table on drop — including on `SrtSocket::Drop`'s
846    // task abort, not only a normal `run()` return (see [`RouteCleanup`]).
847    // Holds `None` for a `SrtSocket::connect`ed connection (no shared table).
848    _route_cleanup: RouteCleanup,
849    // For a `SrtSocket::connect`ed connection: aborts the dedicated-socket
850    // forwarder task on drop, so it stops holding the local UDP port open
851    // (see [`TaskGuard`]). `None` for a listener-accepted connection (no
852    // per-connection forwarder — the listener's routing pump outlives it).
853    _forwarder_guard: TaskGuard,
854    // Absolute time the last datagram (of any kind, valid or not) was
855    // received from the peer — the basis for the peer-idle timeout below.
856    last_rx_at: Instant,
857    // Absolute time the last datagram of any kind was sent to the peer — the
858    // basis for the Keep-Alive timer (§3.2.3).
859    last_tx_at: Instant,
860
861    // ARQ
862    sender: ArqSender,
863    receiver: ArqReceiver,
864
865    // TSBPD
866    tsbpd: TsbpdScheduler,
867
868    // LiveCC pacing
869    livecc: LiveCC,
870
871    next_message_number: u32,
872    next_send_seq: u32,
873
874    // Wall-clock epoch for `now: Duration`.
875    epoch: Instant,
876
877    // Staging: seq → received datagram, released to `deliver` by TSBPD/ARQ.
878    staged: std::collections::BTreeMap<u32, StagedDatagram>,
879
880    // Negotiated maximum flow window (§3.2.1): the cap on how far ahead of
881    // the delivery cursor a packet may be staged, and on how many
882    // unacknowledged packets the sender may hold.
883    max_flow_window: u32,
884
885    // Outbound datagram queues — separate so control can never queue behind
886    // a not-yet-due paced DATA packet (see the module doc above).
887    outbound_data: VecDeque<Vec<u8>>,
888    outbound_control: VecDeque<Vec<u8>>,
889
890    // Token-bucket pacing schedule (issue #1061): the earliest time the next
891    // DATA packet may go out. `None` means no DATA packet is currently
892    // pacing-blocked (the queue is empty of DATA, or was last drained with
893    // room to spare). Advanced by `LiveCC::on_ack_received()`'s period each
894    // time a DATA packet is actually sent, *from whichever is later of the
895    // previous schedule slot or now* — so a burst that arrives after this
896    // connection was otherwise idle (RX/tick-bound) sends immediately
897    // instead of being penalized for the gap, while a sustained flood is
898    // still throttled to the configured rate. This replaces a real
899    // `tokio::time::sleep` per DATA packet in `flush_outbound`, which — even
900    // at a sub-millisecond computed period — actually blocked for
901    // tokio's real timer resolution (>= ~1 ms), capping throughput at
902    // roughly 1000 pkt/s regardless of the configured MAX_BW, and blocked
903    // the same `run()` iteration's RX processing while it slept.
904    next_data_send_at: Option<Instant>,
905
906    // Delivered payloads flowing back to the application handle. Bounded
907    // (item 4): see [`DELIVER_CHANNEL_CAPACITY`].
908    deliver: mpsc::Sender<Bytes>,
909
910    peer_shutdown: bool,
911
912    /// Longest silence from the peer before the connection ends
913    /// ([`IoConfig::read_idle`]).
914    read_idle: Duration,
915    /// Longest a single `send_to` may take ([`IoConfig::write`]).
916    write_timeout: Duration,
917
918    /// Test hook: counts `tick_engines` calls, so a test can prove the run
919    /// loop wakes at deadlines rather than on a fixed tick.
920    #[cfg(test)]
921    tick_counter: Option<Arc<AtomicU64>>,
922}
923
924impl Driver {
925    fn new(p: ConnParams, deliver: mpsc::Sender<Bytes>) -> Self {
926        let now = Instant::now();
927        Driver {
928            udp: p.udp,
929            peer_addr: p.peer_addr,
930            peer_socket_id: p.peer_socket_id,
931            stats: p.stats,
932            rx: p.rx,
933            _route_cleanup: p.route_cleanup,
934            _forwarder_guard: p.forwarder_guard,
935            last_rx_at: now,
936            last_tx_at: now,
937            // `dest_socket_id` on every outgoing DATA/ACKACK/NAK/ACK packet
938            // must be the peer's negotiated SRT Socket ID, not its ISN — the
939            // two are unrelated values (§3).
940            sender: ArqSender::new(p.peer_socket_id),
941            receiver: ArqReceiver::new(p.peer_socket_id, p.peer_initial_seq, p.max_flow_window)
942                .with_mtu(p.mtu),
943            tsbpd: TsbpdScheduler::new(
944                p.peer_initial_seq,
945                p.tsbpd_time_base,
946                p.tsbpd_delay_ms,
947                DEFAULT_DRIFT_US,
948                p.tlpkt_drop,
949                None,
950            ),
951            livecc: LiveCC::new(DEFAULT_MAX_BW),
952            next_message_number: 1,
953            next_send_seq: p.our_initial_seq,
954            epoch: p.epoch,
955            staged: std::collections::BTreeMap::new(),
956            max_flow_window: p.max_flow_window,
957            outbound_data: VecDeque::new(),
958            outbound_control: VecDeque::new(),
959            next_data_send_at: None,
960            deliver,
961            peer_shutdown: false,
962            read_idle: p.read_idle,
963            write_timeout: p.write,
964            #[cfg(test)]
965            tick_counter: None,
966        }
967    }
968
969    /// The next instant at which this connection must act without any inbound
970    /// event: the next Full ACK / NAK, the next TSBPD release (or too-late
971    /// skip), the Keep-Alive when idle, the peer-idle expiry and the next
972    /// pacing slot. Never in the past (floored at [`MIN_WAKE`]).
973    fn poll_timeout(&self) -> Option<Instant> {
974        let now = self.elapsed();
975        // Full ACK / NAK.
976        let mut at = self.epoch + self.receiver.next_timeout();
977        // TSBPD release / TLPKTDROP skip.
978        if let Some(t) = self.tsbpd.next_release_after(now) {
979            at = at.min(self.epoch + t);
980        }
981        // Keep-Alive (only judged when nothing is queued).
982        if self.outbound_control.is_empty() && self.outbound_data.is_empty() {
983            at = at.min(self.last_tx_at + KEEPALIVE_PERIOD);
984        }
985        // Peer idle.
986        at = at.min(self.last_rx_at + self.read_idle);
987        // Pacing slot.
988        if let Some(wait) = self.next_paced_send_wait() {
989            at = at.min(Instant::now() + wait);
990        }
991        Some(at.max(Instant::now() + MIN_WAKE))
992    }
993
994    /// The select loop: socket RX, application-send, and a periodic engine
995    /// tick — the tick arm is what keeps retransmit/ACK/NAK progressing when
996    /// neither peer is actively sending application data.
997    async fn run(mut self, mut app_out: mpsc::Receiver<Bytes>) {
998        let mut app_open = true;
999
1000        // Set when the application handle is gone (its `to_driver` sender was
1001        // dropped): the loop makes one final flush pass and then exits, so a
1002        // dropped [`SrtSocket`] does not leave a driver task parked forever on
1003        // the socket/timer arms — which would keep a current-thread runtime
1004        // from shutting down. (`SrtSocket::Drop` also aborts the task; this is
1005        // the cooperative path that does not rely on abort-during-shutdown.)
1006        let mut shutting_down = false;
1007
1008        loop {
1009            // The next instant this connection must act on its own (ACK/NAK,
1010            // TSBPD release, keep-alive, peer idle, pacing slot): the loop
1011            // sleeps until then or until an event, never on a fixed tick.
1012            let wake_at = self
1013                .poll_timeout()
1014                .unwrap_or_else(|| Instant::now() + KEEPALIVE_PERIOD);
1015            // Stop taking application payloads while a full flow window of
1016            // packets is still unacknowledged: the hand-off channel then
1017            // fills and `SrtSocket::send` waits, instead of the send buffer
1018            // growing without bound behind a stalled or dead peer.
1019            let accept_app_data = app_open && self.send_window_open();
1020
1021            tokio::select! {
1022                // Application handed us a payload to send.
1023                maybe = app_out.recv(), if accept_app_data => {
1024                    match maybe {
1025                        Some(payload) => self.send_one(&payload),
1026                        None => {
1027                            // Handle dropped its sender — no more app data
1028                            // will ever arrive. Stop polling this (now
1029                            // permanently `Ready(None)`) arm and tear down.
1030                            app_open = false;
1031                            shutting_down = true;
1032                        }
1033                    }
1034                }
1035                // A datagram for this connection, already demultiplexed by
1036                // the upstream forwarder/router (issue #1029) — never a
1037                // shared `udp.recv_from` racing another task for the same
1038                // socket.
1039                maybe = self.rx.recv() => {
1040                    match maybe {
1041                        Some(bytes) => {
1042                            // A malformed datagram is ignored, not fatal.
1043                            let _ = self.ingress(bytes);
1044                        }
1045                        None => break, // upstream demux/forwarder is gone.
1046                    }
1047                }
1048                // Deadline: retransmit, ACK, NAK, TSBPD release, keep-alive
1049                // and the pacing slot are all folded into `poll_timeout`.
1050                _ = tokio::time::sleep_until(wake_at) => {}
1051            }
1052
1053            // Timer-driven engine work runs after EVERY wake-up: it is a pure
1054            // function of `now`, so an inbound packet also gets its
1055            // ACK/NAK/TSBPD release without waiting for a tick.
1056            self.tick_engines();
1057
1058            if self.flush_outbound().await.is_err() {
1059                break;
1060            }
1061            if self.peer_idle(Instant::now()) {
1062                // libsrt's default `SRTO_PEERIDLETIMEO`: no packet at all
1063                // (not just DATA) from the peer for this long means the
1064                // connection is broken, not merely quiet — a live SRT peer
1065                // always sends at least periodic Keep-Alives.
1066                break;
1067            }
1068            if self.peer_shutdown || shutting_down {
1069                break;
1070            }
1071        }
1072        // A cooperative exit because *we* are leaving (not the peer's
1073        // SHUTDOWN, nor an idle peer, nor a socket error) tells the peer
1074        // (§3.2.7); `SrtSocket::drop` does the same for the abort path.
1075        if shutting_down
1076            && !self.peer_shutdown
1077            && let Some(buf) = shutdown_datagram(self.peer_socket_id, self.elapsed_us())
1078        {
1079            let _ = send_bounded(&self.udp, &buf, self.peer_addr, self.write_timeout, "send").await;
1080        }
1081        // The route-table and forwarder-task cleanup this used to do inline
1082        // now happens in `_route_cleanup`/`_forwarder_guard`'s `Drop` impls,
1083        // which run here too (falling off the end of this function drops
1084        // `self`) as well as on `SrtSocket::Drop`'s task abort — the case
1085        // this inline code used to miss entirely.
1086        //
1087        // Dropping `self.deliver` here closes the channel, so the handle's
1088        // `recv` returns `None` (clean shutdown / task ended).
1089    }
1090
1091    /// No packet at all has arrived from the peer for [`IoConfig::read_idle`].
1092    fn peer_idle(&self, now: Instant) -> bool {
1093        now.saturating_duration_since(self.last_rx_at) >= self.read_idle
1094    }
1095
1096    /// Room in the send window: fewer than a full flow window of packets are
1097    /// buffered unacknowledged (§3.2.1 Maximum Flow Window Size).
1098    fn send_window_open(&self) -> bool {
1099        let window = usize::try_from(self.max_flow_window)
1100            .unwrap_or(usize::MAX)
1101            .max(1);
1102        self.sender.buffered_count() < window
1103    }
1104
1105    fn send_one(&mut self, payload: &[u8]) {
1106        let now = self.elapsed();
1107        self.livecc
1108            .on_data_packet(u64::try_from(payload.len()).unwrap_or(u64::MAX));
1109        // The counters are kept within their wire widths below, so this cannot
1110        // be refused; if it ever were, the payload is dropped, not the task.
1111        let Ok(bytes) =
1112            self.sender
1113                .on_data(self.next_send_seq, self.next_message_number, payload, now)
1114        else {
1115            return;
1116        };
1117        // Wrap at the wire field's own bit width (31 bits for the sequence
1118        // number, 26 for the message number — `draft-sharabayko-srt-01`
1119        // §3.1), not at `u32::MAX`: a plain `wrapping_add(1)` let both
1120        // counters walk past their field width (~20 h of continuous sending
1121        // for the sequence number, or immediately with a high initial value;
1122        // ~67 million messages for the message number), after which every
1123        // subsequent `DataPacket::serialize_into` returned
1124        // `Error::FieldTooWide` and panicked the `.expect("buffer sized from
1125        // serialized_len")` call sites in `arq::sender` that assumed only a
1126        // too-small buffer could fail (issue #1062).
1127        self.next_send_seq = seq_next(self.next_send_seq);
1128        self.next_message_number = next_message_number(self.next_message_number);
1129        self.outbound_data.push_back(bytes);
1130    }
1131
1132    /// Process one datagram from the peer. Takes the datagram by value so a
1133    /// DATA packet's own allocation can be staged without a copy.
1134    fn ingress(&mut self, datagram: Bytes) -> Result<()> {
1135        // Any datagram from the peer — even one that fails to parse below —
1136        // is evidence the peer is still there, resetting the idle timeout.
1137        self.last_rx_at = Instant::now();
1138        let now = self.elapsed();
1139        match SrtPacket::parse(&datagram)? {
1140            SrtPacket::Data(d) => {
1141                let (seq_number, timestamp, key_flag) = (d.seq_number, d.timestamp, d.key_flag);
1142                self.ingress_data(datagram, seq_number, timestamp, key_flag, now);
1143            }
1144            SrtPacket::Control(c) => self.ingress_control(&c, now),
1145        }
1146        Ok(())
1147    }
1148
1149    fn ingress_data(
1150        &mut self,
1151        datagram: Bytes,
1152        seq_number: u32,
1153        timestamp: u32,
1154        key_flag: EncryptionKeyField,
1155        now: Duration,
1156    ) {
1157        // The adapter never decrypts, so a ciphertext packet must not reach
1158        // the application (§3.1 `KK`, §6): drop it before ARQ or TSBPD see it
1159        // (acknowledging data we can never deliver would be worse than
1160        // dropping it).
1161        if key_flag != EncryptionKeyField::NotEncrypted {
1162            return;
1163        }
1164
1165        // The ARQ receiver drives *reliability* only: loss detection and the
1166        // resulting NAK (rules 4, 14) plus the ACK point. Application
1167        // delivery is the TSBPD scheduler's job — it is the single in-order
1168        // delivery authority (see below), so its `outcome.delivered` is
1169        // intentionally NOT used to deliver here. Running both cursors over
1170        // one `staged` map races them and reorders retransmitted packets.
1171        //
1172        // Flow-window overflow guard (§3.2.1): a packet further ahead of the
1173        // ack point than the negotiated maximum flow window can never be
1174        // released in this connection's lifetime — staging it would let an
1175        // unrecoverable gap grow memory without bound, so the receiver
1176        // refuses it and nothing downstream sees it.
1177        //
1178        // A packet that is not ahead of the delivery cursor (a duplicate, a
1179        // retransmission of what was delivered or given up on, or an
1180        // attacker-chosen stale number with a future timestamp) has nothing
1181        // left to do: TSBPD would ignore it and nothing would ever remove it
1182        // from `staged`, so it is never staged at all.
1183        if seq_lt(seq_number, self.tsbpd.next_release()) {
1184            self.stats.late_dropped.fetch_add(1, Ordering::Relaxed);
1185            return;
1186        }
1187        let outcome = self.receiver.feed_data(seq_number, now);
1188        if outcome.out_of_window {
1189            return;
1190        }
1191        if let Some(nak_bytes) = outcome.nak {
1192            self.outbound_control.push_back(nak_bytes);
1193        }
1194
1195        self.staged.entry(seq_number).or_insert(datagram);
1196
1197        // TSBPD is the sole delivery cursor: it releases packets in strict
1198        // sequence order, waiting for a NAK-recovered gap to be filled —
1199        // until the next available packet reaches its play time, at which
1200        // point live mode skips the unrecoverable gap and delivers that
1201        // packet (only if TLPKTDROP was negotiated, §3.2.1.1.1; otherwise it waits for the
1202        // retransmission, and the ARQ ack point never moves past the gap).
1203        let tsbpd_out = self.tsbpd.feed_data(seq_number, timestamp, now);
1204        self.release(&tsbpd_out);
1205    }
1206
1207    fn ingress_control(&mut self, c: &ControlPacket<'_>, now: Duration) {
1208        match c {
1209            ControlPacket::Ack(ack) => {
1210                if let Some(ackack_bytes) = self.sender.on_ack(ack, now) {
1211                    self.outbound_control.push_back(ackack_bytes);
1212                }
1213            }
1214            ControlPacket::Nak(nak) => {
1215                // Record the reported loss; the next `tick_engines`
1216                // (or this cycle's, if a tick fired) drains the
1217                // retransmit queue — retransmits are queued ahead of any
1218                // new first-time data (rules 5, 15, 16).
1219                self.sender.on_nak(nak);
1220            }
1221            ControlPacket::AckAck(ackack) => {
1222                self.receiver.on_ackack(ackack, now);
1223            }
1224            ControlPacket::DropReq(d) => {
1225                self.handle_dropreq(d, now);
1226            }
1227            // A Keep-Alive only tells us the peer is alive (`last_rx_at` is
1228            // already refreshed): it is not answered. Echoing it made two of
1229            // these adapters bounce a Keep-Alive back and forth forever now
1230            // that an idle connection sends its own every second.
1231            ControlPacket::KeepAlive(_) => {}
1232            ControlPacket::Shutdown(_) => {
1233                self.peer_shutdown = true;
1234            }
1235            _ => {}
1236        }
1237    }
1238
1239    /// Handle a DROPREQ (§3.2.9): the peer announces it will never deliver
1240    /// sequence numbers `first..=last`. Tell the ARQ receiver to stop NAKing
1241    /// them and advance its ack point, tell the TSBPD scheduler to skip them
1242    /// for delivery purposes, discard anything already staged inside the
1243    /// range (the sender has given up on the message they belonged to), then
1244    /// drive one release pass so whatever the gap was blocking becomes
1245    /// deliverable immediately.
1246    fn handle_dropreq(&mut self, d: &DropReqPacket, now: Duration) {
1247        let first = d.first_seq & SEQ_NUMBER_MASK;
1248        let last = d.last_seq & SEQ_NUMBER_MASK;
1249        if seq_diff(last, first) < 0 {
1250            // `last` precedes `first` — malformed range; nothing sane to skip.
1251            return;
1252        }
1253        self.receiver.skip_range(first, last);
1254        self.tsbpd.skip_range(first, last);
1255        self.staged
1256            .retain(|&s, _| !seq_in_closed_range(s, first, last));
1257
1258        let tsbpd_out = self.tsbpd.tick(now);
1259        self.release(&tsbpd_out);
1260    }
1261
1262    /// Apply one TSBPD outcome to `staged` and the application channel:
1263    /// deliver the released payloads, and purge anything the scheduler dropped
1264    /// as too-late/skipped so a lost packet cannot leak its staged bytes.
1265    ///
1266    /// What the scheduler gave up on (§4.6) is also skipped in the ARQ
1267    /// receiver: its ack point then moves past the dropped packets — the
1268    /// "fake ACK" of Too-Late Packet Drop — so it stops NAKing packets that
1269    /// can no longer be delivered, the ACKs it sends let the peer free them,
1270    /// and the flow window it measures new arrivals against advances with the
1271    /// delivery cursor instead of stalling at the lost packet forever.
1272    fn release(&mut self, outcome: &TickOutcome) {
1273        for &seq in &outcome.delivered {
1274            if let Some(datagram) = self.staged.remove(&seq) {
1275                // The staged datagram is a DATA packet (it parsed as one):
1276                // hand over the payload as a view into the same allocation.
1277                let payload = datagram.slice(SRT_HEADER_LEN.min(datagram.len())..);
1278                if self.deliver.try_send(payload).is_err() {
1279                    // Full (app isn't calling `recv` fast enough) or the
1280                    // handle is gone; either way, drop rather than buffer
1281                    // without bound (item 4) and count it.
1282                    self.stats.deliver_dropped.fetch_add(1, Ordering::Relaxed);
1283                }
1284            }
1285        }
1286        for &seq in &outcome.dropped {
1287            self.staged.remove(&seq);
1288        }
1289        for (first, last) in contiguous_runs(&outcome.dropped) {
1290            self.receiver.skip_range(first, last);
1291        }
1292    }
1293
1294    fn tick_engines(&mut self) {
1295        #[cfg(test)]
1296        if let Some(counter) = &self.tick_counter {
1297            counter.fetch_add(1, Ordering::Relaxed);
1298        }
1299        let now = self.elapsed();
1300
1301        // Retransmitted DATA packets first (rules 5, 15, 16, 18): they are
1302        // drained from the NAK-populated loss list and queued *before* any
1303        // new first-time data appended later this cycle, reproducing the
1304        // sans-IO engine's "loss list before first transmission" priority
1305        // (see `arq::sender`'s module doc). Feed LiveCC the same as a
1306        // first-time send (`specs/rules/srt-livecc.md` §5.1.2, L3216-3217:
1307        // "original or retransmitted") and tag them `is_data` so pacing
1308        // applies. The payload length is the datagram less its fixed header —
1309        // no need to re-parse the packet just to learn it.
1310        for bytes in self.sender.tick(now) {
1311            self.livecc.on_data_packet(
1312                u64::try_from(bytes.len().saturating_sub(SRT_HEADER_LEN)).unwrap_or(u64::MAX),
1313            );
1314            self.outbound_data.push_back(bytes);
1315        }
1316
1317        // Keep-Alive (§3.2.3): a connection that has sent nothing for a
1318        // second says so, or the peer's own idle timeout ends it. Judged
1319        // before this tick's ACK/NAK are queued: it asks whether anything has
1320        // gone out for a second, not whether something is about to. (The
1321        // receiver's 10 ms Full ACK normally keeps `last_tx_at` fresh, so
1322        // this is the backstop for when it does not.)
1323        if self.outbound_control.is_empty()
1324            && self.outbound_data.is_empty()
1325            && Instant::now().saturating_duration_since(self.last_tx_at) >= KEEPALIVE_PERIOD
1326        {
1327            self.queue_keepalive();
1328        }
1329
1330        // Periodic ACK/NAK (rules 11, 12, 21, 22): control feedback, never
1331        // paced.
1332        for bytes in self.receiver.tick(now) {
1333            self.outbound_control.push_back(bytes);
1334        }
1335
1336        let tsbpd_out = self.tsbpd.tick(now);
1337        self.release(&tsbpd_out);
1338    }
1339
1340    fn queue_keepalive(&mut self) {
1341        let pkt = ControlPacket::KeepAlive(KeepAlivePacket {
1342            timestamp: self.elapsed_us(),
1343            dest_socket_id: self.peer_socket_id,
1344            libsrt_pad: true,
1345        });
1346        let mut buf = vec![0u8; pkt.serialized_len()];
1347        if pkt.serialize_into(&mut buf).is_ok() {
1348            self.outbound_control.push_back(buf);
1349        }
1350    }
1351
1352    fn elapsed(&self) -> Duration {
1353        Instant::now().saturating_duration_since(self.epoch)
1354    }
1355
1356    /// The Keep-Alive/ACKACK/etc. control-packet wire `Timestamp` — wraps
1357    /// modulo `2^32` past ~71.58 minutes, matching `arq::duration_to_wire_us`
1358    /// (issue #1063; a clamp here made every control packet after that point
1359    /// carry the exact same wire timestamp forever).
1360    fn elapsed_us(&self) -> u32 {
1361        crate::arq::duration_to_wire_us(self.elapsed())
1362    }
1363
1364    /// How long until the DATA packet at the front of the outbound data
1365    /// queue (if any) is next allowed to go out — `None` if there is nothing
1366    /// pacing-blocked right now (the data queue is empty, or its front
1367    /// packet's slot has already arrived). Drives the `run()` loop's pacing
1368    /// `select!` arm (issue #1061): by construction, `flush_outbound` always
1369    /// drains everything currently due before returning, so a `Some` here is
1370    /// always a genuine future deadline, never one already past. Never
1371    /// consults `outbound_control` — control is never pacing-blocked (item 6:
1372    /// two separate queues, not one tagged queue, so control can never queue
1373    /// behind a not-yet-due DATA packet either).
1374    fn next_paced_send_wait(&self) -> Option<Duration> {
1375        if self.outbound_data.is_empty() {
1376            return None;
1377        }
1378        let deadline = self.next_data_send_at?;
1379        Some(deadline.saturating_duration_since(Instant::now()))
1380    }
1381
1382    /// Send every outbound item that is due right now, in order, without
1383    /// blocking on the pacing delay itself (issue #1061).
1384    ///
1385    /// `specs/rules/srt-livecc.md` §5.1.2: `PKT_SND_PERIOD` paces DATA
1386    /// packets only — control feedback (ACK/NAK/ACKACK/Keep-Alive) must go
1387    /// out immediately, or loss recovery (which rides on that same control
1388    /// traffic) would be throttled right along with the data it is meant to
1389    /// unblock.
1390    ///
1391    /// DATA packets are scheduled against `next_data_send_at`, a token-bucket
1392    /// style deadline rather than a per-packet `tokio::time::sleep`: a real
1393    /// sleep, even for a sub-millisecond computed period, actually blocks for
1394    /// tokio's real timer resolution (documented as coarse — at least
1395    /// roughly a millisecond on this host) — capping throughput at roughly
1396    /// 1000 pkt/s regardless of the configured `MAX_BW`, and (since the old
1397    /// code awaited it serially inside this function, called from every
1398    /// `run()` iteration) stalling RX/app-send processing for that same
1399    /// window. The schedule advances from whichever is later of the
1400    /// previous deadline or now, so a connection that was genuinely idle
1401    /// (or RX/tick-bound, not pacing-bound) for a while does not have to
1402    /// "pay back" that gap — it sends immediately and only then resumes
1403    /// pacing at the configured rate — while a sustained flood is still
1404    /// throttled to it.
1405    async fn flush_outbound(&mut self) -> Result<()> {
1406        // Control first, and all of it, unconditionally — never paced, and
1407        // (being its own queue) never stuck behind a not-yet-due DATA packet
1408        // either (item 6).
1409        while let Some(bytes) = self.outbound_control.pop_front() {
1410            send_bounded(
1411                &self.udp,
1412                &bytes,
1413                self.peer_addr,
1414                self.write_timeout,
1415                "send",
1416            )
1417            .await?;
1418            self.last_tx_at = Instant::now();
1419        }
1420        let mut sent = 0;
1421        while self.outbound_data.front().is_some() && sent < PACING_BURST_CAP {
1422            let now = Instant::now();
1423            if let Some(deadline) = self.next_data_send_at
1424                && now < deadline
1425            {
1426                // Not yet due — leave it (and everything behind it, to
1427                // preserve send order) queued for a later pass.
1428                break;
1429            }
1430            let Some(bytes) = self.outbound_data.pop_front() else {
1431                break;
1432            };
1433            let period = self.livecc.on_ack_received();
1434            // Catch-up: a wake that arrives late (the timer has ~1 ms
1435            // granularity, `MIN_WAKE`) still owes the packets whose slots
1436            // passed meanwhile, so the schedule advances from the previous
1437            // slot even if it is already past — but never by more than
1438            // `PACING_BURST_CAP` periods of credit, so a stall cannot be
1439            // repaid as an unbounded burst.
1440            let floor = now
1441                .checked_sub(period * PACING_BURST_CAP as u32)
1442                .unwrap_or(now);
1443            let base = self.next_data_send_at.map_or(now, |t| t.max(floor));
1444            self.next_data_send_at = Some(base + period);
1445            sent += 1;
1446            send_bounded(
1447                &self.udp,
1448                &bytes,
1449                self.peer_addr,
1450                self.write_timeout,
1451                "send",
1452            )
1453            .await?;
1454            self.last_tx_at = Instant::now();
1455        }
1456        // An idle connection owes nothing: drop an expired slot so the next
1457        // backlog starts at "now" instead of replaying the idle gap as credit.
1458        if self.outbound_data.is_empty() {
1459            self.next_data_send_at = self.next_data_send_at.filter(|&t| t > Instant::now());
1460        }
1461        Ok(())
1462    }
1463}
1464
1465/// Split ascending, circularly ordered sequence numbers into inclusive
1466/// `(first, last)` runs of consecutive values.
1467fn contiguous_runs(seqs: &[u32]) -> Vec<(u32, u32)> {
1468    let mut runs: Vec<(u32, u32)> = Vec::new();
1469    for &s in seqs {
1470        match runs.last_mut() {
1471            Some((_, last)) if seq_next(*last) == s => *last = s,
1472            _ => runs.push((s, s)),
1473        }
1474    }
1475    runs
1476}
1477
1478/// Spawn the forwarder task for a connection with its own **dedicated,
1479/// unshared** socket (a [`SrtSocket::connect`]ed caller): reads that socket
1480/// directly (no demux table needed — nothing else ever reads it) and
1481/// forwards only datagrams from `peer`, matching the filtering
1482/// `Driver::run`'s old direct-`recv_from` arm used to do inline (issue
1483/// #1029; see the module doc on [`SrtListener`] for the shared-socket case,
1484/// which needs actual demultiplexing, not just this filter).
1485///
1486/// Returns the receiver the [`Driver`] reads plus the task's own
1487/// [`tokio::task::JoinHandle`] — the caller must abort it (via
1488/// [`TaskGuard`]) once the connection ends, or this loop keeps the socket's
1489/// local port bound forever (item 3): dropping the `Driver`'s `Arc<UdpSocket>`
1490/// reference alone does not stop this task, which holds its own clone and
1491/// stays parked in `recv_from` waiting for a datagram that may never come.
1492fn spawn_dedicated_socket_forwarder(
1493    udp: Arc<UdpSocket>,
1494    peer: std::net::SocketAddr,
1495    stats: Arc<Counters>,
1496    max_datagram: usize,
1497) -> (mpsc::Receiver<Bytes>, tokio::task::JoinHandle<()>) {
1498    let (tx, rx) = mpsc::channel(RX_CHANNEL_CAPACITY);
1499    let handle = tokio::spawn(async move {
1500        let mut scratch = vec![0u8; max_datagram + 1];
1501        loop {
1502            match recv_datagram(&udp, &mut scratch, max_datagram, &stats.rx_oversize).await {
1503                Ok(Some((bytes, src))) if src == peer => {
1504                    if tx.try_send(bytes).is_err() {
1505                        if tx.is_closed() {
1506                            break; // Driver is gone.
1507                        }
1508                        // Full — the driver isn't draining fast enough; drop
1509                        // this datagram rather than buffer without bound
1510                        // (item 4) and count it.
1511                        stats.rx_dropped.fetch_add(1, Ordering::Relaxed);
1512                    }
1513                }
1514                Ok(_) => {} // datagram from another peer, or oversize (counted); ignore.
1515                Err(_) => break,
1516            }
1517        }
1518    });
1519    (rx, handle)
1520}
1521
1522// ===========================================================================
1523// SrtListener
1524// ===========================================================================
1525
1526/// An SRT listener that accepts incoming Caller connections.
1527///
1528/// # One socket, many connections (issue #1029)
1529///
1530/// Every connection this listener accepts shares its single bound socket —
1531/// unlike [`SrtSocket::connect`], which binds a fresh, unshared socket per
1532/// connection. `recv_from` on a shared socket delivers each datagram to
1533/// whichever waiting caller happens to be polled next, *not* whichever
1534/// caller the datagram is actually addressed to: if both this listener's own
1535/// `accept` loop and one or more accepted connections' driver tasks each
1536/// called `recv_from` on the same socket, a datagram belonging to one
1537/// connection could be handed to a completely different one (which would
1538/// then just discard it as foreign), silently losing it for its rightful
1539/// recipient. So exactly one task ever calls `recv_from` on `udp`: the
1540/// routing pump spawned once in [`SrtListener::bind`]. It demultiplexes the
1541/// way libsrt does (item 2, draft §4.3.1): a Destination Socket ID of `0`
1542/// (every handshake packet this crate's Caller ever sends, per the
1543/// `dest_socket_id` fix in `caller.rs`) always means "not yet an established
1544/// connection" and goes to `unrouted_rx` (`accept`'s own input); any other ID
1545/// must match an entry in `routes` *and* that entry's accepted source
1546/// address, or the datagram is dropped — a stray packet naming an ID that was
1547/// never accepted (or accepted from a different address) has nowhere
1548/// legitimate to go.
1549///
1550/// A repeated CONCLUSION from an already-accepted Caller (its copy of our
1551/// response was lost) carries Destination Socket ID `0` too, so it reaches
1552/// the listener's background task, which answers it again — no one has to be
1553/// polling [`accept`](Self::accept) for that.
1554///
1555/// # Lifetime (defect 3)
1556///
1557/// Handshakes advance in a tracked background task, not inside
1558/// [`accept`](Self::accept); the routing pump is a second tracked task. Both end
1559/// on a [`CancellationToken`], fired when the last of {this handle, every
1560/// accepted [`SrtSocket`]} is dropped — so an idle listener releases its UDP
1561/// port the moment the handle is dropped, while connections it already
1562/// accepted keep being routed until they too are gone.
1563pub struct SrtListener {
1564    /// Held only so its `Drop` (cancel the tasks) runs with the handle.
1565    _life: Arc<ListenerLife>,
1566    local: std::net::SocketAddr,
1567    accepted: mpsc::Receiver<Result<SrtSocket>>,
1568    /// Shared demux table (see [`RouteTable`]); the core and the routing pump
1569    /// hold the same `Arc`. Read by tests only.
1570    #[cfg_attr(not(test), allow(dead_code))]
1571    routes: RouteTable,
1572    unrouted_dropped: Arc<AtomicU64>,
1573    overflow_dropped: Arc<AtomicU64>,
1574    send_errors: Arc<AtomicU64>,
1575}
1576
1577/// Capacity of the pending-`accept` queue: handshakes that finished while
1578/// `accept` was not being polled.
1579const ACCEPT_BACKLOG: usize = 64;
1580
1581/// Owns the listener's background tasks. Dropped when the last of the
1582/// [`SrtListener`] handle and every accepted [`SrtSocket`] is gone; that
1583/// cancels the tasks, which closes the UDP socket.
1584#[derive(Debug)]
1585struct ListenerLife {
1586    cancel: CancellationToken,
1587    tasks: TaskTracker,
1588}
1589
1590impl Drop for ListenerLife {
1591    fn drop(&mut self) {
1592        self.cancel.cancel();
1593        self.tasks.close();
1594    }
1595}
1596
1597/// The listener's handshake state, driven by one tracked background task
1598/// ([`ListenerCore::run`]).
1599struct ListenerCore {
1600    udp: Arc<UdpSocket>,
1601    config: HandshakeConfig,
1602    io: IoConfig,
1603    /// Per-listener 128-bit key for [`derive_cookie`] (`draft-sharabayko-srt-01`
1604    /// §4.3.1.1: "a cookie that is crafted based on host, port and current
1605    /// time"), drawn from the OS at [`SrtListener::bind`] and rotated every
1606    /// [`COOKIE_KEY_ROTATION`], so a cookie is neither shared across listeners
1607    /// nor valid for the life of the process.
1608    cookie_keys: CookieKeys,
1609    pending: std::collections::HashMap<std::net::SocketAddr, PendingListener>,
1610    outbound_queue: std::collections::HashMap<std::net::SocketAddr, VecDeque<Vec<u8>>>,
1611    /// CONCLUSION responses of recently accepted connections, by source
1612    /// address, so a repeated CONCLUSION can be answered again (see
1613    /// [`RecentAccept`]).
1614    recent_accepts: std::collections::HashMap<std::net::SocketAddr, RecentAccept>,
1615    /// Shared demux table the routing pump task consults for every inbound
1616    /// datagram; `drain_completed` registers a new entry for each freshly
1617    /// accepted connection.
1618    routes: RouteTable,
1619    /// Datagrams the routing pump could not match to any entry in `routes`
1620    /// — candidate new-connection (handshake) traffic. Bounded (item 4): see
1621    /// [`UNROUTED_CHANNEL_CAPACITY`].
1622    unrouted_rx: mpsc::Receiver<(std::net::SocketAddr, Bytes)>,
1623    /// Weak, so the core never keeps the listener alive: a connection is only
1624    /// handed over while a handle (or another connection) still holds the
1625    /// `Arc`.
1626    life: std::sync::Weak<ListenerLife>,
1627    /// Finished handshakes, for [`SrtListener::accept`].
1628    accepted_tx: mpsc::Sender<Result<SrtSocket>>,
1629    /// Connections dropped because `accepted_tx` was full.
1630    overflow_dropped: Arc<AtomicU64>,
1631    /// Send failures met while answering peers (counted, never queued: they
1632    /// must not compete with finished connections for `accepted_tx` slots).
1633    send_errors: Arc<AtomicU64>,
1634    /// `false` once the handle is gone: no new handshakes are served, but the
1635    /// task keeps draining `unrouted_rx` so the routing pump (which accepted
1636    /// connections still depend on) is never starved into exiting.
1637    accepting: bool,
1638    /// When `tick_pending` last ran: the basis of [`ListenerCore::poll_timeout`].
1639    last_pending_tick: Instant,
1640}
1641
1642/// The listener's SYN-cookie key and when it was drawn. Each pending
1643/// handshake keeps the cookie it was *issued* (the engine compares the
1644/// CONCLUSION's cookie with it), so a handshake that began under the previous
1645/// key still completes after a rotation — the "previous key stays acceptable"
1646/// window is exactly one handshake's lifetime; only cookies issued from then
1647/// on use the new key.
1648struct CookieKeys {
1649    current: u128,
1650    drawn_at: Instant,
1651}
1652
1653impl CookieKeys {
1654    fn new(now: Instant) -> Result<Self> {
1655        Ok(CookieKeys {
1656            current: random_u128()?,
1657            drawn_at: now,
1658        })
1659    }
1660
1661    fn current(&self) -> u128 {
1662        self.current
1663    }
1664
1665    /// Replace the key once it is [`COOKIE_KEY_ROTATION`] old. Returns whether
1666    /// it did. A failing OS random source keeps the old key (and is retried on
1667    /// the next call) rather than ending the listener.
1668    fn rotate_if_due(&mut self, now: Instant) -> bool {
1669        if now.saturating_duration_since(self.drawn_at) < COOKIE_KEY_ROTATION {
1670            return false;
1671        }
1672        match random_u128() {
1673            Ok(key) => {
1674                self.current = key;
1675                self.drawn_at = now;
1676                true
1677            }
1678            Err(_) => false,
1679        }
1680    }
1681}
1682
1683impl core::fmt::Debug for CookieKeys {
1684    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1685        f.debug_struct("CookieKeys")
1686            .field("current", &format_args!("<redacted>"))
1687            .field("drawn_at", &self.drawn_at)
1688            .finish()
1689    }
1690}
1691
1692impl core::fmt::Debug for ListenerCore {
1693    // Manual: the cookie key must never reach a log via `{:?}` (#1142).
1694    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1695        f.debug_struct("ListenerCore")
1696            .field("local_addr", &self.udp.local_addr().ok())
1697            .field("cookie_keys", &self.cookie_keys)
1698            .field("pending", &self.pending.len())
1699            .field("recent_accepts", &self.recent_accepts.len())
1700            .finish_non_exhaustive()
1701    }
1702}
1703
1704impl core::fmt::Debug for SrtListener {
1705    // Manual: only the address — the cookie key lives in `ListenerCore`,
1706    // which is never printed from here (#1142).
1707    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1708        f.debug_struct("SrtListener")
1709            .field("local_addr", &self.local)
1710            .finish_non_exhaustive()
1711    }
1712}
1713
1714#[derive(Debug)]
1715struct PendingListener {
1716    handshake: ListenerHandshake,
1717    params: Option<HandshakeOutput>,
1718    /// The peer's ISN, extracted from the INDUCTION handshake packet.
1719    peer_initial_seq: u32,
1720    /// The `Timestamp` of the peer's CONCLUSION, which seeds the TSBPD time
1721    /// base (§4.5.1.1: `TsbpdTimeBase = T_NOW - HSREQ_TIMESTAMP`).
1722    peer_timestamp_us: u32,
1723    /// When that CONCLUSION arrived: `T_NOW` of the same formula, hence the
1724    /// connection epoch (not the later moment `accept` happens to hand the
1725    /// connection over).
1726    concluded_at: Option<Instant>,
1727    /// The last handshake datagram this entry produced — on completion, the
1728    /// CONCLUSION response a lost-response retransmit must be answered with.
1729    last_response: Option<Vec<u8>>,
1730    /// This listener's own ISN for this connection, generated once when the
1731    /// entry was created and echoed back here (rather than re-read from
1732    /// `self.config` at completion) so it is guaranteed to be the exact
1733    /// value the [`ListenerHandshake`] was constructed with — see
1734    /// [`SrtListener::handle_datagram`].
1735    our_initial_seq: u32,
1736}
1737
1738/// The CONCLUSION response of an accepted connection, kept for
1739/// [`RECENT_ACCEPT_TTL`] so that when the Caller repeats its CONCLUSION (our
1740/// response was lost, so it never saw the handshake finish) the identical
1741/// response is sent again — libsrt re-answers a repeated CONCLUSION the same
1742/// way. Without it the repeat reaches a listener that has already forgotten
1743/// the handshake, nothing is sent, and the Caller times out against a
1744/// connection the application is already using.
1745#[derive(Debug)]
1746struct RecentAccept {
1747    /// The Caller's SRT Socket ID — a repeat must carry the same one.
1748    peer_socket_id: u32,
1749    response: Vec<u8>,
1750    accepted_at: Instant,
1751}
1752
1753impl SrtListener {
1754    /// Bind an SRT listener on `addr`.
1755    ///
1756    /// # Encryption
1757    /// A [`HandshakeConfig`] with `crypto` set is refused with
1758    /// [`Error::EncryptionUnsupported`] before any network I/O, and a peer
1759    /// whose CONCLUSION requests encryption (a Key Material extension or a
1760    /// non-zero `Encryption Field`) is rejected — this adapter's data path
1761    /// does not encrypt, so an encrypted connection must never be accepted.
1762    pub async fn bind<A: tokio::net::ToSocketAddrs>(
1763        addr: A,
1764        config: HandshakeConfig,
1765    ) -> Result<Self> {
1766        Self::bind_with(addr, config, IoConfig::default()).await
1767    }
1768
1769    /// Like [`Self::bind`], with explicit timeouts and datagram size.
1770    pub async fn bind_with<A: tokio::net::ToSocketAddrs>(
1771        addr: A,
1772        config: HandshakeConfig,
1773        io: IoConfig,
1774    ) -> Result<Self> {
1775        refuse_crypto(&config)?;
1776        let socket = Arc::new(UdpSocket::bind(addr).await.map_err(|e| io_err("bind", e))?);
1777        let local = socket.local_addr().map_err(|e| io_err("local_addr", e))?;
1778        let routes: RouteTable = Arc::new(Mutex::new(std::collections::HashMap::new()));
1779        let (unrouted_tx, unrouted_rx) = mpsc::channel(UNROUTED_CHANNEL_CAPACITY);
1780        let (accepted_tx, accepted) = mpsc::channel(ACCEPT_BACKLOG);
1781        let unrouted_dropped = Arc::new(AtomicU64::new(0));
1782        let overflow_dropped = Arc::new(AtomicU64::new(0));
1783        let send_errors = Arc::new(AtomicU64::new(0));
1784        let life = Arc::new(ListenerLife {
1785            cancel: CancellationToken::new(),
1786            tasks: TaskTracker::new(),
1787        });
1788
1789        let core = ListenerCore {
1790            udp: Arc::clone(&socket),
1791            config,
1792            io,
1793            cookie_keys: CookieKeys::new(Instant::now())?,
1794            pending: std::collections::HashMap::new(),
1795            outbound_queue: std::collections::HashMap::new(),
1796            recent_accepts: std::collections::HashMap::new(),
1797            routes: Arc::clone(&routes),
1798            unrouted_rx,
1799            life: Arc::downgrade(&life),
1800            accepted_tx,
1801            overflow_dropped: Arc::clone(&overflow_dropped),
1802            send_errors: Arc::clone(&send_errors),
1803            accepting: true,
1804            last_pending_tick: Instant::now(),
1805        };
1806        life.tasks.spawn(routing_pump(
1807            Arc::clone(&socket),
1808            Arc::clone(&routes),
1809            unrouted_tx,
1810            Arc::clone(&unrouted_dropped),
1811            io.max_datagram.clamp(MIN_MAX_DATAGRAM, MAX_MAX_DATAGRAM),
1812            life.cancel.clone(),
1813        ));
1814        life.tasks.spawn(core.run(life.cancel.clone()));
1815        Ok(SrtListener {
1816            _life: life,
1817            local,
1818            accepted,
1819            routes,
1820            unrouted_dropped,
1821            overflow_dropped,
1822            send_errors,
1823        })
1824    }
1825
1826    /// Datagrams dropped because the candidate-new-connection queue was full
1827    /// (item 4) — a handshake flood outrunning the listener's handshake task —
1828    /// or because they exceeded [`IoConfig::max_datagram`].
1829    pub fn unrouted_dropped(&self) -> u64 {
1830        self.unrouted_dropped.load(Ordering::Relaxed)
1831    }
1832
1833    /// Connections that finished their handshake but were dropped because
1834    /// [`accept`](Self::accept) was not keeping up (the pending-accept queue
1835    /// holds 64).
1836    pub fn accept_overflow_dropped(&self) -> u64 {
1837        self.overflow_dropped.load(Ordering::Relaxed)
1838    }
1839
1840    /// Send failures the background task met while answering peers (for
1841    /// example an unreachable spoofed source). They are counted here and never
1842    /// surface from [`accept`](Self::accept), so a flood of them cannot displace
1843    /// finished connections or end an `accept` loop.
1844    pub fn send_errors(&self) -> u64 {
1845        self.send_errors.load(Ordering::Relaxed)
1846    }
1847
1848    /// The local socket address the listener is bound to.
1849    pub fn local_addr(&self) -> Result<std::net::SocketAddr> {
1850        Ok(self.local)
1851    }
1852
1853    /// Accept the next incoming SRT connection.
1854    ///
1855    /// Handshakes progress in the background whether or not this is being
1856    /// polled; this only waits for a finished one. Send errors met while
1857    /// answering peers are counted ([`send_errors`](Self::send_errors)), not
1858    /// returned.
1859    pub async fn accept(&mut self) -> Result<SrtSocket> {
1860        self.accepted.recv().await.unwrap_or(Err(Error::Io {
1861            kind: std::io::ErrorKind::BrokenPipe,
1862            context: "listener task ended",
1863        }))
1864    }
1865}
1866
1867impl ListenerCore {
1868    /// Next instant a pending handshake needs a tick; `None` when nothing is
1869    /// pending (an idle listener has no timer at all).
1870    fn poll_timeout(&self) -> Option<Instant> {
1871        (self.accepting && !self.pending.is_empty())
1872            .then(|| self.last_pending_tick + PENDING_TICK_INTERVAL)
1873    }
1874
1875    /// The handshake task: answer unrouted datagrams, tick pending handshakes
1876    /// on a deadline, hand finished connections to [`SrtListener::accept`].
1877    async fn run(mut self, cancel: CancellationToken) {
1878        loop {
1879            while self.accepting
1880                && let Some(conn) = self.drain_completed()
1881            {
1882                match self.accepted_tx.try_send(conn) {
1883                    Ok(()) => {}
1884                    Err(mpsc::error::TrySendError::Full(_dropped)) => {
1885                        // Dropping the SrtSocket sends the peer a SHUTDOWN; count it.
1886                        self.overflow_dropped.fetch_add(1, Ordering::Relaxed);
1887                    }
1888                    Err(mpsc::error::TrySendError::Closed(_)) => {
1889                        // The handle is gone but accepted connections may
1890                        // still be alive: stop serving new handshakes, keep
1891                        // draining so the routing pump keeps running.
1892                        self.accepting = false;
1893                        self.pending.clear();
1894                        self.outbound_queue.clear();
1895                    }
1896                }
1897            }
1898            let deadline = self.poll_timeout();
1899            tokio::select! {
1900                _ = cancel.cancelled() => return,
1901                r = self.unrouted_rx.recv() => match r {
1902                    Some((src, bytes)) => {
1903                        if !self.accepting {
1904                            continue;
1905                        }
1906                        // Cookie rotation no longer rides a tick: do it whenever a
1907                        // datagram arrives.
1908                        self.cookie_keys.rotate_if_due(Instant::now());
1909                        let _ = self.handle_datagram(src, &bytes);
1910                        // Raced against cancellation: a stuck send must not
1911                        // delay releasing the port by up to `io.write`.
1912                        tokio::select! {
1913                            _ = cancel.cancelled() => return,
1914                            r = self.flush_for_peer(src) => self.count_send_error(r),
1915                        }
1916                    }
1917                    None => return,
1918                },
1919                _ = async {
1920                    match deadline {
1921                        Some(d) => tokio::time::sleep_until(d).await,
1922                        None => std::future::pending::<()>().await,
1923                    }
1924                } => {
1925                    self.last_pending_tick = Instant::now();
1926                    self.tick_pending();
1927                    tokio::select! {
1928                        _ = cancel.cancelled() => return,
1929                        r = self.flush_all() => self.count_send_error(r),
1930                    }
1931                }
1932            }
1933        }
1934    }
1935
1936    /// Count a send failure (one unreachable peer must neither end the
1937    /// listener nor reach `accept`).
1938    fn count_send_error(&self, r: Result<()>) {
1939        if r.is_err() {
1940            self.send_errors.fetch_add(1, Ordering::Relaxed);
1941        }
1942    }
1943
1944    /// Whether this listener has its own crypto config (feature-gated: with
1945    /// the `crypto` feature compiled out there is no such field, and the
1946    /// adapter can never accept an encrypted connection).
1947    fn local_crypto_enabled(&self) -> bool {
1948        #[cfg(feature = "crypto")]
1949        {
1950            self.config.crypto.is_some()
1951        }
1952        #[cfg(not(feature = "crypto"))]
1953        {
1954            false
1955        }
1956    }
1957
1958    fn handle_datagram(&mut self, src: std::net::SocketAddr, bytes: &[u8]) -> Result<()> {
1959        let packet = SrtPacket::parse(bytes).map_err(|e| handshake_err("parse", e))?;
1960
1961        let ctrl = match packet {
1962            SrtPacket::Control(c) => c,
1963            _ => return Ok(()),
1964        };
1965
1966        // A repeated CONCLUSION from a Caller we already accepted means our
1967        // response never reached it: send the very same response again. A
1968        // fresh INDUCTION from the same address starts over instead.
1969        if let ControlPacket::Handshake(hp) = &ctrl {
1970            match hp.handshake_type {
1971                HandshakeType::Conclusion => {
1972                    if let Some(recent) = self.recent_accepts.get(&src)
1973                        && recent.peer_socket_id == hp.srt_socket_id
1974                        && recent.accepted_at.elapsed() < RECENT_ACCEPT_TTL
1975                    {
1976                        let response = recent.response.clone();
1977                        self.outbound_queue
1978                            .entry(src)
1979                            .or_default()
1980                            .push_back(response);
1981                        return Ok(());
1982                    }
1983                }
1984                HandshakeType::Induction => {
1985                    self.recent_accepts.remove(&src);
1986                }
1987                _ => {}
1988            }
1989        }
1990
1991        // A peer that asks for encryption is refused, never accepted: this
1992        // adapter's data path never applies the negotiated SEK (§6.1.5), so
1993        // accepting would silently exchange plaintext (or deliver a peer's
1994        // ciphertext to the application as if it were TS). With the `crypto`
1995        // feature the sans-IO engine already rejects a Key Material
1996        // *extension* (`(None, Some(km))` → `REJ_UNSECURE`, see
1997        // `listener.rs`); this adapter-level check covers a non-zero
1998        // `Encryption Field` (§3.2.1, Table 2) on any handshake and the
1999        // `KMREQ` extension-flag bit on a CONCLUSION (on an INDUCTION that
2000        // 16-bit field is the legacy UDT socket-type value, not the Table 3
2001        // bitmask — see `handshake_sm::INDUCTION_LEGACY_SOCKET_TYPE`).
2002        if !self.local_crypto_enabled()
2003            && let ControlPacket::Handshake(hp) = &ctrl
2004        {
2005            let asks_cipher = hp.encryption_field != EncryptionField::NoEncryption;
2006            let asks_kmreq =
2007                hp.handshake_type == HandshakeType::Conclusion && hp.extension_field.kmreq();
2008            if asks_cipher || asks_kmreq {
2009                // Refuse before allocating handshake state for the
2010                // source; `own_socket_id` is 0 because no socket was ever
2011                // assigned to this refused connection.
2012                let rejection = build_encryption_rejection(hp, 0, &self.config)?;
2013                self.outbound_queue
2014                    .entry(src)
2015                    .or_default()
2016                    .push_back(rejection);
2017                self.pending.remove(&src);
2018                return Ok(());
2019            }
2020        }
2021
2022        let is_new = !self.pending.contains_key(&src);
2023
2024        if is_new {
2025            // Pending state is bounded: a new source can only be admitted
2026            // after expired entries have been reaped, and even then only if
2027            // room remains — otherwise the source is ignored (§4.3.1.1's SYN
2028            // Cookie keeps unverified callers from allocating resources in
2029            // the first place; this caps what a verified-looking flood can
2030            // hold).
2031            if self.pending.len() >= MAX_PENDING {
2032                self.tick_pending();
2033                if self.pending.len() >= MAX_PENDING {
2034                    return Ok(());
2035                }
2036            }
2037
2038            let peer_isn = match &ctrl {
2039                ControlPacket::Handshake(hp) => hp.initial_seq_number,
2040                _ => return Ok(()),
2041            };
2042
2043            // Both this connection's own Socket ID and its ISN must be
2044            // freshly generated, not a predictable incrementing counter
2045            // (Socket ID) or the listener-wide `config.initial_seq_number`
2046            // reused for every accepted peer (ISN) — `draft-sharabayko-srt-01`
2047            // §3/§4.3.1.1 expects both random per connection, and either a
2048            // fixed or a sequential value lets an off-path party that
2049            // observed one accepted connection predict the next one's wire
2050            // identifiers.
2051            let own_socket_id = random_socket_id()?;
2052            let our_initial_seq = random_isn()?;
2053            let mut per_conn_config = self.config.clone();
2054            per_conn_config.initial_seq_number = our_initial_seq;
2055            // §4.3.1.1: "a cookie that is crafted based on host, port and
2056            // current time with 1 minute accuracy" — `derive_cookie` mixes
2057            // exactly those inputs (`crate::handshake_sm`'s existing,
2058            // documented derivation), keyed by this listener's own secret so
2059            // two listeners never hand out the same cookie for the same
2060            // peer/time bucket.
2061            let peer_key = addr_to_u64(&src);
2062            let time_bucket = unix_time_bucket();
2063            let syn_cookie = derive_cookie(peer_key, time_bucket, self.cookie_keys.current());
2064            let hs = ListenerHandshake::new(own_socket_id, syn_cookie, per_conn_config);
2065            self.pending.insert(
2066                src,
2067                PendingListener {
2068                    handshake: hs,
2069                    params: None,
2070                    peer_initial_seq: peer_isn,
2071                    peer_timestamp_us: 0,
2072                    concluded_at: None,
2073                    last_response: None,
2074                    our_initial_seq,
2075                },
2076            );
2077        }
2078
2079        let entry = self.pending.get_mut(&src).ok_or(Error::InvalidField {
2080            what: "pending",
2081            reason: "no pending entry",
2082        })?;
2083
2084        if let ControlPacket::Handshake(hp) = &ctrl
2085            && hp.handshake_type == HandshakeType::Conclusion
2086        {
2087            // The first CONCLUSION fixes the pair (a repeat must not move it).
2088            if entry.concluded_at.is_none() {
2089                entry.peer_timestamp_us = hp.timestamp;
2090                entry.concluded_at = Some(Instant::now());
2091            }
2092        }
2093
2094        let outcomes = entry
2095            .handshake
2096            .feed(&ctrl)
2097            .map_err(|e| handshake_err("listener feed", e))?;
2098
2099        for outcome in outcomes {
2100            match outcome {
2101                HandshakeOutput::Send(bytes) => {
2102                    entry.last_response = Some(bytes.clone());
2103                    self.outbound_queue.entry(src).or_default().push_back(bytes);
2104                }
2105                HandshakeOutput::Connected(negotiated) => {
2106                    entry.params = Some(HandshakeOutput::Connected(negotiated));
2107                }
2108                HandshakeOutput::Rejected(reason) => {
2109                    self.pending.remove(&src);
2110                    return Err(Error::Rejected(reason));
2111                }
2112                HandshakeOutput::TimedOut => {
2113                    self.pending.remove(&src);
2114                    return Err(Error::HandshakeTimedOut { stage: "listener" });
2115                }
2116            }
2117        }
2118
2119        Ok(())
2120    }
2121
2122    fn tick_pending(&mut self) {
2123        self.cookie_keys.rotate_if_due(Instant::now());
2124        let mut to_remove = Vec::new();
2125        for (addr, entry) in self.pending.iter_mut() {
2126            for outcome in entry.handshake.tick() {
2127                match outcome {
2128                    HandshakeOutput::Send(bytes) => {
2129                        self.outbound_queue
2130                            .entry(*addr)
2131                            .or_default()
2132                            .push_back(bytes);
2133                    }
2134                    HandshakeOutput::TimedOut => {
2135                        to_remove.push(*addr);
2136                    }
2137                    _ => {}
2138                }
2139            }
2140        }
2141        for addr in to_remove {
2142            self.pending.remove(&addr);
2143            // A timed-out peer will never see another packet: drop its queued
2144            // handshake bytes too, so `outbound_queue` cannot grow per-source
2145            // without bound under a flood.
2146            self.outbound_queue.remove(&addr);
2147        }
2148        self.recent_accepts
2149            .retain(|_, r| r.accepted_at.elapsed() < RECENT_ACCEPT_TTL);
2150    }
2151
2152    /// Remember an accepted connection's CONCLUSION response (bounded: expired
2153    /// entries are reaped first, then the oldest is evicted if still full).
2154    fn remember_accept(&mut self, addr: std::net::SocketAddr, recent: RecentAccept) {
2155        self.recent_accepts
2156            .retain(|_, r| r.accepted_at.elapsed() < RECENT_ACCEPT_TTL);
2157        if self.recent_accepts.len() >= MAX_RECENT_ACCEPTS
2158            && let Some(oldest) = self
2159                .recent_accepts
2160                .iter()
2161                .min_by_key(|(_, r)| r.accepted_at)
2162                .map(|(a, _)| *a)
2163        {
2164            self.recent_accepts.remove(&oldest);
2165        }
2166        self.recent_accepts.insert(addr, recent);
2167    }
2168
2169    fn drain_completed(&mut self) -> Option<Result<SrtSocket>> {
2170        // Every handle is gone: nothing may be handed over (the cancel token
2171        // ends this task right after).
2172        let life = self.life.upgrade()?;
2173        let addr = self
2174            .pending
2175            .iter()
2176            .find(|(_, p)| {
2177                p.params.is_some()
2178                    && matches!(p.handshake.state(), ListenerHandshakeState::Connected)
2179            })
2180            .map(|(addr, _)| *addr)?;
2181
2182        let entry = self.pending.remove(&addr)?;
2183        // `Connected` entries always carry negotiated parameters, but a
2184        // missing one must not panic the accept loop.
2185        let Some(negotiated) = entry.handshake.negotiated() else {
2186            return Some(Err(Error::InvalidField {
2187                what: "listener handshake",
2188                reason: "Connected without negotiated parameters",
2189            }));
2190        };
2191        let peer_initial_seq = entry.peer_initial_seq;
2192        // The peer's negotiated SRT Socket ID (distinct from its ISN above).
2193        let peer_socket_id = negotiated.peer_socket_id;
2194        // This listener's own Socket ID for this connection — the value a
2195        // real peer's packets carry as `dest_socket_id` from here on, and so
2196        // the key the routing pump demultiplexes by (item 2; see
2197        // [`routing_pump`]).
2198        let own_socket_id = negotiated.own_socket_id;
2199        // The exact ISN this listener generated for `entry` at INDUCTION
2200        // time (`handle_datagram`) — not `self.config.initial_seq_number`,
2201        // which is the listener-wide template and no longer carries the
2202        // per-connection value once randomized.
2203        let our_initial_seq = entry.our_initial_seq;
2204        let tsbpd_delay_ms = u64::from(negotiated.latency_ms);
2205        let tsbpd_time_base = tsbpd_time_base_from(entry.peer_timestamp_us);
2206        let epoch = entry.concluded_at.unwrap_or_else(Instant::now);
2207
2208        if let Some(response) = entry.last_response.clone() {
2209            self.remember_accept(
2210                addr,
2211                RecentAccept {
2212                    peer_socket_id,
2213                    response,
2214                    accepted_at: epoch,
2215                },
2216            );
2217        }
2218
2219        // Register this connection's own route in the shared demux table
2220        // (issue #1029) *before* handing off to its driver task — the
2221        // routing pump must never see a datagram naming this connection's
2222        // Socket ID land in `unrouted_rx` again once this connection exists.
2223        let (tx, rx) = mpsc::channel(RX_CHANNEL_CAPACITY);
2224        let stats = Arc::new(Counters::default());
2225        lock(&self.routes).insert(
2226            own_socket_id,
2227            RouteEntry {
2228                addr,
2229                tx,
2230                stats: Arc::clone(&stats),
2231            },
2232        );
2233
2234        // Share the listener's Arc<UdpSocket> with the connection's driver.
2235        let conn = SrtSocket::spawn(ConnParams {
2236            udp: Arc::clone(&self.udp),
2237            peer_addr: addr,
2238            rx,
2239            stats,
2240            route_cleanup: RouteCleanup(Some((own_socket_id, Arc::clone(&self.routes)))),
2241            forwarder_guard: TaskGuard(None),
2242            life: Some(life),
2243            read_idle: self.io.read_idle,
2244            write: self.io.write,
2245            our_initial_seq,
2246            peer_initial_seq,
2247            peer_socket_id,
2248            tsbpd_time_base,
2249            tsbpd_delay_ms,
2250            epoch,
2251            max_flow_window: negotiated.max_flow_window_size,
2252            mtu: negotiated.mtu,
2253            tlpkt_drop: negotiated.flags.tlpktdrop(),
2254        });
2255        Some(Ok(conn))
2256    }
2257
2258    async fn flush_for_peer(&mut self, addr: std::net::SocketAddr) -> Result<()> {
2259        if let Some(queue) = self.outbound_queue.get_mut(&addr) {
2260            while let Some(bytes) = queue.pop_front() {
2261                send_bounded(&self.udp, &bytes, addr, self.io.write, "send_to").await?;
2262            }
2263        }
2264        Ok(())
2265    }
2266
2267    async fn flush_all(&mut self) -> Result<()> {
2268        let addrs: Vec<std::net::SocketAddr> = self.outbound_queue.keys().copied().collect();
2269        for addr in addrs {
2270            self.flush_for_peer(addr).await?;
2271        }
2272        Ok(())
2273    }
2274}
2275
2276/// The single task that ever calls `recv_from` on a [`SrtListener`]'s
2277/// shared socket, demultiplexing every datagram the way libsrt does (item 2,
2278/// draft §4.3.1; libsrt's `CRcvQueue::worker` dispatches on Destination
2279/// Socket ID the same way): Destination Socket ID `0` always means "not yet
2280/// an established connection" and goes to `unrouted_tx` (`accept`'s own
2281/// input — every handshake packet this crate's Caller sends carries `0`
2282/// there, see `caller.rs`); any other ID must match a `routes` entry *and*
2283/// that entry's accepted source address, or the datagram is dropped — an ID
2284/// nothing accepted, or one accepted from a different address, has no
2285/// legitimate connection to reach. This is what makes it safe for the
2286/// listener's `accept` loop and every accepted connection's driver task to
2287/// run concurrently without racing each other for the same socket's
2288/// `recv_from`.
2289async fn routing_pump(
2290    udp: Arc<UdpSocket>,
2291    routes: RouteTable,
2292    unrouted_tx: mpsc::Sender<(std::net::SocketAddr, Bytes)>,
2293    unrouted_dropped: Arc<AtomicU64>,
2294    max_datagram: usize,
2295    cancel: CancellationToken,
2296) {
2297    let mut scratch = vec![0u8; max_datagram + 1];
2298    loop {
2299        let received = tokio::select! {
2300            _ = cancel.cancelled() => break,
2301            r = recv_datagram(&udp, &mut scratch, max_datagram, &unrouted_dropped) => r,
2302        };
2303        let (bytes, src) = match received {
2304            Ok(Some(v)) => v,
2305            Ok(None) => continue, // oversize: dropped and counted.
2306            Err(_) => break,      // socket error — end the pump.
2307        };
2308        match crate::packet::peek_dest_socket_id(&bytes) {
2309            Some(0) | None => {
2310                // `0` (candidate new connection) or too short to carry a
2311                // full header at all — either way, not a routable
2312                // established-connection packet; hand it to the handshake
2313                // task, which parses (and rejects malformed bytes) properly.
2314                if unrouted_tx.try_send((src, bytes)).is_err() {
2315                    if unrouted_tx.is_closed() {
2316                        // The handshake task is gone; nothing more this pump can do.
2317                        break;
2318                    }
2319                    unrouted_dropped.fetch_add(1, Ordering::Relaxed);
2320                }
2321            }
2322            Some(id) => {
2323                let route = lock(&routes).get(&id).cloned();
2324                // No `route` entry (no connection was ever accepted with
2325                // this ID), or one exists but from a different source
2326                // address, is never routed — spoofed-source packets
2327                // included.
2328                if let Some(entry) = route
2329                    && entry.addr == src
2330                    && entry.tx.try_send(bytes).is_err()
2331                    && !entry.tx.is_closed()
2332                {
2333                    // A closed channel would instead mean the
2334                    // connection's driver has already exited (it
2335                    // removes its own entry on the way out — see
2336                    // `RouteCleanup`), a benign race, not counted; a
2337                    // still-open-but-full channel is this connection's
2338                    // own backpressure (item 4).
2339                    entry.stats.rx_dropped.fetch_add(1, Ordering::Relaxed);
2340                }
2341            }
2342        }
2343    }
2344}
2345
2346// ===========================================================================
2347// Helpers
2348// ===========================================================================
2349
2350/// Builds a Handshake rejection packet (`Handshake Type` = `1000 + code`,
2351/// §4.3 Table 7) refusing an encryption request with
2352/// [`RejectionReason::Unsecure`] ("password required or unexpected", code
2353/// 1011) — the same wire shape `listener.rs` emits for its own rejections.
2354/// The adapter needs it because a peer can advertise encryption via the
2355/// `Encryption Field` / `KMREQ` flag bits without ever sending a Key Material
2356/// extension block for the engine to notice.
2357fn build_encryption_rejection(
2358    hp: &HandshakePacket<'_>,
2359    own_socket_id: u32,
2360    config: &HandshakeConfig,
2361) -> Result<Vec<u8>> {
2362    let hp_out = HandshakePacket {
2363        timestamp: 0,
2364        dest_socket_id: hp.srt_socket_id,
2365        version: handshake_sm::HANDSHAKE_VERSION_5,
2366        encryption_field: EncryptionField::NoEncryption,
2367        extension_field: HandshakeExtensionFlags(0),
2368        initial_seq_number: 0,
2369        mtu: config.mtu,
2370        max_flow_window_size: config.max_flow_window_size,
2371        handshake_type: RejectionReason::Unsecure.to_handshake_type(),
2372        srt_socket_id: own_socket_id,
2373        syn_cookie: 0,
2374        peer_ip: config.local_ip,
2375        extensions: HandshakeExtensions(&[]),
2376    };
2377    handshake_sm::build_bytes(hp_out)
2378}
2379
2380/// Refuses a [`HandshakeConfig`] that asks for payload encryption.
2381///
2382/// The sans-IO handshake engines implement the §6.1.5 Key Material exchange,
2383/// but this adapter's data path never applies the negotiated SEK — it would
2384/// send and receive plaintext while the caller believed the stream was
2385/// encrypted (and deliver a peer's ciphertext as if it were TS). Until the
2386/// data path is wired, an encrypted connection is refused up front instead.
2387fn refuse_crypto(config: &HandshakeConfig) -> Result<()> {
2388    #[cfg(feature = "crypto")]
2389    if config.crypto.is_some() {
2390        return Err(Error::EncryptionUnsupported);
2391    }
2392    #[cfg(not(feature = "crypto"))]
2393    let _ = config;
2394    Ok(())
2395}
2396
2397/// Runs `fut` for at most `limit`; expiry is `Error::Io { kind: TimedOut, context }`.
2398async fn bounded<T>(
2399    limit: Duration,
2400    context: &'static str,
2401    fut: impl core::future::Future<Output = Result<T>>,
2402) -> Result<T> {
2403    tokio::time::timeout(limit, fut)
2404        .await
2405        .map_err(|_| Error::Io {
2406            kind: std::io::ErrorKind::TimedOut,
2407            context,
2408        })?
2409}
2410
2411/// `send_to` bounded by `limit` (the [`IoConfig::write`] timeout).
2412async fn send_bounded(
2413    udp: &UdpSocket,
2414    bytes: &[u8],
2415    to: std::net::SocketAddr,
2416    limit: Duration,
2417    context: &'static str,
2418) -> Result<()> {
2419    bounded(limit, context, async {
2420        udp.send_to(bytes, to)
2421            .await
2422            .map(|_| ())
2423            .map_err(|e| io_err(context, e))
2424    })
2425    .await
2426}
2427
2428/// Maps an OS I/O failure to a structured [`Error::Io`], preserving the
2429/// `std::io::ErrorKind` (bind failures are then distinguishable from
2430/// mid-connection resets, etc.) and the call site that failed. `std::io::Error`
2431/// itself is not `Clone`/`Eq` (this crate's [`Error`] derives both), so only
2432/// its `kind()` is kept — see the `S4` release-audit finding.
2433fn io_err(context: &'static str, e: std::io::Error) -> Error {
2434    Error::Io {
2435        kind: e.kind(),
2436        context,
2437    }
2438}
2439
2440/// Wraps an engine/codec failure with the handshake stage it happened in,
2441/// keeping the underlying error as the source (r08-SRT-W12) rather than
2442/// flattening it to a generic invalid-field error.
2443fn handshake_err(stage: &'static str, source: Error) -> Error {
2444    Error::Handshake {
2445        stage,
2446        source: alloc::boxed::Box::new(source),
2447    }
2448}
2449
2450/// Mixes a [`std::net::SocketAddr`] into a `u64` for use as `derive_cookie`'s
2451/// `peer_key` input (§4.3.1.1: the cookie is "crafted based on host,
2452/// port..."). Not a spec-defined algorithm — any stable, well-distributed
2453/// mix of the peer's address is sufficient here: the secrecy of the cookie
2454/// rests on the keyed hash in [`derive_cookie`], not on this.
2455fn addr_to_u64(addr: &std::net::SocketAddr) -> u64 {
2456    let mut hasher = std::collections::hash_map::DefaultHasher::new();
2457    addr.hash(&mut hasher);
2458    hasher.finish()
2459}
2460
2461/// The current UNIX time, bucketed to 1-minute accuracy — the `time_bucket`
2462/// input `derive_cookie` expects (§4.3.1.1: "...and current time with 1
2463/// minute accuracy").
2464fn unix_time_bucket() -> u32 {
2465    let secs = std::time::SystemTime::now()
2466        .duration_since(std::time::UNIX_EPOCH)
2467        .unwrap_or_default()
2468        .as_secs();
2469    u32::try_from(secs / 60).unwrap_or(u32::MAX)
2470}
2471
2472/// A random `u64` from the OS randomness source (`getrandom`), used as
2473/// `derive_cookie`'s `secret` input and to draw the per-connection Socket ID
2474/// and ISN (SRT-W11). A failing OS source is reported, never panicked on.
2475fn random_u64() -> Result<u64> {
2476    let mut bytes = [0u8; 8];
2477    getrandom::getrandom(&mut bytes).map_err(|_| Error::Io {
2478        kind: std::io::ErrorKind::Other,
2479        context: "getrandom",
2480    })?;
2481    Ok(u64::from_ne_bytes(bytes))
2482}
2483
2484/// A random `u128` (two OS draws).
2485fn random_u128() -> Result<u128> {
2486    Ok((u128::from(random_u64()?) << 64) | u128::from(random_u64()?))
2487}
2488
2489/// The low 32 bits of a fresh random `u64`.
2490fn random_u32() -> Result<u32> {
2491    Ok(u32::try_from(random_u64()? & u64::from(u32::MAX)).unwrap_or(0))
2492}
2493
2494/// The largest SRT Socket ID this adapter will ever generate.
2495///
2496/// `draft-sharabayko-srt-01` §3/§4.3.1.1 gives the wire field only as "32
2497/// bits" (this crate's own `specs/ietf_draft_sharabayko_srt_01.txt`, e.g. its
2498/// Handshake Packet description — no transcription in this crate's `docs/`
2499/// narrows that range further; there is no `docs/` directory at all yet). A
2500/// real libsrt peer, though, only ever *allocates* an ID in `1..=`
2501/// [`MAX_SRT_SOCKET_ID`]: libsrt's `CUDTUnited::generateSocketID`
2502/// (`srtcore/core.cpp`) masks a freshly drawn 32-bit value down with `&
2503/// 0x3FFFFFFF` before use — bit 30 (`0x40000000`) is libsrt's own "this ID
2504/// names a socket group, not a plain socket" marker, and bit 31 would make
2505/// the ID negative when read back as libsrt's signed C `int`. Generating
2506/// outside that range is wire-legal per the draft but not a value any real
2507/// SRT implementation would ever send or expect, so this adapter matches
2508/// libsrt's allocation range rather than exercising the full 32 bits.
2509const MAX_SRT_SOCKET_ID: u32 = 0x3FFF_FFFF;
2510
2511/// A random SRT Socket ID for a new connection, drawn from the same
2512/// OS-seeded source as [`random_u64`], in `1..=`[`MAX_SRT_SOCKET_ID`] (see
2513/// its doc). Never `0` — that value marks "no socket assigned" elsewhere in
2514/// this adapter (see [`build_encryption_rejection`]'s `own_socket_id`
2515/// argument for a refused, pre-handshake peer) and is reserved for that
2516/// meaning here too — the `% MAX_SRT_SOCKET_ID` reduction followed by `+ 1`
2517/// makes both guarantees (never `0`, never above the cap) hold by
2518/// construction, with no retry loop needed.
2519fn random_socket_id() -> Result<u32> {
2520    Ok(random_u32()? % MAX_SRT_SOCKET_ID + 1)
2521}
2522
2523/// A random Initial Sequence Number in the legal 31-bit SRT sequence-number
2524/// range (`SEQ_NUMBER_MASK`, §3) for a new connection. Every new Caller
2525/// connect and every new accepted Listener connection must draw a fresh
2526/// value here rather than reuse a fixed/default `HandshakeConfig::initial_seq_number`
2527/// (SRT-W11): `draft-sharabayko-srt-01` §3/§4.3.1.1 expects the ISN
2528/// unpredictable per connection, same as the Socket ID above.
2529fn random_isn() -> Result<u32> {
2530    Ok(random_u32()? & SEQ_NUMBER_MASK)
2531}
2532
2533async fn resolve_one<A: tokio::net::ToSocketAddrs>(addr: A) -> Result<std::net::SocketAddr> {
2534    let mut addrs = tokio::net::lookup_host(addr)
2535        .await
2536        .map_err(|e| io_err("resolve", e))?;
2537    addrs.next().ok_or(Error::Io {
2538        kind: std::io::ErrorKind::AddrNotAvailable,
2539        context: "resolve: no addresses",
2540    })
2541}
2542
2543/// The fields of the peer's final handshake packet the adapter seeds its
2544/// engines from.
2545#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2546struct PeerHandshake {
2547    /// The peer's Initial Packet Sequence Number (§3.2.1).
2548    initial_seq_number: u32,
2549    /// The packet's `Timestamp` (§3), microseconds since the peer's
2550    /// connection start — `HSREQ_TIMESTAMP` of `TsbpdTimeBase = T_NOW -
2551    /// HSREQ_TIMESTAMP` (§4.5.1.1).
2552    timestamp_us: u32,
2553}
2554
2555/// Extract the peer's `initial_seq_number` and timestamp from a handshake
2556/// control packet's bytes. These seed ARQ and TSBPD sequence/time tracking for
2557/// the entire connection, so "the bytes didn't parse as a Handshake" must be a
2558/// distinct, caller-visible outcome from "the peer's ISN is genuinely 0" — the
2559/// two are otherwise indistinguishable to a caller that only sees a `u32`.
2560/// Returns [`Error::InvalidField`] rather than defaulting to `0` on any parse
2561/// failure.
2562fn peer_handshake(bytes: &[u8]) -> Result<PeerHandshake> {
2563    match SrtPacket::parse(bytes) {
2564        Ok(SrtPacket::Control(ControlPacket::Handshake(hp))) => Ok(PeerHandshake {
2565            initial_seq_number: hp.initial_seq_number,
2566            timestamp_us: hp.timestamp,
2567        }),
2568        _ => Err(Error::InvalidField {
2569            what: "peer handshake",
2570            reason: "handshake reached Connected but its final packet did not re-parse as a \
2571                     Handshake control packet; refusing to seed ARQ/TSBPD with a fabricated ISN",
2572        }),
2573    }
2574}
2575
2576/// `TsbpdTimeBase` seed (§4.5.1.1, rule 12): `T_NOW - HSREQ_TIMESTAMP` with
2577/// `T_NOW` = 0 at the connection epoch (the instant the handshake packet
2578/// arrived), i.e. minus the peer's handshake timestamp. Signed: the
2579/// timestamp, counted from the peer's own start, is generally positive, so
2580/// the base is generally negative.
2581fn tsbpd_time_base_from(peer_timestamp_us: u32) -> i64 {
2582    -i64::from(peer_timestamp_us)
2583}
2584
2585#[cfg(test)]
2586mod socket_id_tests {
2587    use super::*;
2588
2589    /// Bite test: run against the unfixed `random_socket_id` (a bare
2590    /// `random_u64() as u32`, only ever excluding `0`) and this fails —
2591    /// values above `MAX_SRT_SOCKET_ID` come up immediately (bit 31 alone is
2592    /// set on ~50% of draws). Fixed, every draw is folded into
2593    /// `1..=MAX_SRT_SOCKET_ID` by construction.
2594    #[test]
2595    fn random_socket_id_stays_in_the_libsrt_allocation_range() {
2596        for _ in 0..10_000 {
2597            let id = random_socket_id().expect("OS randomness");
2598            assert!(id != 0, "socket id must never be 0");
2599            assert!(
2600                id <= MAX_SRT_SOCKET_ID,
2601                "socket id {id:#010x} exceeds the libsrt allocation range {MAX_SRT_SOCKET_ID:#010x}"
2602            );
2603        }
2604    }
2605}
2606
2607#[cfg(test)]
2608mod isn_tests {
2609    use super::*;
2610    use crate::packet::{
2611        EncryptionField, HandshakeExtensionFlags, HandshakeExtensions, HandshakePacket,
2612        HandshakeType,
2613    };
2614
2615    fn handshake_bytes(initial_seq_number: u32) -> Vec<u8> {
2616        let hp = HandshakePacket {
2617            timestamp: 0,
2618            dest_socket_id: 0,
2619            version: 5,
2620            encryption_field: EncryptionField::NoEncryption,
2621            extension_field: HandshakeExtensionFlags(0),
2622            initial_seq_number,
2623            mtu: 1500,
2624            max_flow_window_size: 8192,
2625            handshake_type: HandshakeType::Conclusion,
2626            srt_socket_id: 42,
2627            syn_cookie: 0,
2628            peer_ip: [0; 4],
2629            extensions: HandshakeExtensions(&[]),
2630        };
2631        crate::handshake_sm::build_bytes(hp).expect("build handshake bytes")
2632    }
2633
2634    #[test]
2635    fn peer_handshake_extracts_nonzero_isn() {
2636        let bytes = handshake_bytes(0xABCD_1234);
2637        assert_eq!(
2638            peer_handshake(&bytes).unwrap().initial_seq_number,
2639            0xABCD_1234
2640        );
2641    }
2642
2643    #[test]
2644    fn peer_handshake_distinguishes_genuine_zero_from_parse_failure() {
2645        // A genuine ISN of 0 is a valid, well-formed handshake and must
2646        // succeed as Ok(0) — not be conflated with "couldn't parse".
2647        let bytes = handshake_bytes(0);
2648        assert_eq!(peer_handshake(&bytes).unwrap().initial_seq_number, 0);
2649
2650        // Bytes that don't parse as a Handshake control packet at all
2651        // (too short to even carry the fixed SRT header) must error, never
2652        // silently produce a plausible-looking 0.
2653        let err = peer_handshake(&[0u8; 4]).unwrap_err();
2654        assert!(matches!(
2655            err,
2656            Error::InvalidField {
2657                what: "peer handshake",
2658                ..
2659            }
2660        ));
2661    }
2662
2663    #[test]
2664    fn peer_handshake_rejects_non_handshake_control_packet() {
2665        // A well-formed control packet of the WRONG type (Keep-Alive, not
2666        // Handshake) must also error rather than default to 0.
2667        let ka = ControlPacket::KeepAlive(KeepAlivePacket {
2668            timestamp: 0,
2669            dest_socket_id: 7,
2670            libsrt_pad: false,
2671        });
2672        let mut buf = alloc::vec![0u8; ka.serialized_len()];
2673        ka.serialize_into(&mut buf).expect("serialize keepalive");
2674        let err = peer_handshake(&buf).unwrap_err();
2675        assert!(matches!(
2676            err,
2677            Error::InvalidField {
2678                what: "peer handshake",
2679                ..
2680            }
2681        ));
2682    }
2683}
2684
2685// ===========================================================================
2686// Adapter security tests (r08-SRT-C2 / C6 / C7)
2687// ===========================================================================
2688
2689#[cfg(all(test, feature = "tokio"))]
2690mod adapter_tests {
2691    use super::*;
2692    #[cfg(feature = "crypto")]
2693    use crate::handshake_sm::CryptoConfig;
2694    use crate::packet::{
2695        AckCif, AckPacket, DataPacket, DropReqPacket, EncryptionKeyField, HandshakeExtensionFlags,
2696        HandshakeExtensions, HandshakePacket, PacketPosition,
2697    };
2698
2699    const PEER: &str = "10.0.0.1:9999";
2700    /// TSBPD latency used by the test drivers (the spec minimum, §4.5.1).
2701    const LATENCY_MS: u64 = 120;
2702
2703    fn peer_addr() -> std::net::SocketAddr {
2704        PEER.parse().unwrap()
2705    }
2706
2707    /// A `Driver` wired to a throwaway bound socket and an unbounded delivery
2708    /// channel, with the same engine defaults `spawn` uses — so `ingress`,
2709    /// `tick_engines` and `staged` can be driven directly without a live
2710    /// handshake.
2711    async fn test_driver(max_flow_window: u32) -> (Driver, mpsc::Receiver<Bytes>) {
2712        let (driver, rx, _datagram_tx) = test_driver_with_ingress(max_flow_window).await;
2713        // The inbound-datagram sender is dropped here: the tests that use this
2714        // drive `ingress`/`tick_engines` directly, never `Driver::run`'s
2715        // select loop (which would see the closed channel as "upstream gone").
2716        (driver, rx)
2717    }
2718
2719    /// Like [`test_driver`], but also returns the live sender of the
2720    /// driver's inbound-datagram channel, so `Driver::run` can be spawned.
2721    async fn test_driver_with_ingress(
2722        max_flow_window: u32,
2723    ) -> (Driver, mpsc::Receiver<Bytes>, mpsc::Sender<Bytes>) {
2724        let udp = Arc::new(UdpSocket::bind("127.0.0.1:0").await.unwrap());
2725        // Make the socket's writability known up front. Without it the first
2726        // `send_to` yields to the reactor, and under a paused clock the
2727        // runtime would then auto-advance time to the (new) write-timeout
2728        // timer before the real send completes.
2729        udp.writable().await.unwrap();
2730        let (deliver, rx) = mpsc::channel(DELIVER_CHANNEL_CAPACITY);
2731        let (datagram_tx, datagram_rx) = mpsc::channel(RX_CHANNEL_CAPACITY);
2732        let driver = Driver::new(
2733            ConnParams {
2734                udp,
2735                peer_addr: peer_addr(),
2736                rx: datagram_rx,
2737                stats: Arc::new(Counters::default()),
2738                route_cleanup: RouteCleanup(None),
2739                forwarder_guard: TaskGuard(None),
2740                life: None,
2741                read_idle: IoConfig::default().read_idle,
2742                write: IoConfig::default().write,
2743                our_initial_seq: 0,
2744                peer_initial_seq: 0,
2745                peer_socket_id: 1,
2746                tsbpd_time_base: 0,
2747                tsbpd_delay_ms: LATENCY_MS,
2748                epoch: Instant::now(),
2749                max_flow_window,
2750                mtu: 1500,
2751                tlpkt_drop: true,
2752            },
2753            deliver,
2754        );
2755        (driver, rx, datagram_tx)
2756    }
2757
2758    fn data_bytes(seq: u32, timestamp: u32, payload: &[u8]) -> Vec<u8> {
2759        let dp = DataPacket {
2760            seq_number: seq,
2761            position: PacketPosition::Solo,
2762            in_order: true,
2763            key_flag: EncryptionKeyField::NotEncrypted,
2764            retransmitted: false,
2765            message_number: seq & crate::packet::data::MESSAGE_NUMBER_MASK,
2766            timestamp,
2767            dest_socket_id: 1,
2768            data: payload,
2769        };
2770        let mut buf = alloc::vec![0u8; dp.serialized_len()];
2771        dp.serialize_into(&mut buf).expect("serialize data");
2772        buf
2773    }
2774
2775    fn encrypted_data_bytes(seq: u32, timestamp: u32, payload: &[u8]) -> Vec<u8> {
2776        let mut buf = data_bytes(seq, timestamp, payload);
2777        // Flip the `KK` field of word 1 from `00b` to `01b` (even key).
2778        let word1 = u32::from_be_bytes([buf[4], buf[5], buf[6], buf[7]]);
2779        let word1 = (word1 & !(0b11 << 27)) | (u32::from(EncryptionKeyField::Even.to_bits()) << 27);
2780        buf[4..8].copy_from_slice(&word1.to_be_bytes());
2781        buf
2782    }
2783
2784    fn dropreq_bytes(first: u32, last: u32) -> Vec<u8> {
2785        let pkt = ControlPacket::DropReq(DropReqPacket {
2786            message_number: 0,
2787            timestamp: 0,
2788            dest_socket_id: 1,
2789            first_seq: first,
2790            last_seq: last,
2791        });
2792        let mut buf = alloc::vec![0u8; pkt.serialized_len()];
2793        pkt.serialize_into(&mut buf).expect("serialize dropreq");
2794        buf
2795    }
2796
2797    fn induction_bytes(socket_id: u32) -> Vec<u8> {
2798        let hp = HandshakePacket {
2799            timestamp: 0,
2800            dest_socket_id: 0,
2801            version: crate::handshake_sm::HANDSHAKE_VERSION_4,
2802            encryption_field: crate::packet::EncryptionField::NoEncryption,
2803            extension_field: HandshakeExtensionFlags(
2804                crate::handshake_sm::INDUCTION_LEGACY_SOCKET_TYPE,
2805            ),
2806            initial_seq_number: 0,
2807            mtu: 1500,
2808            max_flow_window_size: 8192,
2809            handshake_type: crate::packet::HandshakeType::Induction,
2810            srt_socket_id: socket_id,
2811            syn_cookie: 0,
2812            peer_ip: [0; 4],
2813            extensions: HandshakeExtensions(&[]),
2814        };
2815        let pkt = ControlPacket::Handshake(hp);
2816        let mut buf = alloc::vec![0u8; pkt.serialized_len()];
2817        pkt.serialize_into(&mut buf).expect("serialize induction");
2818        buf
2819    }
2820
2821    /// Review-focus 2. UDP truncates a datagram larger than the receive buffer
2822    /// without telling the reader; a truncated DATA packet then parses as a
2823    /// shorter, valid packet and its payload is delivered corrupted. The
2824    /// forwarder must read `max + 1` bytes, drop anything longer than `max`,
2825    /// and count it.
2826    #[tokio::test]
2827    async fn an_oversize_datagram_is_dropped_and_counted_never_truncated() {
2828        let local = Arc::new(UdpSocket::bind("127.0.0.1:0").await.unwrap());
2829        let peer = UdpSocket::bind("127.0.0.1:0").await.unwrap();
2830        let stats = Arc::new(Counters::default());
2831        let (mut rx, _guard) = spawn_dedicated_socket_forwarder(
2832            Arc::clone(&local),
2833            peer.local_addr().unwrap(),
2834            Arc::clone(&stats),
2835            300,
2836        );
2837        let local_addr = local.local_addr().unwrap();
2838        peer.send_to(&[1u8; 250], local_addr).await.unwrap();
2839        peer.send_to(&[2u8; 400], local_addr).await.unwrap(); // > 300
2840        peer.send_to(&[3u8; 300], local_addr).await.unwrap(); // exactly max: accepted
2841        let a = rx.recv().await.unwrap();
2842        let b = rx.recv().await.unwrap();
2843        assert_eq!((a.len(), a[0]), (250, 1));
2844        assert_eq!(
2845            (b.len(), b[0]),
2846            (300, 3),
2847            "the 400-byte datagram must not appear, truncated or not"
2848        );
2849        assert_eq!(stats.rx_oversize.load(Ordering::Relaxed), 1);
2850    }
2851
2852    #[test]
2853    fn io_config_clamps_a_tiny_max_datagram() {
2854        assert_eq!(
2855            IoConfig::default().with_max_datagram(1).max_datagram,
2856            MIN_MAX_DATAGRAM
2857        );
2858        assert_eq!(IoConfig::default().max_datagram, 1500);
2859        assert_eq!(
2860            IoConfig::default()
2861                .with_max_datagram(usize::MAX)
2862                .max_datagram,
2863            MAX_MAX_DATAGRAM,
2864            "an absurd size is clamped, never overflows `max + 1`"
2865        );
2866    }
2867
2868    #[tokio::test(start_paused = true)]
2869    async fn an_idle_driver_deadline_is_the_ack_period_not_a_two_ms_tick() {
2870        let (driver, _rx) = test_driver(8192).await;
2871        let d = driver
2872            .poll_timeout()
2873            .expect("a connected driver always has a deadline");
2874        assert_eq!(d - driver.epoch, crate::arq::FULL_ACK_PERIOD);
2875    }
2876
2877    /// The old fixed 2 ms ticker ran `tick_engines` ~50 times per 100 ms of idle time; the
2878    /// deadline-driven loop wakes for the 10 ms ACK cadence only.
2879    #[tokio::test(start_paused = true)]
2880    async fn the_run_loop_wakes_at_deadlines_not_on_a_fixed_two_ms_tick() {
2881        let (mut driver, _rx, _tx) = test_driver_with_ingress(8192).await;
2882        // The loop really sends its ACKs: a loopback address accepts them, where
2883        // the default non-routable test peer errors on some hosts and ends the loop.
2884        driver.peer_addr = "127.0.0.1:1".parse().unwrap();
2885        let ticks = Arc::new(AtomicU64::new(0));
2886        driver.tick_counter = Some(Arc::clone(&ticks));
2887        let (_app_tx, app_rx) = mpsc::channel(8);
2888        let handle = tokio::spawn(driver.run(app_rx));
2889        // `advance` jumps the clock in ONE step, so walk it 1 ms at a time to let every timer fire in order.
2890        for _ in 0..100 {
2891            tokio::time::advance(Duration::from_millis(1)).await;
2892            tokio::task::yield_now().await;
2893        }
2894        let n = ticks.load(Ordering::Relaxed);
2895        assert!(
2896            (8..=14).contains(&n),
2897            "expected ~10 wake-ups in 100 ms (10 ms ACK cadence), got {n}"
2898        );
2899        handle.abort();
2900    }
2901
2902    /// A [`ListenerCore`] over a throwaway socket, never spawned: tests drive
2903    /// `handle_datagram`/`tick_pending` and read its state directly.
2904    async fn test_core(config: HandshakeConfig) -> ListenerCore {
2905        test_core_with_channels(config).await.0
2906    }
2907
2908    /// [`test_core`] plus the live ends of its channels: the unrouted-datagram
2909    /// sender and the accepted-connection receiver.
2910    async fn test_core_with_channels(
2911        config: HandshakeConfig,
2912    ) -> (
2913        ListenerCore,
2914        mpsc::Sender<(std::net::SocketAddr, Bytes)>,
2915        mpsc::Receiver<Result<SrtSocket>>,
2916    ) {
2917        let udp = Arc::new(UdpSocket::bind("127.0.0.1:0").await.unwrap());
2918        let (unrouted_tx, unrouted_rx) = mpsc::channel(UNROUTED_CHANNEL_CAPACITY);
2919        let (accepted_tx, accepted) = mpsc::channel(ACCEPT_BACKLOG);
2920        let core = ListenerCore {
2921            udp,
2922            config,
2923            io: IoConfig::default(),
2924            cookie_keys: CookieKeys::new(Instant::now()).unwrap(),
2925            pending: std::collections::HashMap::new(),
2926            outbound_queue: std::collections::HashMap::new(),
2927            recent_accepts: std::collections::HashMap::new(),
2928            routes: Arc::new(Mutex::new(std::collections::HashMap::new())),
2929            unrouted_rx,
2930            life: std::sync::Weak::new(),
2931            accepted_tx,
2932            overflow_dropped: Arc::new(AtomicU64::new(0)),
2933            send_errors: Arc::new(AtomicU64::new(0)),
2934            accepting: true,
2935            last_pending_tick: Instant::now(),
2936        };
2937        (core, unrouted_tx, accepted)
2938    }
2939
2940    #[tokio::test(start_paused = true)]
2941    async fn bounded_turns_a_stuck_future_into_a_timed_out_io_error() {
2942        let r: Result<()> = bounded(
2943            Duration::from_secs(3),
2944            "send",
2945            std::future::pending::<Result<()>>(),
2946        )
2947        .await;
2948        assert!(
2949            matches!(
2950                r,
2951                Err(Error::Io {
2952                    kind: std::io::ErrorKind::TimedOut,
2953                    context: "send"
2954                })
2955            ),
2956            "{r:?}"
2957        );
2958    }
2959
2960    #[tokio::test(start_paused = true)]
2961    async fn the_configured_read_idle_replaces_the_five_second_constant() {
2962        let (mut driver, _rx) = test_driver(8192).await;
2963        driver.read_idle = Duration::from_secs(2);
2964        assert!(!driver.peer_idle(Instant::now()));
2965        tokio::time::advance(Duration::from_secs(2)).await;
2966        assert!(
2967            driver.peer_idle(Instant::now()),
2968            "idle after the configured 2 s, not 5 s"
2969        );
2970    }
2971
2972    /// Real time, real socket: a paused clock would auto-advance past the
2973    /// timers while the first `send_to` waits on the reactor.
2974    #[tokio::test]
2975    async fn the_handshake_budget_comes_from_the_config() {
2976        // black hole: bound UDP socket that never answers
2977        let hole = UdpSocket::bind("127.0.0.1:0").await.unwrap();
2978        let budget = Duration::from_millis(400);
2979        let io = IoConfig::default().with_handshake(budget);
2980        let t0 = Instant::now();
2981        let err =
2982            SrtSocket::connect_with(hole.local_addr().unwrap(), HandshakeConfig::default(), io)
2983                .await
2984                .expect_err("nobody answers");
2985        // The default retransmit budget (12 x 250 ms) would end an unanswered connect at ~3 s with
2986        // stage "caller retransmit budget"; only the configured deadline yields "caller connect".
2987        assert!(
2988            matches!(
2989                err,
2990                Error::HandshakeTimedOut {
2991                    stage: "caller connect"
2992                }
2993            ),
2994            "{err:?}"
2995        );
2996        let took = Instant::now() - t0;
2997        assert!(
2998            took >= budget && took < Duration::from_secs(2),
2999            "the configured {budget:?} deadline, got {took:?}"
3000        );
3001        drop(hole);
3002    }
3003
3004    // -----------------------------------------------------------------------
3005    // Each `Driver::poll_timeout` term, with every EARLIER term pushed out of
3006    // the way, so deleting any one of them changes the asserted deadline.
3007    // -----------------------------------------------------------------------
3008
3009    async fn quiet_driver() -> Driver {
3010        let (mut driver, _rx) = test_driver(8192).await;
3011        driver.peer_addr = "127.0.0.1:1".parse().unwrap();
3012        driver
3013    }
3014
3015    /// TSBPD release: a packet due at 120 ms, the Full ACK just ticked at
3016    /// 118 ms (next ACK 128 ms), so the release is the earliest deadline.
3017    #[tokio::test(start_paused = true)]
3018    async fn the_deadline_is_the_tsbpd_release_when_it_is_the_earliest_term() {
3019        let mut driver = quiet_driver().await;
3020        driver.ingress(Bytes::from(data_bytes(0, 0, b"p"))).unwrap();
3021        tokio::time::advance(Duration::from_millis(118)).await;
3022        driver.tick_engines();
3023        assert_eq!(
3024            driver.poll_timeout().unwrap(),
3025            driver.epoch + Duration::from_millis(LATENCY_MS),
3026            "the TSBPD release must be the next wake-up"
3027        );
3028    }
3029
3030    /// Pacing: a queued DATA packet whose slot is 3 ms away beats the 10 ms ACK.
3031    #[tokio::test(start_paused = true)]
3032    async fn the_deadline_is_the_pacing_slot_when_it_is_the_earliest_term() {
3033        let mut driver = quiet_driver().await;
3034        let now = Instant::now();
3035        driver.outbound_data.push_back(alloc::vec![0u8; 100]);
3036        driver.next_data_send_at = Some(now + Duration::from_millis(3));
3037        assert_eq!(
3038            driver.poll_timeout().unwrap(),
3039            now + Duration::from_millis(3),
3040            "the pacing slot must be the next wake-up"
3041        );
3042    }
3043
3044    /// Peer idle: a 4 ms read-idle limit beats the 10 ms ACK and the 1 s keep-alive.
3045    #[tokio::test(start_paused = true)]
3046    async fn the_deadline_is_the_peer_idle_expiry_when_it_is_the_earliest_term() {
3047        let mut driver = quiet_driver().await;
3048        driver.read_idle = Duration::from_millis(4);
3049        assert_eq!(
3050            driver.poll_timeout().unwrap(),
3051            driver.last_rx_at + Duration::from_millis(4),
3052            "the peer-idle expiry must be the next wake-up"
3053        );
3054    }
3055
3056    /// Keep-Alive: nothing sent for 995 ms and nothing queued, so the keep-alive
3057    /// at +5 ms beats the 10 ms ACK.
3058    #[tokio::test(start_paused = true)]
3059    async fn the_deadline_is_the_keepalive_when_it_is_the_earliest_term() {
3060        let mut driver = quiet_driver().await;
3061        let now = Instant::now();
3062        driver.last_tx_at = now - Duration::from_millis(995);
3063        assert!(driver.outbound_control.is_empty() && driver.outbound_data.is_empty());
3064        assert_eq!(
3065            driver.poll_timeout().unwrap(),
3066            now + Duration::from_millis(5),
3067            "the keep-alive must be the next wake-up"
3068        );
3069        // ... and it is NOT a term while something is queued.
3070        driver.outbound_control.push_back(alloc::vec![0u8; 16]);
3071        assert_eq!(
3072            driver.poll_timeout().unwrap(),
3073            driver.epoch + crate::arq::FULL_ACK_PERIOD
3074        );
3075    }
3076
3077    /// Wake the loop exactly as `run` would (at `poll_timeout`) for `window`
3078    /// of virtual time, returning how many DATA packets left the queue.
3079    async fn drain_for(driver: &mut Driver, window: Duration) -> usize {
3080        let start = Instant::now();
3081        let before = driver.outbound_data.len();
3082        while Instant::now() - start < window {
3083            let at = driver.poll_timeout().unwrap();
3084            tokio::time::advance(at - Instant::now()).await;
3085            driver.tick_engines();
3086            driver.flush_outbound().await.expect("flush");
3087        }
3088        before - driver.outbound_data.len()
3089    }
3090
3091    /// A backlog with NO inbound events and no application traffic (retransmit
3092    /// burst after a NAK, idle app) drains at wake-up granularity: the old
3093    /// one-packet-per-wake ceiling was ~10.5 Mbit/s.
3094    #[tokio::test(start_paused = true)]
3095    async fn an_idle_backlog_drains_faster_than_one_packet_per_wake() {
3096        let mut driver = quiet_driver().await;
3097        for _ in 0..3000 {
3098            driver.send_one(&[0u8; 1316]);
3099        }
3100        let sent = drain_for(&mut driver, Duration::from_millis(100)).await;
3101        let mbit_s = sent as f64 * 1316.0 * 8.0 / 0.1 / 1e6;
3102        assert!(
3103            mbit_s >= 20.0,
3104            "drained {sent} packets in 100 ms = {mbit_s:.1} Mbit/s"
3105        );
3106    }
3107
3108    /// Pacing still holds with catch-up: at 2.5 MB/s (20 Mbit/s) 100 ms is ~190
3109    /// packets plus at most one burst, never an instantaneous dump.
3110    #[tokio::test(start_paused = true)]
3111    async fn catch_up_never_exceeds_the_paced_rate_by_more_than_one_burst() {
3112        let mut driver = quiet_driver().await;
3113        for _ in 0..3000 {
3114            driver.send_one(&[0u8; 1316]);
3115        }
3116        driver.livecc = LiveCC::new(MaxBwConfig::Set(2_500_000));
3117        driver.livecc.on_data_packet(1316);
3118        let sent = drain_for(&mut driver, Duration::from_millis(100)).await;
3119        let allowed = (2_500_000.0_f64 * 0.1 / 1316.0).ceil() as usize + PACING_BURST_CAP + 1;
3120        assert!(
3121            sent <= allowed,
3122            "sent {sent} packets, paced allowance {allowed}"
3123        );
3124        assert!(sent >= 100, "pacing starved the drain: {sent}");
3125    }
3126
3127    // -----------------------------------------------------------------------
3128    // Listener: the deadline wiring and send-error handling
3129    // -----------------------------------------------------------------------
3130
3131    #[tokio::test]
3132    async fn the_listener_deadline_exists_only_while_a_handshake_is_pending() {
3133        let mut core = test_core(HandshakeConfig::default()).await;
3134        assert_eq!(core.poll_timeout(), None, "an idle listener has no timer");
3135        core.handle_datagram(peer_addr(), &induction_bytes(7))
3136            .expect("induction");
3137        assert_eq!(
3138            core.poll_timeout(),
3139            Some(core.last_pending_tick + PENDING_TICK_INTERVAL)
3140        );
3141        core.accepting = false;
3142        assert_eq!(
3143            core.poll_timeout(),
3144            None,
3145            "a handle-less core serves nobody"
3146        );
3147    }
3148
3149    /// The run loop actually ticks a pending handshake on that deadline: with no
3150    /// further inbound traffic the INDUCTION response is retransmitted.
3151    #[tokio::test]
3152    async fn a_pending_handshake_is_retransmitted_by_the_listener_tick_alone() {
3153        let config = HandshakeConfig {
3154            retransmit_after_ticks: 1,
3155            max_retries: 5,
3156            ..HandshakeConfig::default()
3157        };
3158        let (core, unrouted_tx, _accepted) = test_core_with_channels(config).await;
3159        let peer = UdpSocket::bind("127.0.0.1:0").await.unwrap();
3160        let cancel = CancellationToken::new();
3161        let task = tokio::spawn(core.run(cancel.clone()));
3162        unrouted_tx
3163            .send((peer.local_addr().unwrap(), Bytes::from(induction_bytes(7))))
3164            .await
3165            .unwrap();
3166        let mut buf = [0u8; 2048];
3167        for n in 1..=2 {
3168            tokio::time::timeout(Duration::from_secs(5), peer.recv_from(&mut buf))
3169                .await
3170                .unwrap_or_else(|_| panic!("datagram {n} never arrived: the tick is not wired"))
3171                .unwrap();
3172        }
3173        cancel.cancel();
3174        let _ = task.await;
3175    }
3176
3177    /// Send errors are counted, never queued: a flood of them must not touch
3178    /// the accept queue that finished connections depend on.
3179    #[tokio::test]
3180    async fn a_flood_of_send_errors_does_not_displace_completed_connections() {
3181        let (core, _tx, mut accepted) = test_core_with_channels(HandshakeConfig::default()).await;
3182        for _ in 0..(ACCEPT_BACKLOG * 20) {
3183            core.count_send_error(Err(Error::Io {
3184                kind: std::io::ErrorKind::HostUnreachable,
3185                context: "send_to",
3186            }));
3187        }
3188        assert_eq!(
3189            core.send_errors.load(Ordering::Relaxed),
3190            (ACCEPT_BACKLOG * 20) as u64
3191        );
3192        assert_eq!(
3193            core.accepted_tx.capacity(),
3194            ACCEPT_BACKLOG,
3195            "every accept-queue slot is still free for a real connection"
3196        );
3197        assert!(accepted.try_recv().is_err());
3198    }
3199
3200    fn drain_deliveries(rx: &mut mpsc::Receiver<Bytes>) -> Vec<Bytes> {
3201        let mut out = Vec::new();
3202        while let Ok(payload) = rx.try_recv() {
3203            out.push(payload);
3204        }
3205        out
3206    }
3207
3208    // -----------------------------------------------------------------------
3209    // Item 1 — refuse encryption in the tokio adapter
3210    // -----------------------------------------------------------------------
3211
3212    #[cfg(feature = "crypto")]
3213    fn crypto_config() -> HandshakeConfig {
3214        HandshakeConfig {
3215            crypto: Some(CryptoConfig {
3216                passphrase: b"test-passphrase".to_vec(),
3217                salt: [0x11u8; crate::crypto::SALT_LEN],
3218                sek: vec![0x22u8; 16],
3219            }),
3220            ..HandshakeConfig::default()
3221        }
3222    }
3223
3224    #[cfg(feature = "crypto")]
3225    #[tokio::test]
3226    async fn connect_with_crypto_is_refused_before_any_io() {
3227        // A bound UDP socket stands in for the "peer": a refused connection
3228        // must not emit even the INDUCTION datagram.
3229        let peer_socket = UdpSocket::bind("127.0.0.1:0").await.unwrap();
3230        let peer_addr = peer_socket.local_addr().unwrap();
3231
3232        let result = tokio::time::timeout(
3233            Duration::from_millis(2_000),
3234            SrtSocket::connect(peer_addr, crypto_config()),
3235        )
3236        .await
3237        .expect("crypto refusal must return immediately, not run the handshake");
3238
3239        let err = result.expect_err("crypto-enabled connect must be refused");
3240        assert!(
3241            matches!(err, Error::EncryptionUnsupported),
3242            "expected EncryptionUnsupported, got {err:?}"
3243        );
3244
3245        let mut buf = [0u8; 64];
3246        assert!(
3247            tokio::time::timeout(Duration::from_millis(200), peer_socket.recv_from(&mut buf))
3248                .await
3249                .is_err(),
3250            "a refused connect must send nothing to the peer"
3251        );
3252    }
3253
3254    #[cfg(feature = "crypto")]
3255    #[tokio::test]
3256    async fn bind_with_crypto_is_refused() {
3257        let err = SrtListener::bind("127.0.0.1:0", crypto_config())
3258            .await
3259            .expect_err("crypto-enabled bind must be refused");
3260        assert!(
3261            matches!(err, Error::EncryptionUnsupported),
3262            "expected EncryptionUnsupported, got {err:?}"
3263        );
3264    }
3265
3266    #[tokio::test]
3267    async fn encrypted_data_packet_is_never_staged_or_delivered() {
3268        let (mut driver, mut rx) = test_driver(8192).await;
3269        let ts = 0u32;
3270        // The unencrypted packet at seq 0 is staged normally.
3271        driver
3272            .ingress(Bytes::from(data_bytes(0, ts, b"plain")))
3273            .expect("ingress plain");
3274        // An encrypted packet (KK != 0) must never reach `staged` or the app.
3275        driver
3276            .ingress(Bytes::from(encrypted_data_bytes(1, ts, b"ciphertext")))
3277            .expect("ingress encrypted");
3278
3279        assert!(
3280            !driver.staged.contains_key(&1),
3281            "a KK != 0 data packet must never be staged"
3282        );
3283        let delivered = drain_deliveries(&mut rx);
3284        assert!(
3285            delivered.iter().all(|p| &p[..] != b"ciphertext"),
3286            "ciphertext must never be delivered to the application"
3287        );
3288    }
3289
3290    // -----------------------------------------------------------------------
3291    // Issue #1062 — sequence/message-number wrap must not panic
3292    // -----------------------------------------------------------------------
3293
3294    /// Pre-fix, `send_one` incremented both counters with a plain
3295    /// `u32::wrapping_add(1)` (wraps at `u32::MAX`, not the wire field's own
3296    /// bit width). Starting both counters two steps below their real 31-bit
3297    /// (sequence) / 26-bit (message number) boundaries and sending four
3298    /// packets crosses both wraps; pre-fix this panicked inside
3299    /// `DataPacket::serialize_into`'s `.expect("buffer sized from
3300    /// serialized_len")` call sites in `arq::sender` with `FieldTooWide`
3301    /// (verified via a copied pre-fix `io.rs`, `git show HEAD:srt-runtime/src/io.rs`,
3302    /// never `git stash` — shared worktree — swapped back immediately after:
3303    /// `panicked ... buffer sized from serialized_len: FieldTooWide { what:
3304    /// "Packet Sequence Number", value: 2147483648, bits: 31 }`).
3305    #[tokio::test]
3306    async fn send_one_wraps_seq_and_message_number_without_panicking() {
3307        let (mut driver, _rx) = test_driver(8192).await;
3308        driver.next_send_seq = SEQ_NUMBER_MASK - 1;
3309        driver.next_message_number = crate::packet::data::MESSAGE_NUMBER_MASK - 1;
3310
3311        // Four sends: seq goes MASK-1, MASK, 0, 1 (wrapping at 2^31); message
3312        // number goes MASK-1, MASK, 1, 2 (wrapping at 2^26 but skipping 0 —
3313        // libsrt's `SRT_MSGNO_CONTROL` sentinel, see `next_message_number`).
3314        // Each call re-derives the wire bytes through the exact
3315        // `serialize_into` path the panic was in — reaching here without
3316        // panicking is the test.
3317        for _ in 0..4 {
3318            driver.send_one(b"payload");
3319        }
3320
3321        assert_eq!(
3322            driver.next_send_seq, 2,
3323            "sequence number must wrap at 2^31, not 2^32"
3324        );
3325        assert_eq!(
3326            driver.next_message_number, 3,
3327            "message number must wrap at 2^26 (skipping 0), not 2^32"
3328        );
3329
3330        // Every enqueued DATA packet must itself carry a legal (in-range)
3331        // seq/message number — not just the counter that produced it.
3332        for bytes in &driver.outbound_data {
3333            let dp = DataPacket::parse(bytes).expect("parse enqueued data packet");
3334            assert!(dp.seq_number <= SEQ_NUMBER_MASK);
3335            assert!(dp.message_number <= crate::packet::data::MESSAGE_NUMBER_MASK);
3336        }
3337    }
3338
3339    // -----------------------------------------------------------------------
3340    // Item 6 — ACK/NAK must not queue behind a not-yet-due paced DATA packet
3341    // -----------------------------------------------------------------------
3342
3343    /// Pre-fix, a single FIFO `outbound` queue (each item tagged `is_data`)
3344    /// meant `flush_outbound` stopped at the first not-yet-due DATA packet
3345    /// and never looked past it — so an AckAck enqueued *behind* one (the
3346    /// ordinary case: `send_one` queues DATA, then the peer's own Ack —
3347    /// handled by `ingress` — queues the reply) sat there just as
3348    /// pacing-throttled as the DATA in front of it, even though §5.1.2 paces
3349    /// DATA only.
3350    #[tokio::test]
3351    async fn ackack_is_not_queued_behind_a_not_yet_due_paced_data_packet() {
3352        let (mut driver, _rx) = test_driver(8192).await;
3353        // `flush_outbound` does a real `send_to` below — a loopback address
3354        // accepts it without needing an actual listener there, unlike
3355        // `test_driver`'s default non-routable `PEER` test address.
3356        driver.peer_addr = "127.0.0.1:1".parse().unwrap();
3357        // A near-zero bandwidth cap pushes each DATA packet's pacing slot far
3358        // into the future. The very first send establishes that pacing
3359        // schedule (there is no deadline yet before anything has been sent);
3360        // the second one is the packet this test actually checks stays
3361        // queued behind its own not-yet-arrived slot.
3362        driver.livecc = LiveCC::new(MaxBwConfig::Set(1));
3363        driver.send_one(&[0u8; 200]);
3364        driver
3365            .flush_outbound()
3366            .await
3367            .expect("flush first data packet");
3368        driver.send_one(&[0u8; 200]);
3369        assert_eq!(driver.outbound_data.len(), 1, "second DATA must be queued");
3370        assert!(
3371            driver.next_paced_send_wait().is_some(),
3372            "the second DATA packet must not be immediately due"
3373        );
3374
3375        let ack = ControlPacket::Ack(AckPacket {
3376            ack_number: 1,
3377            timestamp: 0,
3378            dest_socket_id: 1,
3379            cif: AckCif::Full {
3380                last_ack_seq: 0,
3381                rtt_us: 0,
3382                rtt_var_us: 0,
3383                avail_buf_size: 8192,
3384                pkt_recv_rate: 0,
3385                est_link_capacity: 0,
3386                recv_rate_bps: 0,
3387            },
3388        });
3389        let mut ack_bytes = alloc::vec![0u8; ack.serialized_len()];
3390        ack.serialize_into(&mut ack_bytes).expect("serialize ack");
3391        driver.ingress(Bytes::from(ack_bytes)).expect("ingress ack");
3392        assert_eq!(
3393            driver.outbound_control.len(),
3394            1,
3395            "the peer's Ack must have queued exactly one AckAck"
3396        );
3397
3398        driver.flush_outbound().await.expect("flush");
3399
3400        assert!(
3401            driver.outbound_control.is_empty(),
3402            "the AckAck must have been sent even though the DATA packet's \
3403             pacing slot had not arrived yet"
3404        );
3405        assert_eq!(
3406            driver.outbound_data.len(),
3407            1,
3408            "the still-not-due DATA packet must remain queued, untouched"
3409        );
3410    }
3411
3412    // -----------------------------------------------------------------------
3413    // Item 2 — one loss must not freeze delivery or grow memory
3414    // -----------------------------------------------------------------------
3415
3416    // Paused-clock tests: `Driver` reads `tokio::time::Instant`, so
3417    // `tokio::time::advance` moves its notion of "now" exactly and instantly —
3418    // no real sleeping, no dependence on scheduler timing.
3419
3420    #[tokio::test(start_paused = true)]
3421    async fn delivery_resumes_after_permanent_loss_once_latency_passes() {
3422        let (mut driver, mut rx) = test_driver(8192).await;
3423        let ts0 = 0u32; // the driver epoch is "now" under the paused clock
3424
3425        // seq 1 is lost and never retransmitted.
3426        for seq in [0u32, 2, 3] {
3427            driver
3428                .ingress(Bytes::from(data_bytes(
3429                    seq,
3430                    ts0,
3431                    &[u8::try_from(seq).unwrap()],
3432                )))
3433                .expect("ingress");
3434        }
3435        assert!(
3436            drain_deliveries(&mut rx).is_empty(),
3437            "play time not yet due"
3438        );
3439
3440        // §4.6 / rule 21: at the successor's play time (one latency after
3441        // send) the gap is skipped and packets 2 and 3 are DELIVERED — not
3442        // thrown away with the lost packet. Step the clock like the driver's
3443        // ticker would, finishing well inside the too-late threshold window.
3444        let mut delivered = Vec::new();
3445        for _ in 0..40 {
3446            tokio::time::advance(Duration::from_millis(10)).await;
3447            driver.tick_engines();
3448            delivered.extend(drain_deliveries(&mut rx));
3449            if delivered.len() >= 3 {
3450                break;
3451            }
3452        }
3453        let seqs: Vec<u8> = delivered.iter().map(|p| p[0]).collect();
3454        assert_eq!(
3455            seqs,
3456            vec![0, 2, 3],
3457            "the gap must be skipped at the successor's play time and its \
3458             packets delivered (live mode, §4.6/rule 21)"
3459        );
3460    }
3461
3462    /// r08-SRT-W2 (adapter side): when TSBPD gives up on a packet (§4.6), the
3463    /// ARQ receiver's ack point follows it — the "fake ACK" of Too-Late
3464    /// Packet Drop. Otherwise it keeps NAKing a packet nobody will ever
3465    /// deliver, the ACKs never let the peer free anything past it, and the
3466    /// flow window it measures arrivals against stalls at the lost packet.
3467    #[tokio::test(start_paused = true)]
3468    async fn a_tsbpd_skip_advances_the_arq_ack_point() {
3469        let (mut driver, mut rx) = test_driver(8192).await;
3470        for seq in [0u32, 2, 3] {
3471            driver
3472                .ingress(Bytes::from(data_bytes(
3473                    seq,
3474                    0,
3475                    &[u8::try_from(seq).unwrap()],
3476                )))
3477                .expect("ingress");
3478        }
3479        assert_eq!(driver.receiver.ack_point(), 1, "stalled at the gap");
3480        assert_eq!(driver.receiver.loss_list_len(), 1, "seq 1 is NAKed");
3481
3482        tokio::time::advance(Duration::from_millis(130)).await;
3483        driver.tick_engines();
3484        assert_eq!(
3485            drain_deliveries(&mut rx).len(),
3486            3,
3487            "0, 2, 3 delivered once the gap is skipped"
3488        );
3489        assert_eq!(
3490            driver.receiver.ack_point(),
3491            4,
3492            "the ack point must move past the packet TSBPD dropped"
3493        );
3494        assert_eq!(
3495            driver.receiver.loss_list_len(),
3496            0,
3497            "a dropped packet must not stay in the loss list (it would be NAKed forever)"
3498        );
3499    }
3500
3501    /// A delivered packet's payload is a view into the received datagram's own
3502    /// allocation (header sliced off the front) — one copy from the socket
3503    /// buffer, not a second `to_vec` per packet (r08-SRT-O4). Pointer identity
3504    /// is the deterministic evidence: a copy would live at a different address.
3505    #[tokio::test(start_paused = true)]
3506    async fn delivery_reuses_the_received_datagrams_allocation() {
3507        let (mut driver, mut rx) = test_driver(8192).await;
3508        let datagram = bytes::Bytes::from(data_bytes(0, 0, b"zero-copy payload"));
3509        let allocation = datagram.as_ptr() as usize;
3510        driver.ingress(datagram).expect("ingress");
3511        tokio::time::advance(Duration::from_millis(130)).await;
3512        driver.tick_engines();
3513        let mut delivered = drain_deliveries(&mut rx);
3514        assert_eq!(delivered.len(), 1);
3515        let payload = delivered.remove(0);
3516        assert_eq!(&payload[..], b"zero-copy payload");
3517        assert_eq!(
3518            payload.as_ptr() as usize,
3519            allocation + SRT_HEADER_LEN,
3520            "the payload must be a view into the received datagram, not a copy"
3521        );
3522    }
3523
3524    #[tokio::test(start_paused = true)]
3525    async fn dropreq_unblocks_delivery_immediately() {
3526        let (mut driver, mut rx) = test_driver(8192).await;
3527        let ts0 = 0u32;
3528
3529        for seq in [0u32, 2, 3] {
3530            driver
3531                .ingress(Bytes::from(data_bytes(
3532                    seq,
3533                    ts0,
3534                    &[u8::try_from(seq).unwrap()],
3535                )))
3536                .expect("ingress");
3537        }
3538        assert!(
3539            drain_deliveries(&mut rx).is_empty(),
3540            "play time not yet due"
3541        );
3542
3543        // The peer announces it will never send seq 1.
3544        driver
3545            .ingress(Bytes::from(dropreq_bytes(1, 1)))
3546            .expect("ingress dropreq");
3547
3548        tokio::time::advance(Duration::from_millis(140)).await;
3549        driver.tick_engines();
3550
3551        let delivered = drain_deliveries(&mut rx);
3552        let seqs: Vec<u8> = delivered.iter().map(|p| p[0]).collect();
3553        assert_eq!(seqs, vec![0, 2, 3], "DROPREQ must unblock the gap");
3554    }
3555
3556    #[tokio::test]
3557    async fn staged_never_exceeds_the_flow_window() {
3558        const WINDOW: u32 = 64;
3559        let (mut driver, mut rx) = test_driver(WINDOW).await;
3560        let ts = 0u32;
3561
3562        // seq 0 is the delivery cursor and never arrives; feed window+100
3563        // packets past the gap.
3564        for seq in 1..=(WINDOW + 100) {
3565            driver
3566                .ingress(Bytes::from(data_bytes(
3567                    seq,
3568                    ts,
3569                    &[u8::try_from(seq).unwrap()],
3570                )))
3571                .expect("ingress");
3572            assert!(
3573                driver.staged.len() <= usize::try_from(WINDOW).unwrap(),
3574                "staged grew to {} past a gap (window {WINDOW})",
3575                driver.staged.len()
3576            );
3577        }
3578        drain_deliveries(&mut rx);
3579    }
3580
3581    // -----------------------------------------------------------------------
3582    // Item 3 — bound listener pending state
3583    // -----------------------------------------------------------------------
3584
3585    #[tokio::test]
3586    async fn listener_pending_is_capped_under_a_source_flood() {
3587        let mut listener = test_core(HandshakeConfig::default()).await;
3588
3589        for i in 0..5000u32 {
3590            let src = std::net::SocketAddr::from(([198, 18, (i >> 8) as u8, i as u8], 40_000));
3591            let _ = listener.handle_datagram(src, &induction_bytes(i));
3592        }
3593
3594        assert!(
3595            listener.pending.len() <= 1024,
3596            "pending grew to {} — must be capped at MAX_PENDING",
3597            listener.pending.len()
3598        );
3599    }
3600
3601    #[tokio::test]
3602    async fn pending_entries_expire_while_other_sources_keep_sending() {
3603        let config = HandshakeConfig {
3604            retransmit_after_ticks: 1,
3605            max_retries: 2,
3606            ..HandshakeConfig::default()
3607        };
3608        let mut listener = test_core(config).await;
3609
3610        let stalling_src = std::net::SocketAddr::from(([203, 0, 113, 1], 1234));
3611        listener
3612            .handle_datagram(stalling_src, &induction_bytes(7))
3613            .expect("first induction");
3614
3615        // Continuous traffic from *other* sources must not keep the stalling
3616        // entry alive: the timer-driven tick expires it.
3617        for i in 0..10u32 {
3618            let src = std::net::SocketAddr::from(([198, 51, (i >> 8) as u8, i as u8], 40_000));
3619            let _ = listener.handle_datagram(src, &induction_bytes(100 + i));
3620            listener.tick_pending();
3621        }
3622
3623        assert!(
3624            !listener.pending.contains_key(&stalling_src),
3625            "a stalled handshake must expire even under continuous traffic"
3626        );
3627    }
3628
3629    // -----------------------------------------------------------------------
3630    // Item 2 (BLOCKER) — dropping an accepted socket must not leak its route
3631    // -----------------------------------------------------------------------
3632
3633    /// Pre-fix, `Driver::run`'s route-table cleanup sat at the tail of its
3634    /// `loop`, reached only on a *normal* exit — `SrtSocket::Drop` instead
3635    /// calls `handle.abort()`, which cancels the task at its next await point
3636    /// and drops its future (the `Driver` included) without ever running
3637    /// that inline code. The entry then sat in `routes` forever: a harmless
3638    /// no-op for the new ID-keyed demux's correctness (a stale entry's key is
3639    /// a dead Socket ID no live peer packet names), but an unbounded
3640    /// per-listener memory leak across repeated accept/drop cycles.
3641    /// `RouteCleanup`'s `Drop` impl runs on both an abort and a normal
3642    /// return, since it fires whenever the guard itself — owned by the
3643    /// `Driver`, and so by the task's future — is dropped.
3644    #[tokio::test]
3645    async fn dropping_an_accepted_socket_removes_its_route_entry() {
3646        let mut listener = SrtListener::bind("127.0.0.1:0", HandshakeConfig::default())
3647            .await
3648            .expect("bind");
3649        let listener_addr = listener.local_addr().expect("local addr");
3650
3651        let accept_jh = tokio::spawn(async move {
3652            let s = listener.accept().await.expect("accept");
3653            (listener, s)
3654        });
3655        let caller = SrtSocket::connect(listener_addr, HandshakeConfig::default())
3656            .await
3657            .expect("connect");
3658        let (listener, accepted) = accept_jh.await.expect("join accept");
3659
3660        assert_eq!(
3661            lock(&listener.routes).len(),
3662            1,
3663            "the freshly accepted connection must have registered exactly one route"
3664        );
3665
3666        drop(accepted); // SrtSocket::Drop aborts the driver task.
3667        drop(caller);
3668
3669        // The abort is not synchronous with `drop` — the aborted task's
3670        // `Drop` impls (including `RouteCleanup`) run at the task's own next
3671        // poll. Yield to the (current-thread) runtime until it has had that
3672        // poll; no wall-clock sleep, bounded by an iteration count.
3673        let mut cleaned = false;
3674        for _ in 0..1_000 {
3675            tokio::task::yield_now().await;
3676            if lock(&listener.routes).is_empty() {
3677                cleaned = true;
3678                break;
3679            }
3680        }
3681        assert!(
3682            cleaned,
3683            "route table still has {} entries after the accepted socket was \
3684             dropped — the route leaked (pre-fix: `Driver::run`'s cleanup only \
3685             ran on a normal loop exit, never on `SrtSocket::Drop`'s task abort)",
3686            lock(&listener.routes).len()
3687        );
3688    }
3689
3690    // -----------------------------------------------------------------------
3691    // r08-SRT-W6 — liveness: keep-alive, idle timeout, bounded send buffer
3692    // -----------------------------------------------------------------------
3693
3694    fn control_kinds(driver: &Driver) -> Vec<&'static str> {
3695        driver
3696            .outbound_control
3697            .iter()
3698            .map(|b| match ControlPacket::parse(b).expect("control packet") {
3699                ControlPacket::KeepAlive(_) => "keepalive",
3700                ControlPacket::Ack(_) => "ack",
3701                ControlPacket::Nak(_) => "nak",
3702                ControlPacket::AckAck(_) => "ackack",
3703                _ => "other",
3704            })
3705            .collect()
3706    }
3707
3708    fn keepalive_bytes() -> Vec<u8> {
3709        let ka = ControlPacket::KeepAlive(KeepAlivePacket {
3710            timestamp: 0,
3711            dest_socket_id: 1,
3712            libsrt_pad: true,
3713        });
3714        let mut buf = alloc::vec![0u8; ka.serialized_len()];
3715        ka.serialize_into(&mut buf).expect("serialize keepalive");
3716        buf
3717    }
3718
3719    /// A connection that has sent nothing for [`KEEPALIVE_PERIOD`] (§3.2.3:
3720    /// one second) queues a Keep-Alive — not a millisecond earlier — and the
3721    /// timer restarts from the last packet actually sent.
3722    #[tokio::test(start_paused = true)]
3723    async fn an_idle_connection_sends_a_keepalive_after_one_second() {
3724        let (mut driver, _rx) = test_driver(8192).await;
3725        // A loopback address accepts the real `send_to` in `flush_outbound`.
3726        driver.peer_addr = "127.0.0.1:1".parse().unwrap();
3727
3728        tokio::time::advance(KEEPALIVE_PERIOD - Duration::from_millis(1)).await;
3729        driver.tick_engines();
3730        assert!(
3731            !control_kinds(&driver).contains(&"keepalive"),
3732            "no Keep-Alive before a full idle second: {:?}",
3733            control_kinds(&driver)
3734        );
3735        driver.outbound_control.clear();
3736
3737        tokio::time::advance(Duration::from_millis(1)).await;
3738        driver.tick_engines();
3739        assert_eq!(
3740            control_kinds(&driver)
3741                .iter()
3742                .filter(|k| **k == "keepalive")
3743                .count(),
3744            1,
3745            "exactly one Keep-Alive once the second has elapsed: {:?}",
3746            control_kinds(&driver)
3747        );
3748        let ka = driver
3749            .outbound_control
3750            .iter()
3751            .find_map(|b| match ControlPacket::parse(b) {
3752                Ok(ControlPacket::KeepAlive(ka)) => Some(ka),
3753                _ => None,
3754            })
3755            .expect("keepalive");
3756        assert_eq!(ka.dest_socket_id, 1, "addressed to the peer's socket id");
3757
3758        // Sending it restarts the idle clock: half a second later, no more.
3759        driver.flush_outbound().await.expect("flush");
3760        tokio::time::advance(KEEPALIVE_PERIOD / 2).await;
3761        driver.tick_engines();
3762        assert!(!control_kinds(&driver).contains(&"keepalive"));
3763    }
3764
3765    /// Traffic in *either* direction counts: a connection that is sending data
3766    /// is not idle, so no Keep-Alive is added on top.
3767    #[tokio::test(start_paused = true)]
3768    async fn queued_data_suppresses_the_keepalive() {
3769        let (mut driver, _rx) = test_driver(8192).await;
3770        tokio::time::advance(KEEPALIVE_PERIOD).await;
3771        driver.send_one(b"payload");
3772        driver.tick_engines();
3773        assert!(!control_kinds(&driver).contains(&"keepalive"));
3774    }
3775
3776    /// A received Keep-Alive only proves the peer is alive: it is not
3777    /// answered. (It used to be echoed; with each side now sending its own
3778    /// Keep-Alives, two adapters would bounce one back and forth forever.)
3779    #[tokio::test(start_paused = true)]
3780    async fn a_received_keepalive_is_not_answered() {
3781        let (mut driver, _rx) = test_driver(8192).await;
3782        driver
3783            .ingress(Bytes::from(keepalive_bytes()))
3784            .expect("ingress");
3785        assert!(
3786            driver.outbound_control.is_empty(),
3787            "a Keep-Alive must not be echoed: {:?}",
3788            control_kinds(&driver)
3789        );
3790        assert!(!driver.peer_shutdown);
3791    }
3792
3793    /// Five silent seconds (any packet resets it) end the connection.
3794    #[tokio::test(start_paused = true)]
3795    async fn the_peer_idle_timeout_is_five_silent_seconds() {
3796        let (mut driver, _rx) = test_driver(8192).await;
3797        // The default (libsrt's SRTO_PEERIDLETIMEO) is five seconds.
3798        const PEER_IDLE_TIMEOUT: Duration = Duration::from_secs(5);
3799        assert_eq!(IoConfig::default().read_idle, PEER_IDLE_TIMEOUT);
3800        tokio::time::advance(PEER_IDLE_TIMEOUT - Duration::from_millis(1)).await;
3801        assert!(!driver.peer_idle(Instant::now()));
3802        tokio::time::advance(Duration::from_millis(1)).await;
3803        assert!(driver.peer_idle(Instant::now()));
3804
3805        // Any datagram from the peer — even a Keep-Alive — resets it.
3806        driver
3807            .ingress(Bytes::from(keepalive_bytes()))
3808            .expect("ingress");
3809        assert!(!driver.peer_idle(Instant::now()));
3810        tokio::time::advance(PEER_IDLE_TIMEOUT - Duration::from_millis(1)).await;
3811        assert!(!driver.peer_idle(Instant::now()));
3812    }
3813
3814    /// The sender never holds more than a flow window of unacknowledged
3815    /// packets: the window closes when full and reopens when an ACK frees it.
3816    #[tokio::test]
3817    async fn the_send_window_closes_when_a_full_window_is_unacknowledged() {
3818        const WINDOW: u32 = 8;
3819        let (mut driver, _rx) = test_driver(WINDOW).await;
3820        for sent in 0..WINDOW {
3821            assert!(driver.send_window_open(), "open after {sent} sends");
3822            driver.send_one(b"x");
3823        }
3824        assert!(!driver.send_window_open(), "a full window closes it");
3825
3826        let ack = ControlPacket::Ack(AckPacket {
3827            ack_number: 0,
3828            timestamp: 0,
3829            dest_socket_id: 1,
3830            cif: AckCif::Light {
3831                last_ack_seq: driver.next_send_seq,
3832            },
3833        });
3834        let mut ack_bytes = alloc::vec![0u8; ack.serialized_len()];
3835        ack.serialize_into(&mut ack_bytes).expect("serialize ack");
3836        driver.ingress(Bytes::from(ack_bytes)).expect("ingress ack");
3837        assert!(driver.send_window_open(), "the ACK freed the window");
3838    }
3839
3840    /// `Driver::run` honours the window: with a peer that never acknowledges
3841    /// anything, only one flow window of the application's payloads is ever
3842    /// taken off the hand-off channel; the rest wait in it (where
3843    /// `SrtSocket::send` would block) instead of growing the send buffer.
3844    #[tokio::test(start_paused = true)]
3845    async fn run_stops_taking_app_payloads_once_the_window_is_full() {
3846        const WINDOW: u32 = 8;
3847        const QUEUED: usize = 24;
3848        let (mut driver, _rx, _datagrams) = test_driver_with_ingress(WINDOW).await;
3849        driver.peer_addr = "127.0.0.1:1".parse().unwrap();
3850        let (app_tx, app_rx) = mpsc::channel::<Bytes>(SEND_CHANNEL_CAPACITY);
3851        for _ in 0..QUEUED {
3852            app_tx
3853                .try_send(Bytes::from(alloc::vec![0u8; 100]))
3854                .expect("queue payload");
3855        }
3856        let handle = tokio::spawn(driver.run(app_rx));
3857        // Well inside the idle timeout, step the driver's clock a while.
3858        for _ in 0..50 {
3859            tokio::time::advance(Duration::from_millis(10)).await;
3860            tokio::task::yield_now().await;
3861        }
3862        let still_queued = app_tx.max_capacity() - app_tx.capacity();
3863        assert_eq!(
3864            still_queued,
3865            QUEUED - usize::try_from(WINDOW).unwrap(),
3866            "the driver must stop draining at one flow window"
3867        );
3868        handle.abort();
3869    }
3870
3871    // -----------------------------------------------------------------------
3872    // r08-SRT-W12 — typed errors
3873    // -----------------------------------------------------------------------
3874
3875    /// A datagram that is not an SRT packet is reported with its stage and
3876    /// the underlying codec error, not flattened to a generic invalid field.
3877    #[tokio::test]
3878    async fn listener_parse_failure_keeps_its_stage_and_cause() {
3879        let mut listener = test_core(HandshakeConfig::default()).await;
3880        let err = listener
3881            .handle_datagram(peer_addr(), &[0u8; 4])
3882            .expect_err("a 4-byte datagram is not an SRT packet");
3883        let Error::Handshake { stage, source } = err else {
3884            panic!("expected Error::Handshake, got {err:?}");
3885        };
3886        assert_eq!(stage, "parse");
3887        assert!(
3888            matches!(*source, Error::BufferTooShort { have: 4, .. }),
3889            "the cause must be preserved, got {source:?}"
3890        );
3891    }
3892
3893    /// A rejection the engine produces surfaces as `Error::Rejected` with the
3894    /// reason — a feed after the handshake already finished is the engine's
3895    /// own out-of-sequence error, wrapped with its stage.
3896    #[tokio::test]
3897    async fn listener_feed_failure_is_wrapped_with_the_engine_error() {
3898        let mut listener = test_core(HandshakeConfig::default()).await;
3899        // A CONCLUSION as the very first packet from a source: the fresh
3900        // engine expects an INDUCTION.
3901        let conclusion = {
3902            let hp = HandshakePacket {
3903                timestamp: 0,
3904                dest_socket_id: 0,
3905                version: crate::handshake_sm::HANDSHAKE_VERSION_5,
3906                encryption_field: crate::packet::EncryptionField::NoEncryption,
3907                extension_field: HandshakeExtensionFlags(0),
3908                initial_seq_number: 0,
3909                mtu: 1500,
3910                max_flow_window_size: 8192,
3911                handshake_type: crate::packet::HandshakeType::Conclusion,
3912                srt_socket_id: 5,
3913                syn_cookie: 0,
3914                peer_ip: [0; 4],
3915                extensions: HandshakeExtensions(&[]),
3916            };
3917            let pkt = ControlPacket::Handshake(hp);
3918            let mut buf = alloc::vec![0u8; pkt.serialized_len()];
3919            pkt.serialize_into(&mut buf).unwrap();
3920            buf
3921        };
3922        let err = listener
3923            .handle_datagram(peer_addr(), &conclusion)
3924            .expect_err("a CONCLUSION before an INDUCTION");
3925        let Error::Handshake { stage, source } = err else {
3926            panic!("expected Error::Handshake, got {err:?}");
3927        };
3928        assert_eq!(stage, "listener feed");
3929        assert!(matches!(*source, Error::HandshakeOutOfSequence { .. }));
3930    }
3931
3932    // -----------------------------------------------------------------------
3933    // #1134 — a poisoned lock must not cascade
3934    // -----------------------------------------------------------------------
3935
3936    /// A connection task that panics while holding the route table's lock
3937    /// poisons it. Dropping a `RouteCleanup` (it runs in `Drop`, including
3938    /// while unwinding) and the routing pump's lookups must keep working, not
3939    /// panic a second time.
3940    #[test]
3941    fn a_poisoned_route_table_does_not_panic_the_cleanup_guard() {
3942        let routes: RouteTable = Arc::new(Mutex::new(std::collections::HashMap::new()));
3943        {
3944            let routes = Arc::clone(&routes);
3945            let panicked = std::thread::spawn(move || {
3946                let _held = routes.lock().expect("lock");
3947                panic!("a connection task panicked holding the route table lock");
3948            })
3949            .join();
3950            assert!(panicked.is_err());
3951        }
3952        assert!(routes.is_poisoned(), "the lock must really be poisoned");
3953
3954        let (tx, _rx) = mpsc::channel(1);
3955        lock(&routes).insert(
3956            7,
3957            RouteEntry {
3958                addr: peer_addr(),
3959                tx,
3960                stats: Arc::new(Counters::default()),
3961            },
3962        );
3963        assert_eq!(lock(&routes).len(), 1);
3964        drop(RouteCleanup(Some((7, Arc::clone(&routes)))));
3965        assert!(
3966            lock(&routes).is_empty(),
3967            "the guard must still remove its entry"
3968        );
3969    }
3970
3971    // -----------------------------------------------------------------------
3972    // r08-SRT-W9 — the time base is seeded from the handshake
3973    // -----------------------------------------------------------------------
3974
3975    /// `TsbpdTimeBase = T_NOW - HSREQ_TIMESTAMP` with `T_NOW = 0` at the
3976    /// epoch is minus the peer's handshake timestamp (rule 12).
3977    #[test]
3978    fn the_time_base_is_minus_the_peer_handshake_timestamp() {
3979        assert_eq!(tsbpd_time_base_from(0), 0);
3980        assert_eq!(tsbpd_time_base_from(3_000_000), -3_000_000);
3981        assert_eq!(tsbpd_time_base_from(u32::MAX), -i64::from(u32::MAX));
3982    }
3983
3984    /// A peer whose clock already reads 30 s when the handshake completes
3985    /// (its first data packet carries `Timestamp` ~30 s) is delivered one
3986    /// latency after arrival — not 30 s later, which is what a hard-coded
3987    /// zero base did (the packet's play time was `0 + 30 s + latency`).
3988    #[tokio::test(start_paused = true)]
3989    async fn a_peer_far_into_its_own_clock_is_not_delayed_by_its_timestamp() {
3990        const PEER_CLOCK_US: u32 = 30_000_000;
3991        let udp = Arc::new(UdpSocket::bind("127.0.0.1:0").await.unwrap());
3992        let (deliver, mut rx) = mpsc::channel(DELIVER_CHANNEL_CAPACITY);
3993        let (_datagram_tx, datagram_rx) = mpsc::channel(RX_CHANNEL_CAPACITY);
3994        let mut driver = Driver::new(
3995            ConnParams {
3996                udp,
3997                peer_addr: peer_addr(),
3998                rx: datagram_rx,
3999                stats: Arc::new(Counters::default()),
4000                route_cleanup: RouteCleanup(None),
4001                forwarder_guard: TaskGuard(None),
4002                life: None,
4003                read_idle: IoConfig::default().read_idle,
4004                write: IoConfig::default().write,
4005                our_initial_seq: 0,
4006                peer_initial_seq: 0,
4007                peer_socket_id: 1,
4008                tsbpd_time_base: tsbpd_time_base_from(PEER_CLOCK_US),
4009                tsbpd_delay_ms: LATENCY_MS,
4010                epoch: Instant::now(),
4011                max_flow_window: 8192,
4012                mtu: 1500,
4013                tlpkt_drop: true,
4014            },
4015            deliver,
4016        );
4017        driver
4018            .ingress(Bytes::from(data_bytes(0, PEER_CLOCK_US, b"first")))
4019            .expect("ingress");
4020        assert!(drain_deliveries(&mut rx).is_empty(), "not due on arrival");
4021        tokio::time::advance(Duration::from_millis(LATENCY_MS)).await;
4022        driver.tick_engines();
4023        assert_eq!(
4024            drain_deliveries(&mut rx),
4025            vec![b"first".to_vec()],
4026            "delivered one latency after arrival"
4027        );
4028    }
4029
4030    // -----------------------------------------------------------------------
4031    // Pacing schedule (issue #1061), deterministically
4032    // -----------------------------------------------------------------------
4033
4034    /// Under a paused clock the token-bucket schedule is exact: the first DATA
4035    /// packet goes at once, the next not a nanosecond before one pacing period
4036    /// later, and a burst after an idle gap is not penalized (it sends
4037    /// immediately, then resumes the period).
4038    #[tokio::test(start_paused = true)]
4039    async fn data_leaves_one_packet_per_pacing_period() {
4040        let (mut driver, _rx) = test_driver(8192).await;
4041        driver.peer_addr = "127.0.0.1:1".parse().unwrap();
4042        const BACKLOG: usize = 60;
4043        for _ in 0..BACKLOG {
4044            driver.send_one(&[0u8; 1316]);
4045        }
4046        let period = driver.livecc.on_ack_received();
4047        assert!(period > Duration::ZERO, "the default MAX_BW paces DATA");
4048
4049        driver.flush_outbound().await.expect("flush");
4050        assert_eq!(
4051            driver.outbound_data.len(),
4052            BACKLOG - 1,
4053            "the first packet goes at once"
4054        );
4055
4056        tokio::time::advance(period - Duration::from_nanos(1)).await;
4057        driver.flush_outbound().await.expect("flush");
4058        assert_eq!(
4059            driver.outbound_data.len(),
4060            BACKLOG - 1,
4061            "one nanosecond short of the slot"
4062        );
4063
4064        tokio::time::advance(Duration::from_nanos(1)).await;
4065        driver.flush_outbound().await.expect("flush");
4066        assert_eq!(
4067            driver.outbound_data.len(),
4068            BACKLOG - 2,
4069            "the slot arrived: one more"
4070        );
4071
4072        // A long stall does not let the backlog out in one burst: the late
4073        // wake claims at most `PACING_BURST_CAP` packets of catch-up (it used
4074        // to send exactly one and lose the rest of the credit).
4075        tokio::time::advance(period * 100).await;
4076        let before = driver.outbound_data.len();
4077        driver.flush_outbound().await.expect("flush");
4078        let sent = before - driver.outbound_data.len();
4079        assert_eq!(
4080            sent, PACING_BURST_CAP,
4081            "a stalled wake must send exactly the burst cap"
4082        );
4083        assert!(!driver.outbound_data.is_empty());
4084        assert!(driver.next_paced_send_wait().is_some());
4085    }
4086
4087    /// r08-SRT-O2: a retransmission feeds LiveCC the packet's *payload* length
4088    /// (the datagram less its fixed header), exactly as a first transmission
4089    /// does — read from the length instead of re-parsing the packet.
4090    #[tokio::test(start_paused = true)]
4091    async fn a_retransmission_is_accounted_by_its_payload_length() {
4092        use crate::packet::nak::build_loss_list;
4093        use crate::packet::{LossListEntry, NakPacket};
4094        let (mut driver, _rx) = test_driver(8192).await;
4095        driver.send_one(&[0u8; 1000]); // seq 0
4096        let raw = build_loss_list(&[LossListEntry::Single(0)]).expect("loss list");
4097        let nak = ControlPacket::Nak(NakPacket {
4098            timestamp: 0,
4099            dest_socket_id: 1,
4100            raw_loss_list: &raw,
4101        });
4102        let mut bytes = alloc::vec![0u8; nak.serialized_len()];
4103        nak.serialize_into(&mut bytes).expect("serialize nak");
4104        driver.ingress(Bytes::from(bytes)).expect("ingress nak");
4105        driver.tick_engines();
4106        assert_eq!(
4107            driver.outbound_data.len(),
4108            2,
4109            "the packet and its retransmit"
4110        );
4111
4112        // The reference sees two 1000-byte payloads; a header-inclusive length
4113        // (1016) would leave the average two bytes higher.
4114        let mut reference = LiveCC::new(DEFAULT_MAX_BW);
4115        reference.on_data_packet(1000);
4116        reference.on_data_packet(1000);
4117        assert_eq!(
4118            driver.livecc.avg_payload_size(),
4119            reference.avg_payload_size()
4120        );
4121    }
4122
4123    /// When the application handle is gone and the driver ends cooperatively
4124    /// (not by abort), it still tells the peer it is leaving (§3.2.7). (Real
4125    /// clock, bounded real waits: a paused clock would auto-advance past the
4126    /// `recv` timeout before the loopback datagram is delivered.)
4127    #[tokio::test]
4128    async fn a_driver_ending_because_its_handle_is_gone_sends_shutdown() {
4129        let peer = UdpSocket::bind("127.0.0.1:0").await.unwrap();
4130        let (mut driver, _rx, _datagrams) = test_driver_with_ingress(8192).await;
4131        driver.peer_addr = peer.local_addr().unwrap();
4132        let (app_tx, app_rx) = mpsc::channel::<Bytes>(SEND_CHANNEL_CAPACITY);
4133        let handle = tokio::spawn(driver.run(app_rx));
4134        drop(app_tx);
4135        tokio::time::timeout(Duration::from_secs(5), handle)
4136            .await
4137            .expect("the driver must end once its handle is gone")
4138            .expect("join");
4139
4140        let mut buf = [0u8; 2048];
4141        let shutdown = loop {
4142            let n = tokio::time::timeout(Duration::from_secs(5), peer.recv(&mut buf))
4143                .await
4144                .expect("no SHUTDOWN reached the peer")
4145                .expect("recv");
4146            if let Ok(SrtPacket::Control(ControlPacket::Shutdown(s))) = SrtPacket::parse(&buf[..n])
4147            {
4148                break s;
4149            }
4150        };
4151        assert_eq!(
4152            shutdown.dest_socket_id, 1,
4153            "addressed to the peer's socket id"
4154        );
4155    }
4156
4157    /// A hostile `retransmit_after_ticks` must not make the handshake timer's
4158    /// period zero (which would panic the connect).
4159    #[tokio::test]
4160    async fn an_absurd_retransmit_tick_count_does_not_panic_the_connect() {
4161        let silent = UdpSocket::bind("127.0.0.1:0").await.unwrap();
4162        for ticks in [0, 1, u32::MAX] {
4163            let config = HandshakeConfig {
4164                retransmit_after_ticks: ticks,
4165                ..HandshakeConfig::default()
4166            };
4167            // Nobody answers; the point is only that it neither panics nor
4168            // fails immediately.
4169            let outcome = tokio::time::timeout(
4170                Duration::from_millis(150),
4171                SrtSocket::connect(silent.local_addr().unwrap(), config),
4172            )
4173            .await;
4174            assert!(
4175                outcome.is_err(),
4176                "ticks={ticks}: still waiting for the peer"
4177            );
4178        }
4179    }
4180
4181    // -----------------------------------------------------------------------
4182    // Stale sequence numbers, and the negotiated TLPKTDROP flag
4183    // -----------------------------------------------------------------------
4184
4185    /// Packets behind the delivery cursor are never staged: with the cursor at
4186    /// 3, a hundred thousand distinct stale sequence numbers (each stamped
4187    /// with a far-future timestamp, so TSBPD would hold them) leave `staged`
4188    /// empty and are counted as late. They used to be staged, ignored by
4189    /// TSBPD and never removed.
4190    #[tokio::test(start_paused = true)]
4191    async fn stale_sequence_numbers_are_never_staged() {
4192        let (mut driver, mut rx) = test_driver(8192).await;
4193        for seq in 0..3u32 {
4194            driver
4195                .ingress(Bytes::from(data_bytes(
4196                    seq,
4197                    0,
4198                    &[u8::try_from(seq).unwrap()],
4199                )))
4200                .expect("ingress");
4201        }
4202        tokio::time::advance(Duration::from_millis(130)).await;
4203        driver.tick_engines();
4204        assert_eq!(drain_deliveries(&mut rx).len(), 3);
4205        assert_eq!(driver.tsbpd.next_release(), 3);
4206
4207        const STALE: u32 = 100_000;
4208        for back in 1..=STALE {
4209            // 2^31 - back is `back` behind the cursor at 0..3 in circular order.
4210            let seq = (1u32 << 31) - back;
4211            driver
4212                .ingress(Bytes::from(data_bytes(seq, u32::MAX, b"x")))
4213                .expect("ingress");
4214        }
4215        assert!(
4216            driver.staged.is_empty(),
4217            "{} stale packets staged",
4218            driver.staged.len()
4219        );
4220        assert_eq!(
4221            driver.stats.late_dropped.load(Ordering::Relaxed),
4222            u64::from(STALE)
4223        );
4224        // A duplicate of something already delivered is late too.
4225        driver
4226            .ingress(Bytes::from(data_bytes(1, 0, b"dup")))
4227            .expect("ingress");
4228        assert!(driver.staged.is_empty());
4229    }
4230
4231    /// Without a negotiated TLPKTDROP the receiver never skips a gap: it waits
4232    /// for the retransmission, delivers nothing past the hole however long it
4233    /// takes, and never moves its ack point past it (which would tell the
4234    /// sender a packet that never arrived was received).
4235    #[tokio::test(start_paused = true)]
4236    async fn without_negotiated_tlpktdrop_a_gap_is_waited_out_not_skipped() {
4237        let (mut driver, mut rx) = test_driver(8192).await;
4238        driver.tsbpd = TsbpdScheduler::new(0, 0, LATENCY_MS, DEFAULT_DRIFT_US, false, None);
4239        for seq in [0u32, 2, 3] {
4240            driver
4241                .ingress(Bytes::from(data_bytes(
4242                    seq,
4243                    0,
4244                    &[u8::try_from(seq).unwrap()],
4245                )))
4246                .expect("ingress");
4247        }
4248        // Far beyond the latency (and the too-late threshold).
4249        for _ in 0..50 {
4250            tokio::time::advance(Duration::from_millis(100)).await;
4251            driver.tick_engines();
4252        }
4253        let delivered = drain_deliveries(&mut rx);
4254        assert_eq!(
4255            delivered.iter().map(|p| p[0]).collect::<Vec<_>>(),
4256            vec![0],
4257            "nothing may pass the hole"
4258        );
4259        assert_eq!(driver.receiver.ack_point(), 1, "never ACK past a gap");
4260        assert_eq!(driver.receiver.loss_list_len(), 1, "still asking for seq 1");
4261
4262        // The retransmission arrives: everything flows, in order.
4263        driver
4264            .ingress(Bytes::from(data_bytes(1, 0, &[1])))
4265            .expect("ingress");
4266        driver.tick_engines();
4267        let delivered = drain_deliveries(&mut rx);
4268        assert_eq!(
4269            delivered.iter().map(|p| p[0]).collect::<Vec<_>>(),
4270            vec![1, 2, 3]
4271        );
4272        assert_eq!(driver.receiver.ack_point(), 4);
4273    }
4274
4275    /// The negotiated flag, not a constant, decides: a connection negotiated
4276    /// with TLPKTDROP skips (the existing live-mode tests), one without does
4277    /// not — pinned through `Driver::new`'s own configuration.
4278    #[tokio::test]
4279    async fn the_driver_honours_the_negotiated_tlpktdrop_flag() {
4280        for negotiated in [true, false] {
4281            let udp = Arc::new(UdpSocket::bind("127.0.0.1:0").await.unwrap());
4282            let (deliver, _rx) = mpsc::channel(1);
4283            let (_tx, datagram_rx) = mpsc::channel(1);
4284            let driver = Driver::new(
4285                ConnParams {
4286                    udp,
4287                    peer_addr: peer_addr(),
4288                    rx: datagram_rx,
4289                    stats: Arc::new(Counters::default()),
4290                    route_cleanup: RouteCleanup(None),
4291                    forwarder_guard: TaskGuard(None),
4292                    life: None,
4293                    read_idle: IoConfig::default().read_idle,
4294                    write: IoConfig::default().write,
4295                    our_initial_seq: 0,
4296                    peer_initial_seq: 0,
4297                    peer_socket_id: 1,
4298                    tsbpd_time_base: 0,
4299                    tsbpd_delay_ms: LATENCY_MS,
4300                    epoch: Instant::now(),
4301                    max_flow_window: 8192,
4302                    mtu: 1500,
4303                    tlpkt_drop: negotiated,
4304                },
4305                deliver,
4306            );
4307            assert_eq!(driver.tsbpd.tlpktdrop_enabled(), negotiated);
4308        }
4309    }
4310
4311    // -----------------------------------------------------------------------
4312    // #1142 / O5 — the cookie key is secret, 128 bits, and rotates
4313    // -----------------------------------------------------------------------
4314
4315    /// `{:?}` of a listener (and of its key holder) never prints the cookie
4316    /// key, in decimal or hex.
4317    #[tokio::test]
4318    async fn listener_debug_never_prints_the_cookie_key() {
4319        let listener = test_core(HandshakeConfig::default()).await;
4320        let key = listener.cookie_keys.current();
4321        assert!(
4322            key > u128::from(u64::MAX),
4323            "a 128-bit key, not a 64-bit one"
4324        );
4325        for dump in [
4326            alloc::format!("{listener:?}"),
4327            alloc::format!("{listener:#?}"),
4328            alloc::format!("{listener:x?}"),
4329        ] {
4330            for needle in [
4331                alloc::format!("{key}"),
4332                alloc::format!("{key:x}"),
4333                alloc::format!("{:x}", key >> 64),
4334            ] {
4335                assert!(!dump.contains(&needle), "key leaked as {needle:?}: {dump}");
4336            }
4337            assert!(dump.contains("redacted"), "{dump}");
4338        }
4339    }
4340
4341    fn induction_cookie(listener: &mut ListenerCore, src: std::net::SocketAddr) -> u32 {
4342        listener
4343            .handle_datagram(src, &induction_bytes(7))
4344            .expect("induction");
4345        let response = listener
4346            .outbound_queue
4347            .get_mut(&src)
4348            .and_then(VecDeque::pop_back)
4349            .expect("an INDUCTION response");
4350        match SrtPacket::parse(&response).expect("parse") {
4351            SrtPacket::Control(ControlPacket::Handshake(hp)) => hp.syn_cookie,
4352            other => panic!("expected a handshake, got {other:?}"),
4353        }
4354    }
4355
4356    /// The key is replaced exactly once a minute is up; cookies issued after
4357    /// differ from those before for the same peer.
4358    #[tokio::test]
4359    async fn the_cookie_key_rotates_every_minute() {
4360        let mut listener = test_core(HandshakeConfig::default()).await;
4361        let t0 = listener.cookie_keys.drawn_at;
4362        let first = listener.cookie_keys.current();
4363
4364        assert!(
4365            !listener
4366                .cookie_keys
4367                .rotate_if_due(t0 + COOKIE_KEY_ROTATION - Duration::from_millis(1))
4368        );
4369        assert_eq!(listener.cookie_keys.current(), first, "not yet due");
4370
4371        let src = peer_addr();
4372        let before = induction_cookie(&mut listener, src);
4373        listener.pending.clear();
4374        assert!(listener.cookie_keys.rotate_if_due(t0 + COOKIE_KEY_ROTATION));
4375        assert_ne!(
4376            listener.cookie_keys.current(),
4377            first,
4378            "a fresh key was drawn"
4379        );
4380        assert_eq!(
4381            listener.cookie_keys.drawn_at,
4382            t0 + COOKIE_KEY_ROTATION,
4383            "the next rotation is measured from this one"
4384        );
4385        let after = induction_cookie(&mut listener, src);
4386        assert_ne!(
4387            before, after,
4388            "the same peer gets a different cookie after rotation"
4389        );
4390    }
4391
4392    /// A handshake begun under the previous key still completes after the key
4393    /// rotates: its pending entry keeps the cookie it was issued.
4394    #[tokio::test]
4395    async fn a_handshake_begun_before_a_rotation_still_completes() {
4396        use crate::caller::CallerHandshake;
4397        let mut listener = test_core(HandshakeConfig::default()).await;
4398        let src = peer_addr();
4399        let mut caller = CallerHandshake::new(0x0000_0777, HandshakeConfig::default());
4400        let induction = caller.start().expect("start");
4401        listener
4402            .handle_datagram(src, &induction)
4403            .expect("induction");
4404        let response = listener
4405            .outbound_queue
4406            .get_mut(&src)
4407            .and_then(VecDeque::pop_back)
4408            .expect("response");
4409
4410        let t0 = listener.cookie_keys.drawn_at;
4411        assert!(listener.cookie_keys.rotate_if_due(t0 + COOKIE_KEY_ROTATION));
4412
4413        let conclusion = caller
4414            .feed_bytes(&response)
4415            .expect("feed")
4416            .into_iter()
4417            .find_map(|o| match o {
4418                HandshakeOutput::Send(b) => Some(b),
4419                _ => None,
4420            })
4421            .expect("CONCLUSION");
4422        listener
4423            .handle_datagram(src, &conclusion)
4424            .expect("the CONCLUSION must be accepted across the rotation");
4425        assert!(
4426            listener.pending[&src].params.is_some(),
4427            "the handshake must have completed"
4428        );
4429        // The connection epoch is when the CONCLUSION arrived, and a repeat
4430        // does not move it.
4431        let concluded = listener.pending[&src].concluded_at.expect("recorded");
4432        listener
4433            .handle_datagram(src, &conclusion)
4434            .expect("a repeated CONCLUSION");
4435        assert_eq!(listener.pending[&src].concluded_at, Some(concluded));
4436    }
4437}