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