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