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