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