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