Skip to main content

srt_runtime/
io.rs

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