13 Commits

Author SHA1 Message Date
mnovak f0aac13f12 [fuzz] rustfmt the host targets 2026-12-04 12:46:47 +01:00
mnovak 95380a3b37 [repo] Docs: the accepting side of ENet and the control host (PROTOCOL.md 3.1, 3.3); S-34 stock ENet host-side functions 2026-12-04 12:46:47 +01:00
mnovak db56a5dbb1 [fuzz] enet_host and control_host targets
enet_host: accept on the first datagram or a canned connect (optionally acknowledged), then datagrams, some with our header; asserts outgoing datagrams parse within the MTU and deliveries stay under the cap. control_host: a connected ControlHost fed sealed arbitrary plaintexts, replayed sequence numbers, arbitrary frames in valid commands and raw datagrams; asserts parse_client_message invariants and that no message appears without a sealed frame. 60 s each, 0 crashes.
2026-12-04 12:46:39 +01:00
mnovak e082570a3f [domistream] Control host: ControlHost (client frames opened with replay refusal, typed client messages, host messages, stop deadline)
parse_client_message types START_B, PERIODIC_PING, INPUT_DATA (through input::parse_input), IDR, INVALIDATE_REF_FRAMES, LOSS_STATS and FRAME_STATS (raw bodies) and skips anything else as Unknown. encode_host_message sends rumble, trigger rumble, motion, RGB LED and the extended termination; the plain termination (U10) and HDR_MODE (GPL-provenance layout) stay Unsupported. StopDeadline ends a session without PERIODIC_PING (default 60 s).
2026-12-04 12:46:39 +01:00
mnovak f8bad73121 [domistream] ENet host: EnetHostPeer, the accepting side (verify connect, session ids, reliable channels, pings, timeouts, disconnect)
One peer per client address. CONNECT answered with a reliable VERIFY CONNECT as stock ENet 1.3 does it (session ids picked from the client's offer, MTU, window and channels clamped, throttle echoed); connected once the client acknowledges the verify; reliable, unreliable and unsequenced delivery with fragment reassembly under the existing caps; duplicate unsequenced groups dropped; pings when the client is quiet; retransmission and timeout as the client; disconnect both ways. Shares the client's channel, fragment and in-flight types.
2026-12-04 12:46:39 +01:00
mnovak 58910d00fa [domistream] Control host: tests first (ControlStream against ControlHost, replay, stop deadline), API stubs
Input arrives typed and byte-identical to what the client encoded; host rumble, trigger rumble, LED, motion and termination reach the client; replays, forgeries and malformed messages are dropped; the stop deadline ends a session without PERIODIC_PING. Alloc caps for the host parsers. They fail against the stubs.
2026-12-04 12:46:39 +01:00
mnovak e77c5fcd83 [domistream] ENet host: tests first (client against host over an in-memory lossy wire), API stubs
EnetHostPeer is the accepting side, one peer per client address. The tests drive our EnetClient against it with simulated time, loss, duplication and reordering, plus a scripted client for the stock ENet 1.3 facts (verify connect fields, session ids, what is acknowledged when). They fail against the stubs.
2026-12-04 12:46:39 +01:00
mnovak eae3b9e754 [repo] Merge: feature/host-rtsp-server (RTSP server, DESCRIBE and ANNOUNCE, PR #10) 2026-12-04 12:46:30 +01:00
mnovak fd4285aff0 [domistream] RTSP server: PROTOCOL.md 2.5 (host side, ANNOUNCE required/defaulted table), clean-room sources S-30 to S-32 2026-12-04 12:44:49 +01:00
mnovak a86a689b1f [domistream] RTSP server: session state machine, DESCRIBE writer, strict ANNOUNCE parser, response encoder and request framer; test fixes (escaped CRLF in alloc_caps, CSeq test state, clippy) 2026-12-04 12:44:49 +01:00
mnovak 27b7f2bf1d [fuzz] RTSP server: rtsp_server (session fed arbitrary requests after a valid prefix) and announce targets 2026-12-04 12:44:49 +01:00
mnovak 54bc9f5faf [domistream] RTSP server: tests first (in-memory client/server session, order, Session, ANNOUNCE parser, DESCRIBE writer, caps); API stubs return Unimplemented 2026-12-04 12:44:40 +01:00
mnovak 33b7b90b65 [repo] Merge: feature/host-packetizers (video and audio packetizers, PR #9) 2026-12-04 12:44:34 +01:00
24 changed files with 6261 additions and 12 deletions
+433
View File
@@ -0,0 +1,433 @@
//! The host side of the control stream (`docs/PROTOCOL.md` 3.2, 3.3), over one [`EnetHostPeer`].
//!
//! [`ControlHost`] mirrors the client's [`super::ControlStream`]: it accepts the client's ENet connection, opens
//! every client frame (nonce direction `'C'`, PROTOCOL.md 3.2), drops frames that fail the tag, replay old sequence
//! numbers or hold a malformed message (PROTOCOL.md 3.3: inside the encrypted frame such a message is skipped, never
//! fatal), and reports [`ClientControlMessage`]s. It seals every host message with `'H'` and an increasing sequence
//! number from 0, reliable on channel 0 (PROTOCOL.md 3.1). It also keeps the stop deadline of PROTOCOL.md 3.3:
//! without a `PERIODIC_PING` for the configured time it reports [`ControlHostEvent::PingTimedOut`], and the caller
//! ends the session (termination, then [`ControlHost::close`]).
//!
//! Only control V2 (every message inside the encrypted frame) is spoken: a bare message outside the frame is
//! dropped like any frame that does not open (UNKNOWN U10 asks whether a client ever sends one).
use core::time::Duration;
use std::collections::VecDeque;
use super::frame::{ControlCipher, Direction};
use super::message::{HdrMetadata, HostMessage, MAX_MESSAGE_BYTES, MESSAGE_HEADER_LEN, MessageType, parse_message};
use crate::enet::{Delivery, EnetHostConfig, EnetHostEvent, EnetHostPeer, EnetHostState};
use crate::input::InputEvent;
use crate::{Error, Instant, Result};
/// Stop a session after this long without a `PERIODIC_PING` (PROTOCOL.md 3.3, Moonshine's default).
pub const DEFAULT_STOP_TIMEOUT: Duration = Duration::from_secs(60);
/// The extended termination code for a graceful end (PROTOCOL.md 3.3).
pub const TERMINATION_GRACEFUL: u32 = 0x8003_0023;
/// The channel every host message goes on, reliable (PROTOCOL.md 3.1).
const HOST_CHANNEL: u8 = 0;
/// Settings of the host side of one control stream. `Debug` never prints the key.
#[derive(Clone, PartialEq, Eq)]
pub struct ControlHostConfig {
/// The ENet host-side peer.
pub enet: EnetHostConfig,
/// The session's `rikey`.
pub rikey: [u8; 16],
/// End the session after this long without a `PERIODIC_PING` ([`DEFAULT_STOP_TIMEOUT`] is Moonshine's);
/// `None` never ends it for that.
pub stop_timeout: Option<Duration>,
}
impl core::fmt::Debug for ControlHostConfig {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("ControlHostConfig")
.field("enet", &self.enet)
.field("rikey", &"<redacted>")
.field("stop_timeout", &self.stop_timeout)
.finish()
}
}
/// A message from the client, as the host reads it (PROTOCOL.md 3.3).
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ClientControlMessage {
/// `START_B`: start video and audio. Any body is ignored (PROTOCOL.md 3.3: Moonshine reads none).
StartB,
/// `PERIODIC_PING`: the client is still there. Any body is ignored.
PeriodicPing,
/// `INPUT_DATA` with a known layout (PROTOCOL.md 4).
Input(InputEvent),
/// `INPUT_DATA` that [`crate::input::parse_input`] refused (a layout still UNKNOWN U21, an unknown input type,
/// or a bad size field). Not fatal: the stream goes on.
InputRejected {
/// Body length.
body_len: usize,
/// Why.
error: Error,
},
/// `IDR_FRAME`: send a key frame. Any body is ignored.
IdrRequest,
/// `INVALIDATE_REF_FRAMES`: stop referencing frames `first..=last`. A field the body is too short for reads
/// as 0 (PROTOCOL.md 3.3).
InvalidateRefFrames {
/// First lost frame.
first: u32,
/// Last lost frame.
last: u32,
},
/// `LOSS_STATS`, body kept as it came (layout UNKNOWN U10).
LossStats(Vec<u8>),
/// `FRAME_STATS`, body kept as it came (layout UNKNOWN U10).
FrameStats(Vec<u8>),
/// Any other type, `START_A` among them (PROTOCOL.md 3.3: skipped inside the encrypted frame).
Unknown {
/// Type code.
message_type: u16,
/// Body length.
body_len: usize,
},
}
/// Interprets a decrypted message from the client (PROTOCOL.md 3.3). Only the split is strict; bodies of the
/// messages a host reads nothing from are ignored, input goes through [`crate::input::parse_input`].
///
/// # Errors
/// As [`parse_message`]: [`Error::TooLarge`] over [`MAX_MESSAGE_BYTES`], [`Error::Truncated`] under the 4-byte
/// header, [`Error::Malformed`] when the length field does not match.
pub fn parse_client_message(message: &[u8]) -> Result<ClientControlMessage> {
let raw = parse_message(message)?;
let b = raw.body;
// `first` at body 0..4, `last` at body 8..12, little-endian; missing means 0 (PROTOCOL.md 3.3).
let field = |at: usize| crate::util::u32_le("invalidate ref frames", b, at).unwrap_or(0);
Ok(match raw.message_type {
t if t == MessageType::StartB as u16 => ClientControlMessage::StartB,
t if t == MessageType::PeriodicPing as u16 => ClientControlMessage::PeriodicPing,
t if t == MessageType::IdrFrame as u16 => ClientControlMessage::IdrRequest,
t if t == MessageType::InvalidateRefFrames as u16 => {
ClientControlMessage::InvalidateRefFrames { first: field(0), last: field(8) }
}
t if t == MessageType::LossStats as u16 => ClientControlMessage::LossStats(b.to_vec()),
t if t == MessageType::FrameStats as u16 => ClientControlMessage::FrameStats(b.to_vec()),
t if t == MessageType::InputData as u16 => match crate::input::parse_input(message) {
Ok(e) => ClientControlMessage::Input(e),
Err(error) => ClientControlMessage::InputRejected { body_len: b.len(), error },
},
other => ClientControlMessage::Unknown { message_type: other, body_len: b.len() },
})
}
/// Type, length, body.
fn framed(message_type: MessageType, body: &[u8]) -> Result<Vec<u8>> {
crate::util::cap("host message", MAX_MESSAGE_BYTES, MESSAGE_HEADER_LEN.saturating_add(body.len()))?;
let len = u16::try_from(body.len()).map_err(|_| crate::util::malformed("host message length"))?;
let mut m = Vec::with_capacity(MESSAGE_HEADER_LEN + body.len());
m.extend_from_slice(&(message_type as u16).to_le_bytes());
m.extend_from_slice(&len.to_le_bytes());
m.extend_from_slice(body);
Ok(m)
}
/// Serializes a message to the client (type, length, body), ready for [`ControlCipher::seal`]: the inverse of
/// [`super::parse_host_message`]. Bodies are little-endian (UNKNOWN U23), the extended termination code big-endian
/// (PROTOCOL.md 3.3).
///
/// # Errors
/// [`Error::Unsupported`] for a message whose layout is not known well enough to send: the plain `TERMINATION`
/// (body UNKNOWN U10), `HDR_MODE` (layout of GPL provenance, `[M*]`) and [`HostMessage::Other`].
pub fn encode_host_message(message: &HostMessage) -> Result<Vec<u8>> {
match *message {
HostMessage::Rumble { controller, low_frequency, high_frequency } => {
let mut b = vec![0u8; 4];
for v in [controller, low_frequency, high_frequency] {
b.extend_from_slice(&v.to_le_bytes());
}
framed(MessageType::RumbleData, &b)
}
HostMessage::RumbleTriggers { controller, left, right } => {
let b: Vec<u8> = [controller, left, right].iter().flat_map(|v| v.to_le_bytes()).collect();
framed(MessageType::RumbleTriggers, &b)
}
HostMessage::MotionEvent { controller, rate_hz, kind } => {
let mut b: Vec<u8> = [controller, rate_hz].iter().flat_map(|v| v.to_le_bytes()).collect();
b.push(match kind {
super::message::MotionKind::Accelerometer => 1,
super::message::MotionKind::Gyroscope => 2,
});
framed(MessageType::MotionEvent, &b)
}
HostMessage::RgbLed { controller, r, g, b } => {
let mut body = controller.to_le_bytes().to_vec();
body.extend_from_slice(&[r, g, b]);
framed(MessageType::RgbLed, &body)
}
HostMessage::Termination { error_code: Some(code) } => {
framed(MessageType::TerminationExtended, &code.to_be_bytes())
}
HostMessage::Termination { error_code: None } => {
Err(Error::Unsupported { what: "the plain TERMINATION message (body UNKNOWN U10)" })
}
// HDR_MODE: Moonshine's layout for it cites Sunshine, so it is GPL provenance ([M*], CLEAN_ROOM.md) and
// stays unused until our own measurement settles it. Lumen streams SDR until then.
HostMessage::HdrMode { .. } => {
Err(Error::Unsupported { what: "HDR_MODE (its layout is GPL provenance [M*], not measured yet)" })
}
HostMessage::Other { .. } => Err(Error::Unsupported { what: "a host message without a known layout" }),
}
}
/// The stop deadline of PROTOCOL.md 3.3: each `PERIODIC_PING` pushes it out to `timeout` after the ping.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct StopDeadline {
timeout: Duration,
deadline: Instant,
}
impl StopDeadline {
/// A deadline `timeout` after `now`.
#[must_use]
pub fn new(now: Instant, timeout: Duration) -> Self {
Self { timeout, deadline: now.saturating_add(timeout) }
}
/// A ping arrived at `now`. The deadline never moves back.
pub fn on_ping(&mut self, now: Instant) {
self.deadline = self.deadline.max(now.saturating_add(self.timeout));
}
/// When the session ends without another ping.
#[must_use]
pub const fn deadline(&self) -> Instant {
self.deadline
}
/// Whether the deadline has passed at `now`.
#[must_use]
pub fn expired(&self, now: Instant) -> bool {
now >= self.deadline
}
}
/// What happened on the host side of the control stream.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ControlHostEvent {
/// The client's ENet connection is up.
Connected,
/// A message from the client.
Message(ClientControlMessage),
/// A client frame failed its tag, came out of order or held a malformed message, and was skipped (counted,
/// never fatal).
Dropped,
/// No `PERIODIC_PING` within the stop timeout: the session should end. Reported once; a later ping starts the
/// clock again.
PingTimedOut,
/// The client closed the stream.
Disconnected,
/// The client stopped answering (ENet).
TimedOut,
}
/// The host side of one control stream.
#[derive(Debug)]
pub struct ControlHost {
enet: EnetHostPeer,
cipher: ControlCipher,
/// Next sequence number to seal with; `u32::MAX + 1` once the space is used up.
next_sequence: u64,
/// Highest client sequence number accepted so far.
last_client_sequence: Option<u32>,
stop_timeout: Option<Duration>,
stop: Option<StopDeadline>,
events: VecDeque<ControlHostEvent>,
}
impl ControlHost {
/// Accepts a client's ENet CONNECT datagram (see [`crate::enet::host`] for the caller's demultiplexing).
///
/// # Errors
/// As [`EnetHostPeer::accept`].
pub fn accept(config: ControlHostConfig, now: Instant, datagram: &[u8]) -> Result<Self> {
Ok(Self {
enet: EnetHostPeer::accept(config.enet, now, datagram)?,
cipher: ControlCipher::new(config.rikey),
next_sequence: 0,
last_client_sequence: None,
stop_timeout: config.stop_timeout,
stop: None,
events: VecDeque::new(),
})
}
/// Moves ENet events into control events, opening every client frame.
fn drain(&mut self, now: Instant) {
while let Some(e) = self.enet.poll_event() {
let event = match e {
EnetHostEvent::Connected { .. } => {
self.stop = self.stop_timeout.map(|t| StopDeadline::new(now, t));
ControlHostEvent::Connected
}
EnetHostEvent::Disconnected { .. } => {
self.stop = None;
ControlHostEvent::Disconnected
}
EnetHostEvent::TimedOut => {
self.stop = None;
ControlHostEvent::TimedOut
}
EnetHostEvent::Received { data, .. } => self.open(now, &data),
};
self.events.push_back(event);
}
}
/// Opens one client frame. A frame that fails, or whose number is not above the last accepted one, is dropped
/// without touching the replay state; a frame that opens moves it forward even if its message is malformed.
fn open(&mut self, now: Instant, frame: &[u8]) -> ControlHostEvent {
let Ok((sequence, plain)) = self.cipher.open(Direction::ClientToHost, frame) else {
return ControlHostEvent::Dropped;
};
if self.last_client_sequence.is_some_and(|last| sequence <= last) {
return ControlHostEvent::Dropped;
}
self.last_client_sequence = Some(sequence);
match parse_client_message(&plain) {
Ok(m) => {
if m == ClientControlMessage::PeriodicPing
&& let Some(timeout) = self.stop_timeout
&& self.enet.state() == EnetHostState::Connected
{
match self.stop.as_mut() {
Some(s) => s.on_ping(now),
None => self.stop = Some(StopDeadline::new(now, timeout)),
}
}
ControlHostEvent::Message(m)
}
Err(_) => ControlHostEvent::Dropped,
}
}
/// Feeds one datagram from the client.
///
/// # Errors
/// As [`EnetHostPeer::handle_datagram`]. Bad frames inside a good datagram are not errors; they become
/// [`ControlHostEvent::Dropped`].
pub fn handle_datagram(&mut self, now: Instant, datagram: &[u8]) -> Result<()> {
let r = self.enet.handle_datagram(now, datagram);
self.drain(now);
r
}
/// Seals and queues a message to the client (reliable, channel 0).
///
/// # Errors
/// As [`encode_host_message`] and [`EnetHostPeer::send`]; [`Error::Closed`] once the sequence space is used up
/// (2^32 messages).
pub fn send(&mut self, now: Instant, message: &HostMessage) -> Result<()> {
let plain = encode_host_message(message)?;
let sequence = u32::try_from(self.next_sequence).map_err(|_| Error::Closed)?;
let frame = self.cipher.seal(sequence, Direction::HostToClient, &plain)?;
self.enet.send(now, HOST_CHANNEL, Delivery::Reliable, &frame)?;
self.next_sequence += 1;
Ok(())
}
/// Rumbles a controller.
///
/// # Errors
/// As [`Self::send`].
pub fn send_rumble(
&mut self,
now: Instant,
controller: u16,
low_frequency: u16,
high_frequency: u16,
) -> Result<()> {
self.send(now, &HostMessage::Rumble { controller, low_frequency, high_frequency })
}
/// Rumbles a controller's triggers.
///
/// # Errors
/// As [`Self::send`].
pub fn send_rumble_triggers(&mut self, now: Instant, controller: u16, left: u16, right: u16) -> Result<()> {
self.send(now, &HostMessage::RumbleTriggers { controller, left, right })
}
/// Ends the session with an extended termination code ([`TERMINATION_GRACEFUL`] for a normal end). Follow it
/// with [`Self::close`]; the message goes out before the disconnect.
///
/// # Errors
/// As [`Self::send`].
pub fn send_termination(&mut self, now: Instant, error_code: u32) -> Result<()> {
self.send(now, &HostMessage::Termination { error_code: Some(error_code) })
}
/// HDR mode: a typed placeholder that is **not implemented**. The only known layout (PROTOCOL.md 3.3) has GPL
/// provenance (`[M*]`), so nothing is sent until our own measurement settles it.
///
/// # Errors
/// Always [`Error::Unsupported`]; nothing is queued.
pub fn send_hdr_mode(&mut self, now: Instant, enabled: bool, metadata: Option<HdrMetadata>) -> Result<()> {
self.send(now, &HostMessage::HdrMode { enabled, metadata })
}
/// The next datagram to send.
pub fn poll_transmit(&mut self, now: Instant) -> Option<Vec<u8>> {
self.enet.poll_transmit(now)
}
/// The next event.
pub fn poll_event(&mut self) -> Option<ControlHostEvent> {
self.events.pop_front()
}
/// When [`Self::handle_timeout`] is due (ENet timers or the stop deadline).
#[must_use]
pub fn poll_timeout(&self) -> Option<Instant> {
let stop = self.stop_deadline();
match (self.enet.poll_timeout(), stop) {
(Some(a), Some(b)) => Some(a.min(b)),
(a, b) => a.or(b),
}
}
/// Advances timers: ENet's, then the stop deadline ([`ControlHostEvent::PingTimedOut`]).
///
/// # Errors
/// As [`EnetHostPeer::handle_timeout`].
pub fn handle_timeout(&mut self, now: Instant) -> Result<()> {
let r = self.enet.handle_timeout(now);
self.drain(now);
if self.stop.is_some_and(|s| s.expired(now)) {
self.stop = None;
self.events.push_back(ControlHostEvent::PingTimedOut);
}
r
}
/// Closes the stream gracefully (ENet disconnect; messages queued before it go out first).
///
/// # Errors
/// [`Error::Closed`] when already closed.
pub fn close(&mut self, now: Instant) -> Result<()> {
self.stop = None;
self.enet.disconnect(now, 0)
}
/// The ENet peer underneath (state, connect id, round-trip time).
#[must_use]
pub const fn enet(&self) -> &EnetHostPeer {
&self.enet
}
/// When the session ends without another `PERIODIC_PING`, while that clock runs (from the connection on, until
/// it is reported or the stream closes).
#[must_use]
pub fn stop_deadline(&self) -> Option<Instant> {
if self.enet.state() == EnetHostState::Disconnected {
return None;
}
self.stop.map(|s| s.deadline())
}
}
+5
View File
@@ -11,9 +11,14 @@ use crate::enet::{Delivery, EnetClient, EnetConfig, EnetEvent};
use crate::{Instant, RandomSource, Result};
pub mod frame;
pub mod host;
pub mod message;
pub use frame::{ControlCipher, Direction, EncryptedFrame, parse_encrypted_frame};
pub use host::{
ClientControlMessage, ControlHost, ControlHostConfig, ControlHostEvent, StopDeadline, encode_host_message,
parse_client_message,
};
pub use message::{ClientMessage, HostMessage, MessageType, parse_host_message, parse_message};
/// Settings of one control stream. `Debug` never prints the key.
+793
View File
@@ -0,0 +1,793 @@
//! The accepting side of the ENet 1.3 layer (`docs/PROTOCOL.md` 3.1): one host-side peer per client.
//!
//! The caller owns the UDP socket and **demultiplexes by source address**: a datagram from an address it does not
//! know yet goes to [`EnetHostPeer::accept`], which takes only a CONNECT and creates the peer; every later datagram
//! from that address goes to [`EnetHostPeer::handle_datagram`] of that peer. A CONNECT with a new connect id from a
//! known address is a new connection (the client restarted): the peer ignores it, and [`parse_connect_request`]
//! lets the caller see it and replace the old peer. Each peer has its own `peer_id` in [`EnetHostConfig`]; it may be
//! the same for every peer, since the caller tells clients apart by address.
//!
//! ```text
//! on datagram d from addr:
//! match peers[addr] {
//! None => peers[addr] = EnetHostPeer::accept(config, now, &d)?, // refused: drop d
//! Some(p) => p.handle_datagram(now, &d)?,
//! }
//! loop {
//! while let Some(d) = peer.poll_transmit(now) { socket.send_to(&d, addr) }
//! while let Some(e) = peer.poll_event() { … }
//! wake at peer.poll_timeout() → peer.handle_timeout(now)
//! }
//! ```
//!
//! What the host does, as stock ENet 1.3 does it (PROTOCOL.md 3.1): the CONNECT is answered with a reliable VERIFY
//! CONNECT on the connection channel (the CONNECT itself is not acknowledged: the verify retires it on the client);
//! the session ids are picked from the ones the client offers; the connection counts as up when the client
//! acknowledges the verify, and data that arrives earlier is neither taken nor acknowledged (the client sends it
//! again). A command that wants an acknowledgement in a datagram without a sent time is handled but not acknowledged,
//! and the rest of that datagram is skipped. Duplicated unsequenced packets are dropped with a 1024-group window.
//! Not done: the checksum and compression (PROTOCOL.md 3.1: GameStream clients use neither), bandwidth throttling of
//! what the host sends (bandwidth-limit and throttle-configure commands are acknowledged and otherwise ignored), and
//! unreliable fragments (dropped; control messages are small and reliable).
use core::time::Duration;
use std::collections::VecDeque;
use super::protocol::{
self, Command, CommandBody, ConnectParams, Datagram, MAX_DATAGRAM_BYTES, MAX_PEER_ID, MAX_WINDOW_SIZE, MIN_MTU,
MIN_WINDOW_SIZE, NO_PEER_ID,
};
use super::{
CONNECTION_CHANNEL, Channel, Delivery, INITIAL_RTO, InFlight, MAX_IN_FLIGHT, MAX_PACKET_BYTES, MAX_PENDING_ACKS,
MAX_PENDING_PER_CHANNEL, MAX_REASSEMBLIES, MAX_RTO, MAX_SEND_QUEUE, MIN_RTO, Outgoing, Pending, RELIABLE_WINDOW,
Reassembly, check_fragment, ms16,
};
use crate::util::malformed;
use crate::{Error, Instant, Result};
/// Unsequenced groups tracked per window (stock ENet's window).
const UNSEQUENCED_WINDOW: u32 = 1024;
/// Windows ahead of the current one that are accepted (stock ENet's free windows).
const FREE_UNSEQUENCED_WINDOWS: u32 = 32;
/// The session id of a peer slot that has never been used (stock ENet's reset value).
const FRESH_SESSION: u8 = 0xFF;
/// Settings of the host side.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct EnetHostConfig {
/// Our peer id, which the client puts in the header of every datagram it sends us (0..=0xFFE).
pub peer_id: u16,
/// Most channels we grant (the client's request is capped to this; at least 1).
pub channel_limit: u8,
/// Our MTU (576..=4096); the connection uses the smaller of this and the client's.
pub mtu: u16,
/// Send a ping when nothing was received for this long.
pub ping_interval: Duration,
/// Give up when a reliable command stays unacknowledged this long.
pub timeout: Duration,
}
/// State of the host-side peer.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum EnetHostState {
/// Verify connect sent, waiting for the client to acknowledge it.
AcknowledgingConnect,
/// Connected.
Connected,
/// Our disconnect sent, waiting for its acknowledgement.
Disconnecting,
/// Closed (by either side or by timeout).
Disconnected,
}
/// What happened.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum EnetHostEvent {
/// The client acknowledged our verify connect.
Connected {
/// The connect command's user data word.
data: u32,
},
/// A packet arrived (reassembled, in order for reliable and unreliable delivery).
Received {
/// Channel.
channel: u8,
/// The packet.
data: Vec<u8>,
},
/// The client closed the connection.
Disconnected {
/// The client's disconnect data word.
data: u32,
},
/// The client stopped answering.
TimedOut,
}
/// A client's CONNECT, as [`parse_connect_request`] finds it.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct ConnectRequest {
/// The connect parameters.
pub params: ConnectParams,
/// The connect command's user data word.
pub data: u32,
}
/// The CONNECT in a datagram addressed to "no peer yet", if it holds one. As in stock ENet, only a CONNECT at the
/// start of such a datagram counts.
///
/// # Errors
/// Parser errors as [`protocol::parse_datagram`]; [`Error::UnexpectedValue`] when the datagram is addressed to a
/// peer, does not start with a CONNECT, or asks for a channel count outside 1..=255.
pub fn parse_connect_request(datagram: &[u8]) -> Result<ConnectRequest> {
let d = protocol::parse_datagram(datagram)?;
if d.peer_id != NO_PEER_ID {
return Err(Error::UnexpectedValue { what: "enet connect peer id", value: d.peer_id.into() });
}
let Some(first) = d.commands.into_iter().next() else {
return Err(Error::UnexpectedValue { what: "enet connect command", value: 0 });
};
let CommandBody::Connect { params, data } = first.body else {
return Err(Error::UnexpectedValue {
what: "enet connect command",
value: (protocol::kind_of(&first.body) as u8).into(),
});
};
if params.channel_count == 0 || params.channel_count > u32::from(protocol::MAX_CHANNEL_COUNT) {
return Err(Error::UnexpectedValue { what: "enet channel count", value: params.channel_count.into() });
}
Ok(ConnectRequest { params, data })
}
/// The session id one side ends up with: the offered one (or ours when the client says "pick one", 0xFF) plus
/// one, skipping the value the slot used last (PROTOCOL.md 3.1, stock ENet).
const fn next_session(offered: u8, current: u8) -> u8 {
let base = if offered == FRESH_SESSION { current } else { offered };
let mut s = base.wrapping_add(1) & 0x3;
if s == current {
s = s.wrapping_add(1) & 0x3;
}
s
}
/// The host-side ENet peer of one client.
#[derive(Debug)]
pub struct EnetHostPeer {
config: EnetHostConfig,
state: EnetHostState,
connect_id: u32,
connect_data: u32,
/// The client's peer id: the header of every datagram we send.
client_peer_id: u16,
/// Session id in the header of our datagrams.
out_session: u8,
/// Session id the client's datagrams must carry.
in_session: u8,
channel_count: u8,
mtu: usize,
connection_out_reliable: u16,
unsequenced_group: u16,
in_unsequenced_base: u16,
unsequenced_seen: [u32; (UNSEQUENCED_WINDOW / 32) as usize],
channels: Vec<Channel>,
outgoing: VecDeque<Outgoing>,
queued_packets: usize,
resend: VecDeque<Command>,
acks: VecDeque<Command>,
in_flight: Vec<InFlight>,
reassemblies: Vec<Reassembly>,
events: VecDeque<EnetHostEvent>,
last_receive: Instant,
srtt: Option<Duration>,
rttvar: Duration,
}
impl EnetHostPeer {
/// Accepts a client's CONNECT datagram: queues the verify connect. The datagram is consumed; do not feed it to
/// [`Self::handle_datagram`] again.
///
/// # Errors
/// [`Error::Malformed`] for a config outside ENet's limits (MTU 576..=4096, at least one channel, peer id up to
/// 0xFFE); anything [`parse_connect_request`] refuses.
pub fn accept(config: EnetHostConfig, now: Instant, datagram: &[u8]) -> Result<Self> {
if config.mtu < MIN_MTU
|| usize::from(config.mtu) > MAX_DATAGRAM_BYTES
|| config.channel_limit == 0
|| config.peer_id >= MAX_PEER_ID
{
return Err(malformed("enet host config"));
}
let ConnectRequest { params: p, data } = parse_connect_request(datagram)?;
let out_session = next_session(p.incoming_session_id, FRESH_SESSION);
let in_session = next_session(p.outgoing_session_id, FRESH_SESSION);
let max_mtu = u32::try_from(MAX_DATAGRAM_BYTES).unwrap_or(u32::MAX);
let mtu = p.mtu.clamp(u32::from(MIN_MTU), max_mtu).min(u32::from(config.mtu));
let window_size = MAX_WINDOW_SIZE.min(p.window_size).clamp(MIN_WINDOW_SIZE, MAX_WINDOW_SIZE);
let channel_count = u8::try_from(p.channel_count.min(u32::from(config.channel_limit))).unwrap_or(1);
let mut peer = Self {
config,
state: EnetHostState::AcknowledgingConnect,
connect_id: p.connect_id,
connect_data: data,
client_peer_id: p.outgoing_peer_id & MAX_PEER_ID,
out_session,
in_session,
channel_count,
mtu: usize::try_from(mtu).unwrap_or(usize::from(MIN_MTU)),
connection_out_reliable: 0,
unsequenced_group: 0,
in_unsequenced_base: 0,
unsequenced_seen: [0; (UNSEQUENCED_WINDOW / 32) as usize],
channels: (0..channel_count).map(|_| Channel::default()).collect(),
outgoing: VecDeque::new(),
queued_packets: 0,
resend: VecDeque::new(),
acks: VecDeque::new(),
in_flight: Vec::new(),
reassemblies: Vec::new(),
events: VecDeque::new(),
last_receive: now,
srtt: None,
rttvar: Duration::ZERO,
};
let verify = ConnectParams {
outgoing_peer_id: config.peer_id,
incoming_session_id: out_session,
outgoing_session_id: in_session,
mtu,
window_size,
channel_count: u32::from(channel_count),
incoming_bandwidth: 0,
outgoing_bandwidth: 0,
packet_throttle_interval: p.packet_throttle_interval,
packet_throttle_acceleration: p.packet_throttle_acceleration,
packet_throttle_deceleration: p.packet_throttle_deceleration,
connect_id: p.connect_id,
};
peer.queue_connection_command(CommandBody::VerifyConnect(verify));
Ok(peer)
}
fn queue_connection_command(&mut self, body: CommandBody) {
self.connection_out_reliable = self.connection_out_reliable.wrapping_add(1);
let command = Command {
acknowledge: true,
channel_id: CONNECTION_CHANNEL,
reliable_sequence: self.connection_out_reliable,
body,
};
self.outgoing.push_back(Outgoing { command, ends_packet: false });
}
fn rto(&self) -> Duration {
match self.srtt {
None => INITIAL_RTO,
Some(s) => (s + 4 * self.rttvar).clamp(MIN_RTO, MAX_RTO),
}
}
/// Closes with `event`. Acknowledgements already queued still go out (the client's disconnect among them).
fn close(&mut self, event: EnetHostEvent) {
self.state = EnetHostState::Disconnected;
self.events.push_back(event);
self.outgoing.clear();
self.queued_packets = 0;
self.resend.clear();
self.in_flight.clear();
self.reassemblies.clear();
for ch in &mut self.channels {
ch.pending.clear();
}
}
/// Feeds one datagram from the client. Datagrams for another peer id or session, and CONNECTs (repeated or
/// new), are dropped without error.
///
/// # Errors
/// Parser errors as [`protocol::parse_datagram`]; [`Error::TooLarge`] or [`Error::Malformed`] for a fragment
/// that lies about its lengths; [`Error::Closed`] once disconnected. A malformed datagram never changes the
/// connection state.
pub fn handle_datagram(&mut self, now: Instant, datagram: &[u8]) -> Result<()> {
if self.state == EnetHostState::Disconnected {
return Err(Error::Closed);
}
let d = protocol::parse_datagram(datagram)?;
if d.peer_id != self.config.peer_id || d.session_id != self.in_session {
return Ok(());
}
self.last_receive = now;
let sent_time = d.sent_time;
for c in d.commands {
if self.state == EnetHostState::Disconnected {
break;
}
let wants_ack = c.acknowledge;
// Stock ENet stops at the first command it cannot handle, and after an acknowledged command in a
// datagram without sent time (PROTOCOL.md 3.1).
self.command(now, sent_time, c)?;
if wants_ack && sent_time.is_none() {
break;
}
}
Ok(())
}
fn ack(&mut self, channel: u8, seq: u16, sent_time: Option<u16>) {
let Some(sent_time) = sent_time else { return };
if self.acks.len() >= MAX_PENDING_ACKS {
self.acks.pop_front();
}
self.acks.push_back(Command {
acknowledge: false,
channel_id: channel,
reliable_sequence: seq,
body: CommandBody::Acknowledge { received_reliable_sequence: seq, received_sent_time: sent_time },
});
}
fn command(&mut self, now: Instant, sent_time: Option<u16>, c: Command) -> Result<()> {
let (channel, seq) = (c.channel_id, c.reliable_sequence);
let connected = self.state == EnetHostState::Connected;
match c.body {
CommandBody::Acknowledge { received_reliable_sequence, received_sent_time } => {
self.acknowledged(now, channel, received_reliable_sequence, received_sent_time);
Ok(())
}
CommandBody::Disconnect { data } => {
if c.acknowledge && connected {
self.ack(channel, seq, sent_time);
}
self.close(EnetHostEvent::Disconnected { data });
Ok(())
}
CommandBody::Ping | CommandBody::BandwidthLimit { .. } | CommandBody::ThrottleConfigure { .. } => {
if c.acknowledge && connected {
self.ack(channel, seq, sent_time);
}
Ok(())
}
CommandBody::Connect { .. } | CommandBody::VerifyConnect(_) | CommandBody::SendUnreliableFragment(_) => {
Ok(())
}
CommandBody::SendReliable(data) => self.reliable(channel, seq, sent_time, Pending::Data(data)),
CommandBody::SendFragment(f) => {
let check = check_fragment(seq, &f);
let pending = match &check {
Ok(()) => Pending::Fragment(f),
Err(_) => Pending::Skip,
};
self.reliable(channel, seq, sent_time, pending)?;
check
}
CommandBody::SendUnreliable { unreliable_sequence, data } => {
if connected
&& channel < self.channel_count
&& let Some(ch) = self.channels.get_mut(usize::from(channel))
{
let newer = ch
.in_unreliable
.is_none_or(|last| (1..0x8000).contains(&unreliable_sequence.wrapping_sub(last)));
if newer {
ch.in_unreliable = Some(unreliable_sequence);
self.events.push_back(EnetHostEvent::Received { channel, data });
}
}
Ok(())
}
CommandBody::SendUnsequenced { unsequenced_group, data } => {
if connected && channel < self.channel_count && self.unsequenced_fresh(unsequenced_group) {
self.events.push_back(EnetHostEvent::Received { channel, data });
}
Ok(())
}
}
}
/// Whether an unsequenced group is new: a window of [`UNSEQUENCED_WINDOW`] groups remembers what was seen;
/// groups up to [`FREE_UNSEQUENCED_WINDOWS`] windows ahead move it, anything else is dropped.
fn unsequenced_fresh(&mut self, group: u16) -> bool {
let index = u32::from(group) % UNSEQUENCED_WINDOW;
let base = u32::from(self.in_unsequenced_base);
let mut g = u32::from(group);
if g < base {
g += 0x1_0000;
}
if g >= base + FREE_UNSEQUENCED_WINDOWS * UNSEQUENCED_WINDOW {
return false;
}
let g = g & 0xFFFF;
let new_base = g - index;
if new_base != base {
self.in_unsequenced_base = u16::try_from(new_base).unwrap_or(0);
self.unsequenced_seen = [0; (UNSEQUENCED_WINDOW / 32) as usize];
}
let bit = 1u32 << (index % 32);
let Some(word) = self.unsequenced_seen.get_mut(usize::try_from(index / 32).unwrap_or(usize::MAX)) else {
return false;
};
if *word & bit != 0 {
return false;
}
*word |= bit;
true
}
/// A reliable command on a data channel: acknowledged, ordered, then processed in sequence. Taken only while
/// connected.
fn reliable(&mut self, channel: u8, seq: u16, sent_time: Option<u16>, pending: Pending) -> Result<()> {
if self.state != EnetHostState::Connected || channel >= self.channel_count {
return Ok(());
}
let Some(ch) = self.channels.get_mut(usize::from(channel)) else { return Ok(()) };
let next = ch.in_reliable.wrapping_add(1);
let distance = seq.wrapping_sub(next);
if distance >= 0x8000 {
// Already delivered: a retransmission. Acknowledge again, deliver nothing.
self.ack(channel, seq, sent_time);
return Ok(());
}
if distance >= RELIABLE_WINDOW || ch.pending.len() >= MAX_PENDING_PER_CHANNEL {
return Ok(());
}
ch.pending.entry(seq).or_insert(pending);
self.ack(channel, seq, sent_time);
self.deliver_in_order(channel);
Ok(())
}
fn deliver_in_order(&mut self, channel: u8) {
loop {
let Some(ch) = self.channels.get_mut(usize::from(channel)) else { return };
let next = ch.in_reliable.wrapping_add(1);
let Some(p) = ch.pending.remove(&next) else { return };
ch.in_reliable = next;
match p {
Pending::Data(data) => self.events.push_back(EnetHostEvent::Received { channel, data }),
Pending::Fragment(f) => self.fragment(channel, f),
Pending::Skip => {}
}
}
}
/// One checked fragment ([`check_fragment`] ran before it was queued).
fn fragment(&mut self, channel: u8, f: protocol::Fragment) {
let idx = match self.reassemblies.iter().position(|r| r.channel == channel && r.start == f.start_sequence) {
Some(i) => i,
None => {
if self.reassemblies.len() >= MAX_REASSEMBLIES {
self.reassemblies.remove(0);
}
let (Ok(count), Ok(total)) = (usize::try_from(f.fragment_count), usize::try_from(f.total_length))
else {
return;
};
self.reassemblies.push(Reassembly {
channel,
start: f.start_sequence,
count: f.fragment_count,
total: f.total_length,
got: vec![false; count],
received: 0,
data: vec![0; total],
});
self.reassemblies.len() - 1
}
};
let Some(r) = self.reassemblies.get_mut(idx) else { return };
if r.count != f.fragment_count || r.total != f.total_length {
self.reassemblies.remove(idx);
return;
}
let (Ok(number), Ok(offset)) = (usize::try_from(f.fragment_number), usize::try_from(f.fragment_offset)) else {
return;
};
let Some(seen) = r.got.get_mut(number) else { return };
if *seen {
return;
}
let Some(end) = offset.checked_add(f.data.len()) else { return };
let Some(dest) = r.data.get_mut(offset..end) else { return };
dest.copy_from_slice(&f.data);
*seen = true;
r.received += 1;
if r.received == r.count {
let done = self.reassemblies.remove(idx);
self.events.push_back(EnetHostEvent::Received { channel, data: done.data });
}
}
fn acknowledged(&mut self, now: Instant, channel: u8, seq: u16, sent_time: u16) {
let Some(pos) =
self.in_flight.iter().position(|f| f.command.channel_id == channel && f.command.reliable_sequence == seq)
else {
return;
};
let done = self.in_flight.remove(pos);
self.resend.retain(|c| !(c.channel_id == channel && c.reliable_sequence == seq));
let sample = ms16(now).wrapping_sub(sent_time);
if sample < 10_000 {
let sample = Duration::from_millis(u64::from(sample));
match self.srtt {
None => {
self.srtt = Some(sample);
self.rttvar = sample / 2;
}
Some(s) => {
let diff = s.abs_diff(sample);
self.rttvar = (self.rttvar * 3 + diff) / 4;
self.srtt = Some((s * 7 + sample) / 8);
}
}
}
match (done.command.body, self.state) {
(CommandBody::VerifyConnect(_), EnetHostState::AcknowledgingConnect) => {
self.state = EnetHostState::Connected;
self.events.push_back(EnetHostEvent::Connected { data: self.connect_data });
}
(CommandBody::Disconnect { .. }, EnetHostState::Disconnecting) => {
self.state = EnetHostState::Disconnected;
self.outgoing.clear();
self.queued_packets = 0;
self.resend.clear();
self.in_flight.clear();
}
_ => {}
}
}
/// Queues a packet. Packets larger than one command within the MTU are fragmented.
///
/// # Errors
/// [`Error::State`] unless connected, [`Error::UnexpectedValue`] for a channel outside the granted count,
/// [`Error::TooLarge`] over [`MAX_PACKET_BYTES`], an unsequenced packet over one command, or a full queue
/// ([`MAX_SEND_QUEUE`] packets).
pub fn send(&mut self, now: Instant, channel: u8, delivery: Delivery, data: &[u8]) -> Result<()> {
let _ = now;
if self.state != EnetHostState::Connected {
return Err(Error::State { expected: "enet connected" });
}
if channel >= self.channel_count {
return Err(Error::UnexpectedValue { what: "enet channel", value: channel.into() });
}
crate::util::cap("enet packet", MAX_PACKET_BYTES, data.len())?;
crate::util::cap("enet send queue", MAX_SEND_QUEUE, self.queued_packets + 1)?;
// Header with sent time (4) plus the command header and its fields.
let single = self.mtu.saturating_sub(4 + 6);
let piece = self.mtu.saturating_sub(4 + 24).max(1);
if delivery == Delivery::Unsequenced && data.len() > single {
return Err(Error::TooLarge { what: "enet unsequenced packet", max: single, actual: data.len() });
}
let Some(ch) = self.channels.get_mut(usize::from(channel)) else {
return Err(Error::UnexpectedValue { what: "enet channel", value: channel.into() });
};
let mut commands = Vec::new();
match delivery {
Delivery::Reliable | Delivery::Unreliable if data.len() > single => {
let count = data.len().div_ceil(piece);
let start = ch.out_reliable.wrapping_add(1);
let total = u32::try_from(data.len()).unwrap_or(u32::MAX);
for (n, chunk) in data.chunks(piece).enumerate() {
ch.out_reliable = ch.out_reliable.wrapping_add(1);
let f = protocol::Fragment {
start_sequence: start,
fragment_count: u32::try_from(count).unwrap_or(u32::MAX),
fragment_number: u32::try_from(n).unwrap_or(u32::MAX),
total_length: total,
fragment_offset: u32::try_from(n * piece).unwrap_or(u32::MAX),
data: chunk.to_vec(),
};
commands.push(Command {
acknowledge: true,
channel_id: channel,
reliable_sequence: ch.out_reliable,
body: CommandBody::SendFragment(f),
});
}
}
Delivery::Reliable => {
ch.out_reliable = ch.out_reliable.wrapping_add(1);
commands.push(Command {
acknowledge: true,
channel_id: channel,
reliable_sequence: ch.out_reliable,
body: CommandBody::SendReliable(data.to_vec()),
});
}
Delivery::Unreliable => {
ch.out_unreliable = ch.out_unreliable.wrapping_add(1);
commands.push(Command {
acknowledge: false,
channel_id: channel,
reliable_sequence: ch.out_reliable,
body: CommandBody::SendUnreliable { unreliable_sequence: ch.out_unreliable, data: data.to_vec() },
});
}
Delivery::Unsequenced => {
self.unsequenced_group = self.unsequenced_group.wrapping_add(1);
commands.push(Command {
acknowledge: false,
channel_id: channel,
reliable_sequence: 0,
body: CommandBody::SendUnsequenced {
unsequenced_group: self.unsequenced_group,
data: data.to_vec(),
},
});
}
}
let last = commands.len().saturating_sub(1);
for (i, command) in commands.into_iter().enumerate() {
self.outgoing.push_back(Outgoing { command, ends_packet: i == last });
}
self.queued_packets += 1;
Ok(())
}
/// Starts a graceful disconnect. Packets queued before it still go out first (as stock ENet's
/// `disconnect_later`), so a termination message sent just before arrives.
///
/// # Errors
/// [`Error::Closed`] when already disconnected or disconnecting.
pub fn disconnect(&mut self, now: Instant, data: u32) -> Result<()> {
let _ = now;
if matches!(self.state, EnetHostState::Disconnected | EnetHostState::Disconnecting) {
return Err(Error::Closed);
}
self.queue_connection_command(CommandBody::Disconnect { data });
self.state = EnetHostState::Disconnecting;
Ok(())
}
/// The next datagram to send, at most the MTU (acknowledgements, retransmissions, queued packets, pings).
pub fn poll_transmit(&mut self, now: Instant) -> Option<Vec<u8>> {
let budget = self.mtu;
let mut size = 4;
let mut commands: Vec<Command> = Vec::new();
let fits = |size: usize, c: &Command, n: usize| {
n < protocol::MAX_COMMANDS_PER_DATAGRAM && size + protocol::command_size(c) <= budget
};
while let Some(a) = self.acks.front() {
if !fits(size, a, commands.len()) {
break;
}
size += protocol::command_size(a);
if let Some(a) = self.acks.pop_front() {
commands.push(a);
}
}
if self.state != EnetHostState::Disconnected {
let rto = self.rto();
while let Some(c) = self.resend.front() {
if !fits(size, c, commands.len()) {
break;
}
size += protocol::command_size(c);
if let Some(c) = self.resend.pop_front() {
if let Some(f) = self.in_flight.iter_mut().find(|f| {
f.command.channel_id == c.channel_id && f.command.reliable_sequence == c.reliable_sequence
}) {
f.sent_at = now;
}
commands.push(c);
}
}
while let Some(o) = self.outgoing.front() {
if !fits(size, &o.command, commands.len()) || self.in_flight.len() >= MAX_IN_FLIGHT {
break;
}
size += protocol::command_size(&o.command);
let Some(o) = self.outgoing.pop_front() else { break };
if o.ends_packet {
self.queued_packets = self.queued_packets.saturating_sub(1);
}
if o.command.acknowledge {
self.in_flight.push(InFlight { command: o.command.clone(), first_sent: now, sent_at: now, rto });
}
commands.push(o.command);
}
}
if commands.is_empty() {
return None;
}
// Stock ENet leaves the session bits out while the remote peer id is unknown (0xFFF).
let session_id = if self.client_peer_id < MAX_PEER_ID { self.out_session } else { 0 };
let d = Datagram { peer_id: self.client_peer_id, session_id, sent_time: Some(ms16(now)), commands };
protocol::encode_datagram(&d).ok()
}
/// The next event.
pub fn poll_event(&mut self) -> Option<EnetHostEvent> {
self.events.pop_front()
}
/// When [`Self::handle_timeout`] must be called next (retransmission, ping or timeout), if ever.
#[must_use]
pub fn poll_timeout(&self) -> Option<Instant> {
if self.state == EnetHostState::Disconnected {
return None;
}
let flight = self
.in_flight
.iter()
.flat_map(|f| [f.sent_at.saturating_add(f.rto), f.first_sent.saturating_add(self.config.timeout)])
.min();
let ping = (self.state == EnetHostState::Connected && self.in_flight.is_empty())
.then(|| self.last_receive.saturating_add(self.config.ping_interval));
match (flight, ping) {
(Some(a), Some(b)) => Some(a.min(b)),
(a, b) => a.or(b),
}
}
/// Advances timers: retransmits, pings a client that has been quiet for the ping interval, or gives up with
/// [`EnetHostEvent::TimedOut`].
///
/// # Errors
/// None today.
pub fn handle_timeout(&mut self, now: Instant) -> Result<()> {
if self.state == EnetHostState::Disconnected {
return Ok(());
}
let timeout = self.config.timeout;
if self.in_flight.iter().any(|f| f.first_sent.saturating_add(timeout) <= now) {
self.close(EnetHostEvent::TimedOut);
return Ok(());
}
for f in &mut self.in_flight {
if f.sent_at.saturating_add(f.rto) <= now
&& !self
.resend
.iter()
.any(|c| c.channel_id == f.command.channel_id && c.reliable_sequence == f.command.reliable_sequence)
{
f.rto = (f.rto * 2).min(MAX_RTO);
f.sent_at = now;
self.resend.push_back(f.command.clone());
}
}
if self.state == EnetHostState::Connected
&& self.in_flight.is_empty()
&& self.outgoing.is_empty()
&& self.last_receive.saturating_add(self.config.ping_interval) <= now
{
self.queue_connection_command(CommandBody::Ping);
}
Ok(())
}
/// Connection state.
#[must_use]
pub const fn state(&self) -> EnetHostState {
self.state
}
/// The connect id of this connection (compare with [`parse_connect_request`] to spot a new connection).
#[must_use]
pub const fn connect_id(&self) -> u32 {
self.connect_id
}
/// Channels granted.
#[must_use]
pub const fn channel_count(&self) -> u8 {
self.channel_count
}
/// The MTU in use.
#[must_use]
pub const fn mtu(&self) -> usize {
self.mtu
}
/// Smoothed round-trip time, once measured.
#[must_use]
pub const fn round_trip_time(&self) -> Option<Duration> {
self.srtt
}
/// The configuration.
#[must_use]
pub const fn config(&self) -> &EnetHostConfig {
&self.config
}
}
+4 -1
View File
@@ -1,5 +1,5 @@
//! A sans-I/O ENet 1.3 client peer, compatible with GameStream hosts (`docs/PROTOCOL.md` 3.1,
//! `docs/research/open-point-2.md`).
//! `docs/research/open-point-2.md`), and its accepting mirror for the Lumen host, [`host::EnetHostPeer`].
//!
//! One peer, one connection. The caller owns the UDP socket:
//!
@@ -24,8 +24,11 @@ use protocol::{Command, CommandBody, ConnectParams, Datagram, Fragment, MAX_DATA
use crate::util::malformed;
use crate::{Error, Instant, RandomSource, Result};
pub mod host;
pub mod protocol;
pub use host::{ConnectRequest, EnetHostConfig, EnetHostEvent, EnetHostPeer, EnetHostState, parse_connect_request};
/// Maximum size of one reassembled packet, in bytes (control messages are small; this caps fragment memory).
pub const MAX_PACKET_BYTES: usize = 64 * 1024;
/// Maximum number of packets queued for sending before [`EnetClient::send`] refuses more.
+2 -2
View File
@@ -21,8 +21,8 @@
//! | [`http`] | serverinfo, applist, launch/resume/cancel (section 1) |
//! | [`pairing`] | the PIN handshake and the client certificate (section 1.5) |
//! | [`rtsp`] | OPTIONS, DESCRIBE, SETUP, ANNOUNCE, PLAY and SDP (section 2) |
//! | [`enet`] | the ENet-compatible reliable UDP layer under the control stream (section 3.1) |
//! | [`control`] | AES-GCM framing and control messages (sections 3.2, 3.3) |
//! | [`enet`] | the ENet-compatible reliable UDP layer under the control stream, client and host side (section 3.1) |
//! | [`control`] | AES-GCM framing and control messages, client and host side (sections 3.2, 3.3) |
//! | [`input`] | input and gamepad packets (section 4) |
//! | [`rtp`] | the RTP header shared by video and audio |
//! | [`fec`] | Reed-Solomon erasure coding over GF(2^8) |
+52 -8
View File
@@ -1,11 +1,13 @@
//! RTSP stream negotiation (`docs/PROTOCOL.md` section 2): message codec, a framer for the TCP byte stream, SDP,
//! and the client state machine.
//! the client state machine and the host's session ([`server`], section 2.5).
pub mod client;
pub mod sdp;
pub mod server;
pub use client::{NegotiatedStream, RtspClient, RtspClientState, RtspProgress, StreamConfig, StreamPorts};
pub use sdp::{EncryptionFlags, HostCapabilities, OpusConfig, Sdp};
pub use server::{HostOffer, RtspServer, RtspServerState, ServerConfig, ServerEvent, ServerReply};
use crate::util::{cap, malformed, parse_dec};
use crate::{Error, Result};
@@ -132,6 +134,37 @@ impl RtspResponse {
pub fn header(&self, name: &str) -> Option<&str> {
header(&self.headers, name)
}
/// Serializes the response (`RTSP/1.0 <status> <reason>`, CRLF line ends, empty line, payload) with exactly the
/// given headers. The host side's mirror of [`RtspRequest::encode`].
///
/// # Errors
/// [`Error::Malformed`] for a status outside 100..=999, CR, LF or another control character in the reason, a
/// header name that is not a token, or CR or LF in a header value; [`Error::TooLarge`] over
/// [`MAX_RTSP_MESSAGE_BYTES`].
pub fn encode(&self) -> Result<Vec<u8>> {
if !(100..=999).contains(&self.status) || self.reason.bytes().any(|b| b.is_ascii_control()) {
return Err(malformed("rtsp status line"));
}
let mut out = format!("{VERSION} {} {}\r\n", self.status, self.reason);
for (name, value) in &self.headers {
if name.is_empty() || !name.bytes().all(is_token) {
return Err(malformed("rtsp header name"));
}
if value.bytes().any(|b| b == b'\r' || b == b'\n') {
return Err(malformed("rtsp header value"));
}
out.push_str(name);
out.push_str(": ");
out.push_str(value);
out.push_str("\r\n");
}
out.push_str("\r\n");
let mut bytes = out.into_bytes();
cap("rtsp response", MAX_RTSP_MESSAGE_BYTES, bytes.len().saturating_add(self.body.len()))?;
bytes.extend_from_slice(&self.body);
Ok(bytes)
}
}
/// A message split into start line, headers and payload.
@@ -252,21 +285,31 @@ pub fn parse_request(message: &[u8]) -> Result<RtspRequest> {
Ok(RtspRequest { method, target: target.to_owned(), headers: m.headers, body: m.body })
}
/// Cuts the TCP byte stream from the host into whole messages.
/// Cuts a TCP byte stream into whole messages.
///
/// A message ends after its headers plus `Content-Length` payload bytes; without `Content-Length` it ends when
/// the host closes the connection ([`RtspFramer::finish`]) (UNKNOWN U5). Never buffers more than
/// [`MAX_RTSP_MESSAGE_BYTES`].
/// A message ends after its headers plus `Content-Length` payload bytes. Without `Content-Length`, a framer made
/// with [`RtspFramer::new`] (the client reading the host's answers) ends the message when the host closes the
/// connection ([`RtspFramer::finish`]) (UNKNOWN U5); one made with [`RtspFramer::for_requests`] (the host reading
/// a client's requests) takes a missing `Content-Length` as zero, as RFC 2326 section 4.4 says, so the message
/// ends at the empty line (`docs/PROTOCOL.md` 2.5). Never buffers more than [`MAX_RTSP_MESSAGE_BYTES`].
#[derive(Debug, Default)]
pub struct RtspFramer {
buffer: Vec<u8>,
/// A missing `Content-Length` means "no payload" (requests) instead of "until close" (answers).
missing_length_is_zero: bool,
}
impl RtspFramer {
/// An empty framer.
/// An empty framer for the host's answers (client side).
#[must_use]
pub const fn new() -> Self {
Self { buffer: Vec::new() }
Self { buffer: Vec::new(), missing_length_is_zero: false }
}
/// An empty framer for a client's requests (host side): a request without `Content-Length` has no payload.
#[must_use]
pub const fn for_requests() -> Self {
Self { buffer: Vec::new(), missing_length_is_zero: true }
}
/// Appends received bytes.
@@ -293,7 +336,8 @@ impl RtspFramer {
headers.push((n.to_owned(), v.trim_matches([' ', '\t']).to_owned()));
}
}
Ok(Some((head_len, content_length(&headers, head_len)?)))
let length = content_length(&headers, head_len)?;
Ok(Some((head_len, if self.missing_length_is_zero { Some(length.unwrap_or(0)) } else { length })))
}
/// Takes the next complete message, if one is buffered.
+1 -1
View File
@@ -199,7 +199,7 @@ impl HostCapabilities {
}
}
/// `x-nv-vqos[0].bitStreamFormat` values (judgment from the codec order H.264, HEVC, AV1; UNKNOWN U6).
/// `x-nv-vqos[0].bitStreamFormat` values: 0 H.264, 1 HEVC, 2 AV1 as a host reads them (`docs/PROTOCOL.md` 2.5 \[M\]).
const fn bitstream_format(codec: VideoCodec) -> u8 {
match codec {
VideoCodec::H264 => 0,
@@ -0,0 +1,338 @@
//! The ANNOUNCE payload on the host side (`docs/PROTOCOL.md` 2.4, 2.5): a strict parser of the client's SDP into a
//! typed [`StreamConfig`], and the matching writer.
//!
//! The payload is hostile input. The parser caps the payload size, the number of lines, the length of each line and
//! the number of `a=` attributes before it looks at any of them, allocates nothing while it reads, refuses a known
//! attribute that appears twice, range-checks every number, and counts (then ignores) attributes it does not know.
use crate::rtsp::client::VideoCodec;
use crate::rtsp::sdp::{EncryptionFlags, MAX_AUDIO_CHANNELS};
use crate::util::{cap, malformed, parse_dec};
use crate::{Error, Result};
/// Maximum size of an ANNOUNCE payload, in bytes (the SDP cap of `docs/PROTOCOL.md` 2.3).
pub const MAX_ANNOUNCE_BYTES: usize = crate::rtsp::sdp::MAX_SDP_BYTES;
/// Maximum number of non-empty lines in an ANNOUNCE payload.
pub const MAX_ANNOUNCE_LINES: usize = 1024;
/// Maximum length of one line, in bytes, without its line end.
pub const MAX_ANNOUNCE_LINE_BYTES: usize = 1024;
/// Maximum number of `a=` attributes, known or not.
pub const MAX_ANNOUNCE_ATTRIBUTES: usize = 512;
/// Largest width or height accepted, in pixels (our cap, not the protocol's).
pub const MAX_DIMENSION: u32 = 16_384;
/// Largest frame rate accepted (our cap, not the protocol's).
pub const MAX_FPS: u32 = 1000;
/// Smallest video `packetSize` a host accepts (`docs/PROTOCOL.md` 2.5 \[M\]).
pub const MIN_PACKET_SIZE: u16 = 200;
/// Largest video `packetSize`: one stream packet in one IPv6 UDP datagram (`docs/PROTOCOL.md` 2.5 \[M\]).
pub const MAX_PACKET_SIZE: u16 = 65_471;
/// Largest bitrate in kbit/s: the value times 1000 must fit in a `u32` (`docs/PROTOCOL.md` 2.5 \[M\]).
pub const MAX_BITRATE_KBPS: u32 = 4_294_967;
/// Longest audio packet in milliseconds: the longest Opus packet (RFC 6716 section 3.2.5).
pub const MAX_AUDIO_PACKET_DURATION_MS: u8 = 120;
/// Chroma subsampling, `x-ss-video[0].chromaSamplingType` (`docs/PROTOCOL.md` 2.5 \[M\]).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum ChromaSampling {
/// 4:2:0, value 0 (the default).
#[default]
Yuv420,
/// 4:4:4, value 1.
Yuv444,
}
/// The audio layout the client asks for (`x-nv-audio.surround.*`, `docs/PROTOCOL.md` 2.5).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct SurroundSettings {
/// `x-nv-audio.surround.enable`: 0 or 1, default 0. When off, a Moonshine-like host takes the layout from the
/// launch call's `surroundAudioInfo` instead of `channels` and `channel_mask` \[M\].
pub enabled: bool,
/// `x-nv-audio.surround.numChannels`: 1..=8, default 2 \[M\].
pub channels: u8,
/// `x-nv-audio.surround.channelMask`: the speaker mask, kept as sent; default `0x3` \[M\].
pub channel_mask: u32,
/// `x-nv-audio.surround.AudioQuality`: 0 or 1, default 1 (high quality) \[M\].
pub high_quality: bool,
}
impl Default for SurroundSettings {
fn default() -> Self {
Self { enabled: false, channels: 2, channel_mask: 0x3, high_quality: true }
}
}
/// What a client asked for in ANNOUNCE, typed and range-checked (`docs/PROTOCOL.md` 2.4, 2.5).
///
/// Values whose meaning is not settled are kept as the raw number the client sent.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct StreamConfig {
/// `x-nv-video[0].clientViewportWd`, required, 1..=[`MAX_DIMENSION`].
pub width: u32,
/// `x-nv-video[0].clientViewportHt`, required, 1..=[`MAX_DIMENSION`].
pub height: u32,
/// `x-nv-video[0].maxFPS`, required, 1..=[`MAX_FPS`].
pub max_fps: u32,
/// `x-nv-video[0].packetSize`, required, [`MIN_PACKET_SIZE`]..=[`MAX_PACKET_SIZE`].
pub packet_size: u16,
/// `x-ml-video.configuredBitrateKbps`, required, 1..=[`MAX_BITRATE_KBPS`].
pub bitrate_kbps: u32,
/// `x-nv-vqos[0].bitStreamFormat`, required: 0 H.264, 1 HEVC, 2 AV1 \[M\]; anything else is refused.
pub codec: VideoCodec,
/// `x-nv-vqos[0].fec.minRequiredFecPackets`, required, 0..=255.
pub min_fec_packets: u8,
/// `x-nv-vqos[0].qosTrafficType`, required, kept as sent (a Moonshine-like host turns QoS off for 0 \[M\]).
pub video_qos_traffic_type: u32,
/// `x-nv-aqos.packetDuration`, required, 1..=[`MAX_AUDIO_PACKET_DURATION_MS`] milliseconds.
pub audio_packet_duration_ms: u8,
/// `x-nv-aqos.qosTrafficType`, required, kept as sent.
pub audio_qos_traffic_type: u32,
/// `x-nv-video[0].maxNumReferenceFrames`, default 1 \[M\]. Kept raw: what 0 means has GPL provenance only
/// (\[M*\], `docs/PROTOCOL.md` 2.4), so it is not interpreted here.
pub max_reference_frames: u32,
/// `x-nv-video[0].refPicInvalidation`, 0 or 1. Default 0 (the client cannot invalidate, so the host sends an
/// IDR frame on loss, which always works): UNKNOWN U6, settled by measurement.
pub reference_frame_invalidation: bool,
/// `x-nv-video[0].dynamicRangeMode`, default 0, kept raw. Moonshine reads 0 as SDR \[M\]; no other value has a
/// settled meaning: UNKNOWN U6, settled by measurement.
pub dynamic_range_mode: u32,
/// `x-nv-video[0].encoderCscMode`, default 0, kept raw. Its bit layout has GPL provenance only (\[M*\]):
/// UNKNOWN U6, settled by measurement (`docs/LUMEN-HOST-PLAN.md` 1.3).
pub encoder_csc_mode: u32,
/// `x-ss-video[0].chromaSamplingType`, 0 or 1, default 0 (4:2:0) \[M\].
pub chroma: ChromaSampling,
/// `x-ss-general.encryptionEnabled`, 0..=255, default 0 \[M\]; bits as in `docs/PROTOCOL.md` 2.3. Kept as sent;
/// [`super::RtspServer`] refuses bits the host did not offer.
pub encryption: EncryptionFlags,
/// `x-nv-audio.surround.*`.
pub surround: SurroundSettings,
/// `a=` attributes the parser does not know: counted, otherwise ignored (UNKNOWN U6). Not written by
/// [`write_announce`].
pub unknown_attributes: u32,
}
/// Parses an ANNOUNCE payload (SDP lines, LF or CRLF, empty lines skipped) into a [`StreamConfig`].
///
/// # Errors
/// [`Error::TooLarge`] over [`MAX_ANNOUNCE_BYTES`], [`MAX_ANNOUNCE_LINES`], [`MAX_ANNOUNCE_LINE_BYTES`] or
/// [`MAX_ANNOUNCE_ATTRIBUTES`]; [`Error::Malformed`] for a payload that is not UTF-8, a line without `=`, an empty
/// line type, a control character, a known attribute given twice, a required attribute missing or a number that is
/// not plain decimal; [`Error::UnexpectedValue`] for a number outside its range.
pub fn parse_announce(payload: &[u8]) -> Result<StreamConfig> {
cap("announce", MAX_ANNOUNCE_BYTES, payload.len())?;
let text = core::str::from_utf8(payload).map_err(|_| malformed("announce: not UTF-8"))?;
let mut values: [Option<&str>; ATTRIBUTES.len()] = [None; ATTRIBUTES.len()];
let mut lines = 0usize;
let mut attributes = 0usize;
let mut unknown = 0u32;
for raw in text.split('\n') {
let line = raw.strip_suffix('\r').unwrap_or(raw);
cap("announce line", MAX_ANNOUNCE_LINE_BYTES, line.len())?;
if line.is_empty() {
continue;
}
lines += 1;
cap("announce lines", MAX_ANNOUNCE_LINES, lines)?;
if line.bytes().any(|b| b.is_ascii_control() && b != b'\t') {
return Err(malformed("announce: control character in a line"));
}
let (kind, rest) = line.split_once('=').ok_or(malformed("announce: line without ="))?;
if kind.is_empty() {
return Err(malformed("announce: line with an empty type"));
}
// Only `a=` lines carry settings; `v=`, `o=`, `s=`, `t=`, `m=` and bare lines are not read.
if kind != "a" {
continue;
}
attributes += 1;
cap("announce attributes", MAX_ANNOUNCE_ATTRIBUTES, attributes)?;
let (name, value) = rest.split_once(':').unwrap_or((rest, ""));
match ATTRIBUTES.iter().position(|a| a.name == name).and_then(|i| values.get_mut(i)) {
Some(Some(_)) => return Err(malformed("announce: an attribute given twice")),
Some(slot) => *slot = Some(value.trim_matches([' ', '\t'])),
None => unknown = unknown.saturating_add(1),
}
}
let a = Values(&values);
let codec = match a.required(BIT_STREAM_FORMAT, 0, 2)? {
0 => VideoCodec::H264,
1 => VideoCodec::Hevc,
_ => VideoCodec::Av1,
};
Ok(StreamConfig {
width: narrow(a.required(VIEWPORT_WD, 1, u64::from(MAX_DIMENSION))?)?,
height: narrow(a.required(VIEWPORT_HT, 1, u64::from(MAX_DIMENSION))?)?,
max_fps: narrow(a.required(MAX_FPS_ATTR, 1, u64::from(MAX_FPS))?)?,
packet_size: narrow(a.required(PACKET_SIZE, u64::from(MIN_PACKET_SIZE), u64::from(MAX_PACKET_SIZE))?)?,
bitrate_kbps: narrow(a.required(BITRATE, 1, u64::from(MAX_BITRATE_KBPS))?)?,
codec,
min_fec_packets: narrow(a.required(MIN_FEC_PACKETS, 0, u64::from(u8::MAX))?)?,
video_qos_traffic_type: narrow(a.required(VIDEO_QOS, 0, u64::from(u32::MAX))?)?,
audio_packet_duration_ms: narrow(a.required(PACKET_DURATION, 1, u64::from(MAX_AUDIO_PACKET_DURATION_MS))?)?,
audio_qos_traffic_type: narrow(a.required(AUDIO_QOS, 0, u64::from(u32::MAX))?)?,
max_reference_frames: narrow(a.optional(MAX_REFERENCE_FRAMES, 1, 0, u64::from(u32::MAX))?)?,
reference_frame_invalidation: a.optional(REF_PIC_INVALIDATION, 0, 0, 1)? == 1,
dynamic_range_mode: narrow(a.optional(DYNAMIC_RANGE_MODE, 0, 0, u64::from(u32::MAX))?)?,
encoder_csc_mode: narrow(a.optional(ENCODER_CSC_MODE, 0, 0, u64::from(u32::MAX))?)?,
chroma: if a.optional(CHROMA_SAMPLING, 0, 0, 1)? == 1 {
ChromaSampling::Yuv444
} else {
ChromaSampling::Yuv420
},
encryption: EncryptionFlags(narrow(a.optional(ENCRYPTION_ENABLED, 0, 0, u64::from(u8::MAX))?)?),
surround: SurroundSettings {
enabled: a.optional(SURROUND_ENABLE, 0, 0, 1)? == 1,
channels: narrow(a.optional(SURROUND_CHANNELS, 2, 1, MAX_AUDIO_CHANNELS as u64)?)?,
channel_mask: narrow(a.optional(SURROUND_MASK, 0x3, 0, u64::from(u32::MAX))?)?,
high_quality: a.optional(AUDIO_QUALITY, 1, 0, 1)? == 1,
},
unknown_attributes: unknown,
})
}
/// Writes `config` as an ANNOUNCE payload (`v=0`, then every known attribute, CRLF line ends) that
/// [`parse_announce`] reads back as the same config (with `unknown_attributes` 0).
#[must_use]
pub fn write_announce(config: &StreamConfig) -> Vec<u8> {
let codec: u8 = match config.codec {
VideoCodec::H264 => 0,
VideoCodec::Hevc => 1,
VideoCodec::Av1 => 2,
};
let chroma: u8 = match config.chroma {
ChromaSampling::Yuv420 => 0,
ChromaSampling::Yuv444 => 1,
};
let s = &config.surround;
let values: [(usize, u64); ATTRIBUTES.len()] = [
(VIEWPORT_WD, u64::from(config.width)),
(VIEWPORT_HT, u64::from(config.height)),
(MAX_FPS_ATTR, u64::from(config.max_fps)),
(PACKET_SIZE, u64::from(config.packet_size)),
(BITRATE, u64::from(config.bitrate_kbps)),
(BIT_STREAM_FORMAT, u64::from(codec)),
(MIN_FEC_PACKETS, u64::from(config.min_fec_packets)),
(VIDEO_QOS, u64::from(config.video_qos_traffic_type)),
(PACKET_DURATION, u64::from(config.audio_packet_duration_ms)),
(AUDIO_QOS, u64::from(config.audio_qos_traffic_type)),
(MAX_REFERENCE_FRAMES, u64::from(config.max_reference_frames)),
(REF_PIC_INVALIDATION, u64::from(config.reference_frame_invalidation)),
(DYNAMIC_RANGE_MODE, u64::from(config.dynamic_range_mode)),
(ENCODER_CSC_MODE, u64::from(config.encoder_csc_mode)),
(CHROMA_SAMPLING, u64::from(chroma)),
(ENCRYPTION_ENABLED, u64::from(config.encryption.0)),
(SURROUND_ENABLE, u64::from(s.enabled)),
(SURROUND_CHANNELS, u64::from(s.channels)),
(SURROUND_MASK, u64::from(s.channel_mask)),
(AUDIO_QUALITY, u64::from(s.high_quality)),
];
let mut out = String::with_capacity(1024);
out.push_str("v=0\r\n");
for (index, value) in values {
if let Some(attribute) = ATTRIBUTES.get(index) {
out.push_str("a=");
out.push_str(attribute.name);
out.push(':');
out.push_str(&value.to_string());
out.push_str("\r\n");
}
}
out.into_bytes()
}
/// One attribute the host reads (`docs/PROTOCOL.md` 2.4, 2.5).
struct Attribute {
/// The SDP attribute name.
name: &'static str,
/// The error text when a required attribute is missing; `None` for attributes with a default.
missing: Option<&'static str>,
}
const fn required(name: &'static str, missing: &'static str) -> Attribute {
Attribute { name, missing: Some(missing) }
}
const fn defaulted(name: &'static str) -> Attribute {
Attribute { name, missing: None }
}
const VIEWPORT_WD: usize = 0;
const VIEWPORT_HT: usize = 1;
const MAX_FPS_ATTR: usize = 2;
const PACKET_SIZE: usize = 3;
const BITRATE: usize = 4;
const BIT_STREAM_FORMAT: usize = 5;
const MIN_FEC_PACKETS: usize = 6;
const VIDEO_QOS: usize = 7;
const PACKET_DURATION: usize = 8;
const AUDIO_QOS: usize = 9;
const MAX_REFERENCE_FRAMES: usize = 10;
const REF_PIC_INVALIDATION: usize = 11;
const DYNAMIC_RANGE_MODE: usize = 12;
const ENCODER_CSC_MODE: usize = 13;
const CHROMA_SAMPLING: usize = 14;
const ENCRYPTION_ENABLED: usize = 15;
const SURROUND_ENABLE: usize = 16;
const SURROUND_CHANNELS: usize = 17;
const SURROUND_MASK: usize = 18;
const AUDIO_QUALITY: usize = 19;
/// Every attribute read, in the order of the index constants above. The required set is the one a known host
/// refuses to stream without (`docs/PROTOCOL.md` 2.5 \[M\]); the others have the defaults documented on
/// [`StreamConfig`].
const ATTRIBUTES: [Attribute; 20] = [
required("x-nv-video[0].clientViewportWd", "announce: x-nv-video[0].clientViewportWd missing"),
required("x-nv-video[0].clientViewportHt", "announce: x-nv-video[0].clientViewportHt missing"),
required("x-nv-video[0].maxFPS", "announce: x-nv-video[0].maxFPS missing"),
required("x-nv-video[0].packetSize", "announce: x-nv-video[0].packetSize missing"),
required("x-ml-video.configuredBitrateKbps", "announce: x-ml-video.configuredBitrateKbps missing"),
required("x-nv-vqos[0].bitStreamFormat", "announce: x-nv-vqos[0].bitStreamFormat missing"),
required("x-nv-vqos[0].fec.minRequiredFecPackets", "announce: x-nv-vqos[0].fec.minRequiredFecPackets missing"),
required("x-nv-vqos[0].qosTrafficType", "announce: x-nv-vqos[0].qosTrafficType missing"),
required("x-nv-aqos.packetDuration", "announce: x-nv-aqos.packetDuration missing"),
required("x-nv-aqos.qosTrafficType", "announce: x-nv-aqos.qosTrafficType missing"),
defaulted("x-nv-video[0].maxNumReferenceFrames"),
defaulted("x-nv-video[0].refPicInvalidation"),
defaulted("x-nv-video[0].dynamicRangeMode"),
defaulted("x-nv-video[0].encoderCscMode"),
defaulted("x-ss-video[0].chromaSamplingType"),
defaulted("x-ss-general.encryptionEnabled"),
defaulted("x-nv-audio.surround.enable"),
defaulted("x-nv-audio.surround.numChannels"),
defaulted("x-nv-audio.surround.channelMask"),
defaulted("x-nv-audio.surround.AudioQuality"),
];
/// The values found, one slot per entry of [`ATTRIBUTES`].
struct Values<'a, 'b>(&'a [Option<&'b str>; ATTRIBUTES.len()]);
impl Values<'_, '_> {
/// The attribute's number in `lo..=hi`, or `default` when it is absent.
fn optional(&self, index: usize, default: u64, lo: u64, hi: u64) -> Result<u64> {
let name = ATTRIBUTES.get(index).map_or("announce attribute", |a| a.name);
match self.0.get(index).copied().flatten() {
None => Ok(default),
Some(text) => {
let value = parse_dec(name, text)?;
if value < lo || value > hi {
return Err(Error::UnexpectedValue { what: name, value });
}
Ok(value)
}
}
}
/// The attribute's number in `lo..=hi`; refused when absent.
fn required(&self, index: usize, lo: u64, hi: u64) -> Result<u64> {
if self.0.get(index).copied().flatten().is_none() {
let what = ATTRIBUTES.get(index).and_then(|a| a.missing).unwrap_or("announce: attribute missing");
return Err(malformed(what));
}
self.optional(index, 0, lo, hi)
}
}
/// A range-checked number into its field type (cannot fail after the range check; never panics either way).
fn narrow<T: TryFrom<u64>>(value: u64) -> Result<T> {
T::try_from(value).map_err(|_| Error::UnexpectedValue { what: "announce number", value })
}
@@ -0,0 +1,85 @@
//! The DESCRIBE answer (`docs/PROTOCOL.md` 2.3, 2.5): what the host offers, written as the SDP lines the client
//! reads with [`crate::rtsp::HostCapabilities::from_sdp`].
use crate::rtsp::sdp::{EncryptionFlags, FeatureFlags, MAX_OPUS_CONFIGS, OpusConfig, parse_surround_params};
use crate::util::{cap, malformed};
use crate::{Error, Result};
/// The `sprop-parameter-sets` line a known host sends; its value is not used by clients (`docs/PROTOCOL.md` 2.3).
const SPROP_LINE: &str = "sprop-parameter-sets=AAAAAU";
/// What the host offers: written into the DESCRIBE answer, and checked against the client's ANNOUNCE.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct HostOffer {
/// `x-ss-general.featureFlags` (pen/touch, controller touch).
pub feature_flags: FeatureFlags,
/// `x-ss-general.encryptionSupported`.
pub encryption_supported: EncryptionFlags,
/// `x-nv-video[0].refPicInvalidation:1`: the host can invalidate reference frames.
pub reference_frame_invalidation: bool,
/// H.264: `a=fmtp:96 packetization-mode=1`.
pub h264: bool,
/// HEVC. No DESCRIBE line is known for it (a host advertises it in serverinfo, `docs/PROTOCOL.md` 1.2, U25);
/// used only to check ANNOUNCE.
pub hevc: bool,
/// AV1: `a=rtpmap:98 AV1/90000`.
pub av1: bool,
/// HDR. No DESCRIBE line is known for it (serverinfo again); used only to check ANNOUNCE: without it, a
/// `dynamicRangeMode` other than 0 (SDR \[M\]) is refused.
pub hdr: bool,
/// 4:4:4 chroma. No DESCRIBE line is known; used only to check ANNOUNCE.
pub yuv444: bool,
/// One `a=fmtp:97 surround-params=…` line each, in order (at most
/// [`crate::rtsp::sdp::MAX_OPUS_CONFIGS`]). The mappings are written as given: whether a host must rotate the
/// 5.1/7.1 normal-quality mappings is UNKNOWN U26.
pub opus_configs: Vec<OpusConfig>,
}
/// Builds the DESCRIBE payload for `offer`, in the line order a known host uses (`docs/PROTOCOL.md` 2.5 \[M\]):
/// feature flags, encryption, `sprop-parameter-sets`, reference invalidation, AV1, H.264, then one
/// `surround-params` line per Opus configuration. CRLF line ends.
///
/// # Errors
/// [`Error::Malformed`] for an Opus configuration that the client's `surround-params` parser would refuse (more
/// than 8 channels, a mapping entry or count above 9, a wrong mapping length, no streams, more coupled streams than
/// streams); [`Error::TooLarge`] over [`crate::rtsp::sdp::MAX_OPUS_CONFIGS`]; [`Error::Unsupported`] when no codec
/// is offered.
pub fn build_describe(offer: &HostOffer) -> Result<Vec<u8>> {
if !(offer.h264 || offer.hevc || offer.av1) {
return Err(Error::Unsupported { what: "a video codec in the host offer" });
}
cap("describe opus configurations", MAX_OPUS_CONFIGS, offer.opus_configs.len())?;
let mut out = String::with_capacity(256 + 48 * offer.opus_configs.len());
let mut line = |text: &str| {
out.push_str(text);
out.push_str("\r\n");
};
line(&format!("a=x-ss-general.featureFlags:{}", offer.feature_flags.0));
line(&format!("a=x-ss-general.encryptionSupported:{}", offer.encryption_supported.0));
line(SPROP_LINE);
if offer.reference_frame_invalidation {
line("a=x-nv-video[0].refPicInvalidation:1");
}
if offer.av1 {
line("a=rtpmap:98 AV1/90000");
}
if offer.h264 {
line("a=fmtp:96 packetization-mode=1");
}
for config in &offer.opus_configs {
line(&format!("a=fmtp:97 surround-params={}", surround_digits(config)?));
}
Ok(out.into_bytes())
}
/// `surround-params` digits for `config` (`docs/PROTOCOL.md` 2.3): channel count, stream count, coupled count, then
/// one mapping digit per channel. The client's own parser checks the result, so nothing it refuses is written.
fn surround_digits(config: &OpusConfig) -> Result<String> {
let mut digits = String::with_capacity(3 + config.mapping.len());
for n in [config.channels, config.streams, config.coupled_streams].iter().chain(&config.mapping) {
let d = char::from_digit(u32::from(*n), 10).ok_or(malformed("surround-params: a value above 9"))?;
digits.push(d);
}
parse_surround_params(&digits)?;
Ok(digits)
}
+402
View File
@@ -0,0 +1,402 @@
//! The host's RTSP session (`docs/PROTOCOL.md` 2.2, 2.5), the mirror of [`super::client`]: OPTIONS → DESCRIBE →
//! SETUP audio, video and control (any order, each once) → ANNOUNCE → PLAY.
//!
//! The caller accepts TCP on the RTSP port, cuts each connection's bytes with [`super::RtspFramer::for_requests`],
//! feeds every whole request to [`RtspServer::handle_request`], writes the [`ServerReply`] back, and reads
//! [`ServerEvent`]s from [`RtspServer::poll_event`]. One [`RtspServer`] belongs to one launched session, not to one
//! TCP connection: a client may open a connection per request (UNKNOWN U5, `docs/PROTOCOL.md` 2.5), so the caller
//! routes every connection of that session to the same machine.
//!
//! Every request gets an answer. A request that is malformed, out of order or for another session gets an RTSP error
//! status and leaves the state unchanged; [`ServerReply::error`] says why, and the caller decides whether to close the
//! connection. Nothing here panics on any input.
mod announce;
mod describe;
pub use announce::{
ChromaSampling, MAX_ANNOUNCE_ATTRIBUTES, MAX_ANNOUNCE_BYTES, MAX_ANNOUNCE_LINE_BYTES, MAX_ANNOUNCE_LINES,
MAX_AUDIO_PACKET_DURATION_MS, MAX_BITRATE_KBPS, MAX_DIMENSION, MAX_FPS, MAX_PACKET_SIZE, MIN_PACKET_SIZE,
StreamConfig, SurroundSettings, parse_announce, write_announce,
};
pub use describe::{HostOffer, build_describe};
use std::collections::VecDeque;
use super::client::{StreamPorts, VideoCodec};
use super::sdp::EncryptionFlags;
use super::{MAX_RTSP_HEADERS, MAX_RTSP_MESSAGE_BYTES, Method, RtspRequest, RtspResponse, parse_request};
use crate::util::{hex_encode, malformed, parse_u32};
use crate::{Error, RandomSource, Result};
/// `timeout` of the `Session` header in SETUP answers, in seconds (`docs/PROTOCOL.md` 2.2 \[M\]).
pub const DEFAULT_SESSION_TIMEOUT_SECS: u32 = 90;
/// Random bytes in a session id (RFC 2326 section 3.4: at least eight octets, chosen at random); written as hex.
pub const SESSION_ID_BYTES: usize = 8;
/// How the host answers.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ServerConfig {
/// The UDP ports answered to SETUP audio, video and control (`Transport: server_port=<port>`).
pub ports: StreamPorts,
/// What DESCRIBE offers and ANNOUNCE is checked against.
pub offer: HostOffer,
/// Encryption the client must turn on in ANNOUNCE (Lumen: at least control V2); must be offered.
pub required_encryption: EncryptionFlags,
/// Refuse requests after the first SETUP that carry no `Session` header. Off by default: whether clients echo
/// it is UNKNOWN U5, and a known host does not read it (`docs/PROTOCOL.md` 2.5). A `Session` that is present is
/// always checked.
pub require_session_header: bool,
/// `timeout` in the `Session` header, seconds, 1.. ([`DEFAULT_SESSION_TIMEOUT_SECS`]).
pub session_timeout_secs: u32,
}
/// Which request the session expects next.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum RtspServerState {
/// OPTIONS.
Options,
/// DESCRIBE.
Describe,
/// SETUP of the streams not set up yet.
Setup,
/// ANNOUNCE.
Announce,
/// PLAY.
Play,
/// PLAY answered: the streams start. Only OPTIONS is still answered with 200.
Playing,
}
/// What the session tells the caller.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ServerEvent {
/// ANNOUNCE accepted: the stream settings the client asked for.
Announced(StreamConfig),
/// PLAY accepted: start the streams (video and audio wait for the client's PING, control for ENet).
PlayRequested,
}
/// The answer to one request.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ServerReply {
/// The whole RTSP answer to write to the connection.
pub bytes: Vec<u8>,
/// Its status code (200, or 400, 451, 454, 455 or 501).
pub status: u16,
/// Why the request was refused; `None` with status 200.
pub error: Option<Error>,
}
/// The host side of one session's RTSP negotiation.
#[derive(Debug)]
pub struct RtspServer {
config: ServerConfig,
session_id: String,
/// The DESCRIBE payload, built once from the offer.
describe: Vec<u8>,
state: RtspServerState,
/// SETUP answered for audio, video, control.
set_up: [bool; 3],
/// A SETUP was answered, so the session id is known to the client.
session_issued: bool,
announced: Option<StreamConfig>,
/// At most two events ever (one ANNOUNCE, one PLAY).
events: VecDeque<ServerEvent>,
}
/// `Public` in the OPTIONS answer (RFC 2326 section 10.1 example form).
const PUBLIC: &str = "OPTIONS, DESCRIBE, SETUP, ANNOUNCE, PLAY";
/// The streams of SETUP, in the order of `RtspServer::set_up` (`docs/PROTOCOL.md` 2.2).
const STREAMS: [&str; 3] = ["audio", "video", "control"];
/// The CSeq, headers and payload of a 200 answer.
type Answer = (u32, Vec<(String, String)>, Vec<u8>);
/// A refused request: the status, the CSeq to echo if one was readable, and why.
struct Refusal {
status: u16,
cseq: Option<u32>,
error: Error,
}
impl RtspServer {
/// Checks `config` and draws a fresh session id from `rng`.
///
/// # Errors
/// [`Error::Malformed`] for a zero port or session timeout, or required encryption the offer lacks; any error
/// of [`build_describe`] for the offer.
pub fn new(config: ServerConfig, rng: &mut dyn RandomSource) -> Result<Self> {
let p = config.ports;
if p.audio == 0 || p.video == 0 || p.control == 0 {
return Err(malformed("rtsp server: stream port 0"));
}
if config.session_timeout_secs == 0 {
return Err(malformed("rtsp server: session timeout 0"));
}
if !config.offer.encryption_supported.contains(config.required_encryption.0) {
return Err(malformed("rtsp server: required encryption is not offered"));
}
let describe = build_describe(&config.offer)?;
let mut id = [0u8; SESSION_ID_BYTES];
rng.fill(&mut id);
Ok(Self {
config,
session_id: hex_encode(&id),
describe,
state: RtspServerState::Options,
set_up: [false; 3],
session_issued: false,
announced: None,
events: VecDeque::new(),
})
}
/// Answers one whole request (see [`super::RtspFramer::for_requests`]). Never panics; a refusal leaves the
/// state as it was.
pub fn handle_request(&mut self, message: &[u8]) -> ServerReply {
match self.answer(message) {
Ok((cseq, headers, body)) => reply(200, Some(cseq), headers, body, None),
Err(r) => reply(r.status, r.cseq, Vec::new(), Vec::new(), Some(r.error)),
}
}
/// The headers and payload of a 200 answer, or why the request is refused.
fn answer(&mut self, message: &[u8]) -> core::result::Result<Answer, Refusal> {
let request = parse_request(message).map_err(|error| {
let status = if matches!(error, Error::UnexpectedValue { what: "rtsp method", .. }) { 501 } else { 400 };
Refusal { status, cseq: salvage_cseq(message), error }
})?;
let cseq = request_cseq(&request).map_err(|error| Refusal { status: 400, cseq: None, error })?;
let refuse = |status: u16, error: Error| Refusal { status, cseq: Some(cseq), error };
self.check_session(&request).map_err(|(status, error)| refuse(status, error))?;
let mut headers = Vec::new();
let mut body = Vec::new();
match request.method {
Method::Options => {
// OPTIONS may come at any time and changes nothing else (RFC 2326 section 10.1).
if self.state == RtspServerState::Options {
self.state = RtspServerState::Describe;
}
headers.push(("Public".to_owned(), PUBLIC.to_owned()));
}
Method::Describe => {
self.expect(RtspServerState::Describe, "DESCRIBE after OPTIONS").map_err(|e| refuse(455, e))?;
headers.push(("Content-Type".to_owned(), "application/sdp".to_owned()));
body.clone_from(&self.describe);
self.state = RtspServerState::Setup;
}
Method::Setup => {
self.expect(RtspServerState::Setup, "SETUP after DESCRIBE").map_err(|e| refuse(455, e))?;
// A Transport header must be present; its value is not interpreted (`docs/PROTOCOL.md` 2.2 [M]).
if request.header("Transport").is_none() {
return Err(refuse(400, malformed("rtsp SETUP without Transport")));
}
let index = setup_stream(&request.target).map_err(|e| refuse(400, e))?;
let port = self.port(index).ok_or(refuse(400, malformed("rtsp SETUP stream")))?;
let slot = self.set_up.get_mut(index).ok_or(refuse(400, malformed("rtsp SETUP stream")))?;
if *slot {
return Err(refuse(455, Error::State { expected: "one SETUP per stream" }));
}
*slot = true;
self.session_issued = true;
if self.set_up.iter().all(|done| *done) {
self.state = RtspServerState::Announce;
}
let session = format!("{};timeout = {}", self.session_id, self.config.session_timeout_secs);
headers.push(("Session".to_owned(), session));
headers.push(("Transport".to_owned(), format!("server_port={port}")));
}
Method::Announce => {
self.expect(RtspServerState::Announce, "ANNOUNCE after the three SETUPs")
.map_err(|e| refuse(455, e))?;
let config = parse_announce(&request.body).map_err(|e| refuse(400, e))?;
self.check_offer(&config).map_err(|e| refuse(451, e))?;
self.events.push_back(ServerEvent::Announced(config.clone()));
self.announced = Some(config);
self.state = RtspServerState::Play;
}
Method::Play => {
self.expect(RtspServerState::Play, "PLAY after ANNOUNCE").map_err(|e| refuse(455, e))?;
self.events.push_back(ServerEvent::PlayRequested);
self.state = RtspServerState::Playing;
}
}
Ok((cseq, headers, body))
}
fn expect(&self, state: RtspServerState, expected: &'static str) -> Result<()> {
if self.state == state { Ok(()) } else { Err(Error::State { expected }) }
}
/// The UDP port answered for stream `index` (audio, video, control).
fn port(&self, index: usize) -> Option<u16> {
let p = self.config.ports;
[p.audio, p.video, p.control].get(index).copied()
}
/// `Session` checks (`docs/PROTOCOL.md` 2.5): a present id must be the one issued in SETUP; a missing one is
/// refused only when the config asks for it.
fn check_session(&self, request: &RtspRequest) -> core::result::Result<(), (u16, Error)> {
let mut ids = request
.headers
.iter()
.filter(|(n, _)| n.eq_ignore_ascii_case("session"))
.map(|(_, v)| v.split(';').next().unwrap_or("").trim_matches([' ', '\t']));
let first = ids.next();
if let Some(id) = first
&& ids.any(|other| other != id)
{
return Err((400, malformed("rtsp: two different Session headers")));
}
match first {
Some(id) if !self.session_issued || id != self.session_id => {
Err((454, malformed("rtsp: Session is not this session's id")))
}
None if self.config.require_session_header && self.session_issued && request.method != Method::Options => {
Err((454, malformed("rtsp: Session missing")))
}
_ => Ok(()),
}
}
/// What ANNOUNCE asks for must be in the offer.
fn check_offer(&self, config: &StreamConfig) -> Result<()> {
let offer = &self.config.offer;
let codec_offered = match config.codec {
VideoCodec::H264 => offer.h264,
VideoCodec::Hevc => offer.hevc,
VideoCodec::Av1 => offer.av1,
};
if !codec_offered {
return Err(Error::Unsupported { what: "the requested video codec" });
}
if config.encryption.0 & !offer.encryption_supported.0 != 0 {
return Err(Error::Unsupported { what: "encryption the host did not offer" });
}
if !config.encryption.contains(self.config.required_encryption.0) {
return Err(Error::Unsupported { what: "a stream without the encryption the host requires" });
}
// 0 is SDR (`docs/PROTOCOL.md` 2.5 [M]); any other value is "not SDR", without a settled meaning (U6).
if config.dynamic_range_mode != 0 && !offer.hdr {
return Err(Error::Unsupported { what: "HDR" });
}
if config.chroma == ChromaSampling::Yuv444 && !offer.yuv444 {
return Err(Error::Unsupported { what: "4:4:4 chroma" });
}
Ok(())
}
/// The next event, if any.
pub fn poll_event(&mut self) -> Option<ServerEvent> {
self.events.pop_front()
}
/// Which request the session expects next.
#[must_use]
pub const fn state(&self) -> RtspServerState {
self.state
}
/// The session id sent in SETUP answers.
#[must_use]
pub fn session_id(&self) -> &str {
&self.session_id
}
/// The accepted ANNOUNCE, once there is one.
#[must_use]
pub const fn announced(&self) -> Option<&StreamConfig> {
self.announced.as_ref()
}
/// The configuration the session answers with.
#[must_use]
pub const fn config(&self) -> &ServerConfig {
&self.config
}
}
/// The reason phrase of each status the session sends (RFC 2326 section 7.1.1).
const fn reason(status: u16) -> &'static str {
match status {
200 => "OK",
400 => "Bad Request",
451 => "Parameter Not Understood",
454 => "Session Not Found",
455 => "Method Not Valid in This State",
501 => "Not Implemented",
_ => "Internal Server Error",
}
}
/// Builds the answer: `CSeq` first (when known), the given headers, then `Content-Length` (always, so the client's
/// framer never has to wait for the connection to close, `docs/PROTOCOL.md` 2.1 U5).
fn reply(
status: u16,
cseq: Option<u32>,
extra: Vec<(String, String)>,
body: Vec<u8>,
error: Option<Error>,
) -> ServerReply {
let mut headers = Vec::with_capacity(extra.len() + 2);
if let Some(c) = cseq {
headers.push(("CSeq".to_owned(), c.to_string()));
}
headers.extend(extra);
headers.push(("Content-Length".to_owned(), body.len().to_string()));
match (RtspResponse { status, reason: reason(status).to_owned(), headers, body }).encode() {
Ok(bytes) => ServerReply { bytes, status, error },
// Only an answer over the message cap could fail, and none is that large; answer 500 rather than panic.
Err(e) => ServerReply {
bytes: b"RTSP/1.0 500 Internal Server Error\r\nContent-Length: 0\r\n\r\n".to_vec(),
status: 500,
error: Some(e),
},
}
}
/// The request's CSeq: present, plain decimal `u32`, every copy equal.
fn request_cseq(request: &RtspRequest) -> Result<u32> {
let mut found = None;
for (_, v) in request.headers.iter().filter(|(n, _)| n.eq_ignore_ascii_case("cseq")) {
let n = parse_u32("rtsp CSeq", v)?;
if found.is_some_and(|f| f != n) {
return Err(malformed("rtsp: two different CSeq values"));
}
found = Some(n);
}
found.ok_or(malformed("rtsp request without CSeq"))
}
/// The CSeq of a request that did not parse, if a header line says it plainly, so the refusal can still echo it.
/// Reads at most the header section, at most [`MAX_RTSP_HEADERS`] lines, and allocates nothing.
fn salvage_cseq(message: &[u8]) -> Option<u32> {
let head = message.get(..message.len().min(MAX_RTSP_MESSAGE_BYTES))?;
for raw in head.split(|&b| b == b'\n').skip(1).take(MAX_RTSP_HEADERS) {
let line = raw.strip_suffix(b"\r").unwrap_or(raw);
if line.is_empty() {
break;
}
let Ok(text) = core::str::from_utf8(line) else { continue };
if let Some((name, value)) = text.split_once(':')
&& name.eq_ignore_ascii_case("cseq")
{
return parse_u32("rtsp CSeq", value.trim_matches([' ', '\t'])).ok();
}
}
None
}
/// The stream a SETUP target names: exactly one `streamid=` followed by `audio`, `video` or `control`, ended by
/// `/`, `?`, `&`, `;` or the end (`docs/PROTOCOL.md` 2.2 \[M\], 2.5). Index into [`STREAMS`].
fn setup_stream(target: &str) -> Result<usize> {
let mut parts = target.split("streamid=");
parts.next();
let after = parts.next().ok_or(malformed("rtsp SETUP target without streamid"))?;
if parts.next().is_some() {
return Err(malformed("rtsp SETUP target with two streamid"));
}
let name = after.split(['/', '?', '&', ';']).next().unwrap_or("");
STREAMS.iter().position(|s| *s == name).ok_or(malformed("rtsp SETUP streamid"))
}
+34
View File
@@ -60,6 +60,15 @@ fn lying_inputs() -> Vec<Case> {
b"ANNOUNCE x RTSP/1.0\r\nCSeq: 1\r\nContent-Length: 4294967295\r\n\r\nabc".to_vec(),
|b| common::implemented(&domistream::rtsp::parse_request(b)),
));
v.push((
"rtsp server",
b"ANNOUNCE x RTSP/1.0\r\nCSeq: 1\r\nContent-Length: 4294967295\r\n\r\nabc".to_vec(),
rtsp_server_answers,
));
// ANNOUNCE: a number far past any range, then more unknown attributes than the cap allows.
let mut announce = b"a=x-nv-video[0].clientViewportWd:99999999999999999999999999999999\n".to_vec();
announce.extend_from_slice(&b"a=u:1\n".repeat(600));
v.push(("announce", announce, |b| common::implemented(&domistream::rtsp::server::parse_announce(b))));
v.push(("rtsp framer", rtsp, |b| {
let mut f = domistream::rtsp::RtspFramer::new();
let pushed = f.push(b);
@@ -129,6 +138,29 @@ fn lying_inputs() -> Vec<Case> {
v
}
/// A fresh host RTSP session answers `b`; false only for an `Unimplemented` answer.
fn rtsp_server_answers(b: &[u8]) -> bool {
let config = domistream::rtsp::ServerConfig {
ports: domistream::rtsp::StreamPorts { audio: 48000, video: 47998, control: 47999 },
offer: domistream::rtsp::HostOffer {
feature_flags: domistream::rtsp::sdp::FeatureFlags(3),
encryption_supported: domistream::rtsp::EncryptionFlags(7),
reference_frame_invalidation: true,
h264: true,
hevc: true,
av1: true,
hdr: false,
yuv444: false,
opus_configs: vec![domistream::rtsp::OpusConfig::stereo()],
},
required_encryption: domistream::rtsp::EncryptionFlags(1),
require_session_header: false,
session_timeout_secs: 90,
};
let Ok(mut s) = domistream::rtsp::RtspServer::new(config, &mut common::SeqRng::new(3)) else { return false };
s.handle_request(b).error != Some(domistream::Error::Unimplemented)
}
/// Stateful receivers: the bound is their caps (frames or blocks in flight), never a claimed size.
fn depacketizer_checks() {
use domistream::video::{MAX_FRAME_BYTES, MAX_FRAMES_IN_FLIGHT, VideoConfig, VideoDepacketizer};
@@ -225,6 +257,8 @@ fn parsers_never_allocate_past_their_caps() {
("rtsp response", |b| common::implemented(&domistream::rtsp::parse_response(b))),
("rtsp request", |b| common::implemented(&domistream::rtsp::parse_request(b))),
("sdp", |b| common::implemented(&domistream::rtsp::sdp::parse_sdp(b))),
("announce", |b| common::implemented(&domistream::rtsp::server::parse_announce(b))),
("rtsp server", rtsp_server_answers),
("enet", |b| common::implemented(&domistream::enet::protocol::parse_datagram(b))),
("control frame", |b| common::implemented(&domistream::control::parse_encrypted_frame(b))),
("control message", |b| common::implemented(&domistream::control::parse_host_message(b))),
+157
View File
@@ -0,0 +1,157 @@
//! "Caps every length before it allocates", for the host side of ENet and control: a counting global allocator
//! (`peak_alloc`) checks that lying fragment lengths and lying message lengths never reserve what they claim, and
//! that arbitrary input stays within a bound tied to the input and the caps.
//!
//! The counters are process-wide, so this file holds exactly one #[test] that runs everything in sequence.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::indexing_slicing, missing_docs)]
mod common;
use core::time::Duration;
use domistream::Instant;
use domistream::control::{ControlCipher, ControlHost, ControlHostConfig, Direction, parse_client_message};
use domistream::enet::protocol::{Command, CommandBody, ConnectParams, Datagram, NO_PEER_ID, encode_datagram};
use domistream::enet::{EnetHostConfig, EnetHostPeer, MAX_PACKET_BYTES};
use peak_alloc::PeakAlloc;
use proptest::prelude::*;
use proptest::test_runner::{Config, TestRunner};
#[global_allocator]
static ALLOC: PeakAlloc = PeakAlloc;
fn peak_of<R>(f: impl FnOnce() -> R) -> usize {
ALLOC.reset_peak_usage();
let before = ALLOC.current_usage();
let r = f();
let peak = ALLOC.peak_usage();
drop(r);
peak.saturating_sub(before)
}
fn budget(input: usize) -> usize {
64 * input + 256 * 1024
}
fn enet_config() -> EnetHostConfig {
EnetHostConfig {
peer_id: 1,
channel_limit: 4,
mtu: 1400,
ping_interval: Duration::from_millis(500),
timeout: Duration::from_secs(10),
}
}
fn connect() -> Vec<u8> {
let params = ConnectParams {
outgoing_peer_id: 0,
incoming_session_id: 0xFF,
outgoing_session_id: 0xFF,
mtu: 1400,
window_size: 65536,
channel_count: 4,
incoming_bandwidth: 0,
outgoing_bandwidth: 0,
packet_throttle_interval: 5000,
packet_throttle_acceleration: 2,
packet_throttle_deceleration: 2,
connect_id: 1,
};
encode_datagram(&Datagram {
peer_id: NO_PEER_ID,
session_id: 0,
sent_time: Some(0),
commands: vec![Command {
acknowledge: true,
channel_id: 0xFF,
reliable_sequence: 1,
body: CommandBody::Connect { params, data: 0 },
}],
})
.unwrap()
}
/// A connected host peer (verify acknowledged).
fn connected() -> EnetHostPeer {
let mut h = EnetHostPeer::accept(enet_config(), Instant::ZERO, &connect()).unwrap();
while h.poll_transmit(Instant::ZERO).is_some() {}
let ack = encode_datagram(&Datagram {
peer_id: 1,
session_id: 0,
sent_time: Some(1),
commands: vec![Command {
acknowledge: false,
channel_id: 0xFF,
reliable_sequence: 1,
body: CommandBody::Acknowledge { received_reliable_sequence: 1, received_sent_time: 0 },
}],
})
.unwrap();
h.handle_datagram(Instant::from_micros(1000), &ack).unwrap();
h
}
#[test]
fn host_parsers_never_allocate_past_their_caps() {
// Fragments of 4 billion pieces and gigabyte totals on every channel and sequence: at most the reassembly cap.
let used = peak_of(|| {
let mut h = connected();
for i in 0..256u16 {
let mut d = vec![0x80, 0x01, 0x00, 0x02];
d.extend_from_slice(&[0x88, (i % 4) as u8]);
d.extend_from_slice(&(i + 1).to_be_bytes());
d.extend_from_slice(&(i + 1).to_be_bytes()); // start sequence
d.extend_from_slice(&4u16.to_be_bytes());
d.extend_from_slice(&u32::MAX.to_be_bytes());
d.extend_from_slice(&0u32.to_be_bytes());
d.extend_from_slice(&(MAX_PACKET_BYTES as u32).to_be_bytes());
d.extend_from_slice(&0u32.to_be_bytes());
d.extend_from_slice(&[1, 2, 3, 4]);
let _ = h.handle_datagram(Instant::from_micros(2000), &d);
let mut lie = d.clone();
lie[20..24].copy_from_slice(&u32::MAX.to_be_bytes()); // total length
let _ = h.handle_datagram(Instant::from_micros(2000), &lie);
}
h
});
assert!(used <= 4 * MAX_PACKET_BYTES + 512 * 1024, "enet host: {used} bytes at peak");
// A control message whose length field claims 64 KiB.
let lie = [0x01, 0x02, 0xFF, 0xFF, 1, 2, 3];
let used = peak_of(|| common::implemented(&parse_client_message(&lie)));
assert!(used <= budget(lie.len()), "client message: {used}");
// The control host fed sealed frames that lie inside.
let used = peak_of(|| {
let config = ControlHostConfig { enet: enet_config(), rikey: [3; 16], stop_timeout: None };
let mut h = ControlHost::accept(config, Instant::ZERO, &connect()).unwrap();
let cipher = ControlCipher::new([3; 16]);
for seq in 0..64u32 {
let frame =
cipher.seal(seq, Direction::ClientToHost, &[0x06, 0x02, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]).unwrap();
let mut d = vec![0x80, 0x01, 0x00, 0x02, 0x86, 0x00];
d.extend_from_slice(&((seq + 1) as u16).to_be_bytes());
d.extend_from_slice(&(frame.len() as u16).to_be_bytes());
d.extend_from_slice(&frame);
let _ = h.handle_datagram(Instant::from_micros(2000), &d);
while h.poll_event().is_some() {}
}
h
});
assert!(used <= 1024 * 1024, "control host: {used}");
// Arbitrary inputs.
let mut runner = TestRunner::new(Config { cases: 300, ..Config::default() });
runner
.run(&proptest::collection::vec(any::<u8>(), 0..1500), |data| {
let used = peak_of(|| common::implemented(&parse_client_message(&data)));
prop_assert!(used <= budget(data.len()), "client message: {} for {}", used, data.len());
let used = peak_of(|| common::implemented(&EnetHostPeer::accept(enet_config(), Instant::ZERO, &data)));
prop_assert!(used <= budget(data.len()), "accept: {} for {}", used, data.len());
Ok(())
})
.unwrap();
}
+2
View File
@@ -7,6 +7,8 @@ use std::collections::HashMap;
use domistream::RandomSource;
pub mod wire;
// ------------------------------------------------------------------------------------------------ assertions
/// Asserts that `$e` is `Err` matching `$p` (an `Error` pattern), printing the actual value otherwise.
+197
View File
@@ -0,0 +1,197 @@
//! An in-memory, simulated-time network for client-against-host tests: two one-way links with optional loss,
//! duplication and reordering (all from a seeded [`SeqRng`], so every run is the same), and a driver that shuttles
//! datagrams between two sans-I/O endpoints, advancing the clock to the next delivery or deadline.
use domistream::Instant;
use super::SeqRng;
/// One side of a session, as the wire drives it.
pub trait Endpoint {
/// The next datagram this side wants to send.
fn transmit(&mut self, now: Instant) -> Option<Vec<u8>>;
/// A datagram arrived.
fn receive(&mut self, now: Instant, datagram: &[u8]);
/// When this side wants [`Endpoint::tick`].
fn deadline(&self) -> Option<Instant>;
/// Timers.
fn tick(&mut self, now: Instant);
}
/// What a one-way link does to datagrams. Rates are per mille.
#[derive(Clone, Copy, Debug, Default)]
pub struct Impair {
pub loss: u32,
pub duplicate: u32,
/// Chance that a datagram is held back by up to `reorder_ms` extra.
pub reorder: u32,
pub reorder_ms: u64,
/// Fixed one-way latency, ms.
pub latency_ms: u64,
}
impl Impair {
pub fn clean(latency_ms: u64) -> Self {
Self { latency_ms, ..Self::default() }
}
pub fn lossy(loss: u32, latency_ms: u64) -> Self {
Self { loss, duplicate: 20, reorder: 100, reorder_ms: 30, latency_ms }
}
}
/// A one-way link.
#[derive(Debug)]
pub struct Link {
pub impair: Impair,
rng: SeqRng,
queue: Vec<(u64, u64, Vec<u8>)>,
order: u64,
/// Datagrams handed to the link, and the ones it dropped.
pub sent: usize,
pub lost: usize,
/// When set, every datagram is dropped (a peer that vanished).
pub cut: bool,
}
impl Link {
pub fn new(impair: Impair, seed: u64) -> Self {
Self { impair, rng: SeqRng::new(seed), queue: Vec::new(), order: 0, sent: 0, lost: 0, cut: false }
}
fn chance(&mut self, per_mille: u32) -> bool {
per_mille > 0 && (self.rng.below(1000) as u32) < per_mille
}
pub fn send(&mut self, now_ms: u64, datagram: Vec<u8>) {
self.sent += 1;
if self.cut || self.chance(self.impair.loss) {
self.lost += 1;
return;
}
let copies = if self.chance(self.impair.duplicate) { 2 } else { 1 };
for _ in 0..copies {
let mut due = now_ms + self.impair.latency_ms;
if self.impair.reorder_ms > 0 && self.chance(self.impair.reorder) {
due += 1 + self.rng.below(self.impair.reorder_ms as usize) as u64;
}
self.order += 1;
self.queue.push((due, self.order, datagram.clone()));
}
}
pub fn next_due(&self) -> Option<u64> {
self.queue.iter().map(|(d, _, _)| *d).min()
}
/// Datagrams due by `now_ms`, in delivery order.
pub fn due(&mut self, now_ms: u64) -> Vec<Vec<u8>> {
let mut ready: Vec<(u64, u64, Vec<u8>)> = Vec::new();
let mut rest = Vec::new();
for item in self.queue.drain(..) {
if item.0 <= now_ms { ready.push(item) } else { rest.push(item) }
}
self.queue = rest;
ready.sort_by_key(|(d, o, _)| (*d, *o));
ready.into_iter().map(|(_, _, d)| d).collect()
}
}
pub fn ms(t: Instant) -> u64 {
t.as_micros().div_ceil(1000)
}
pub fn at(ms: u64) -> Instant {
Instant::from_micros(ms * 1000)
}
/// A client, a host and the two links between them.
pub struct Wire<C: Endpoint, H: Endpoint> {
pub client: C,
pub host: H,
pub to_host: Link,
pub to_client: Link,
pub now_ms: u64,
}
impl<C: Endpoint, H: Endpoint> Wire<C, H> {
pub fn new(client: C, host: H, to_host: Impair, to_client: Impair, seed: u64) -> Self {
Self {
client,
host,
to_host: Link::new(to_host, seed ^ 0xC2C2),
to_client: Link::new(to_client, seed ^ 0x4848),
now_ms: 0,
}
}
/// Moves everything that can move at the current time (transmit, deliver, timers), until quiet.
pub fn settle(&mut self) {
for _ in 0..10_000 {
let now = at(self.now_ms);
let mut moved = false;
if self.client.deadline().is_some_and(|t| t <= now) {
self.client.tick(now);
}
if self.host.deadline().is_some_and(|t| t <= now) {
self.host.tick(now);
}
while let Some(d) = self.client.transmit(now) {
self.to_host.send(self.now_ms, d);
moved = true;
}
while let Some(d) = self.host.transmit(now) {
self.to_client.send(self.now_ms, d);
moved = true;
}
for d in self.to_host.due(self.now_ms) {
self.host.receive(now, &d);
moved = true;
}
for d in self.to_client.due(self.now_ms) {
self.client.receive(now, &d);
moved = true;
}
if !moved {
return;
}
}
panic!("the wire never settles at {} ms", self.now_ms);
}
/// The next moment anything happens, if anything ever does.
pub fn next_event(&self) -> Option<u64> {
[
self.to_host.next_due(),
self.to_client.next_due(),
self.client.deadline().map(ms),
self.host.deadline().map(ms),
]
.into_iter()
.flatten()
.min()
}
/// Runs until `done` holds or `limit_ms` passes; returns whether `done` held.
pub fn run_until(&mut self, limit_ms: u64, mut done: impl FnMut(&mut Self) -> bool) -> bool {
loop {
self.settle();
if done(self) {
return true;
}
let next = self.next_event().unwrap_or(u64::MAX).max(self.now_ms + 1);
if next > limit_ms {
self.now_ms = limit_ms.max(self.now_ms);
self.settle();
return done(self);
}
self.now_ms = next;
}
}
/// Runs for `duration_ms` of simulated time.
pub fn run_for(&mut self, duration_ms: u64) {
let end = self.now_ms + duration_ms;
self.run_until(end, |w| w.now_ms >= end);
}
}
+786
View File
@@ -0,0 +1,786 @@
//! The host side of the control stream (`docs/PROTOCOL.md` 3.2, 3.3, `control::host`): our own [`ControlStream`]
//! (and a probe-style client for the messages whose bodies are empty) talks to a [`ControlHost`] over the in-memory
//! wire. Input arrives typed and byte-identical, host messages reach the client, replays and forgeries are dropped,
//! and the stop deadline ends a session without pings.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::indexing_slicing, missing_docs)]
mod common;
use core::time::Duration;
use common::wire::{Endpoint, Impair, Wire, at};
use domistream::control::host::{DEFAULT_STOP_TIMEOUT, TERMINATION_GRACEFUL};
use domistream::control::message::{HdrMetadata, MAX_MESSAGE_BYTES, MotionKind, encode_client_message};
use domistream::control::{
ClientControlMessage, ClientMessage, ControlCipher, ControlConfig, ControlEvent, ControlHost, ControlHostConfig,
ControlHostEvent, ControlStream, Direction, HostMessage, StopDeadline, encode_host_message, parse_client_message,
parse_host_message,
};
use domistream::enet::{Delivery, EnetClient, EnetConfig, EnetEvent, EnetHostConfig, EnetHostState, EnetState};
use domistream::input::{
ButtonFlags, ControllerCapabilities, ControllerKind, GamepadState, InputEvent, MouseButton, encode_input,
};
use domistream::{Error, Instant};
use proptest::prelude::*;
const KEY: [u8; 16] = *b"lumen-control-k!";
fn enet_client_config() -> EnetConfig {
EnetConfig {
channel_count: 1,
mtu: 1400,
connect_data: 0,
ping_interval: Duration::from_millis(500),
timeout: Duration::from_secs(30),
}
}
fn host_config(stop_timeout: Option<Duration>) -> ControlHostConfig {
ControlHostConfig {
enet: EnetHostConfig {
peer_id: 0,
channel_limit: 0x30,
mtu: 1400,
ping_interval: Duration::from_millis(500),
timeout: Duration::from_secs(30),
},
rikey: KEY,
stop_timeout,
}
}
fn msg(ty: u16, body: &[u8]) -> Vec<u8> {
let mut m = ty.to_le_bytes().to_vec();
m.extend_from_slice(&(body.len() as u16).to_le_bytes());
m.extend_from_slice(body);
m
}
// ================================================================================================ endpoints
/// Our client as it ships: [`ControlStream`].
struct StreamClient {
stream: ControlStream,
events: Vec<ControlEvent>,
}
impl StreamClient {
fn new(seed: u64) -> Self {
let config =
ControlConfig { enet: enet_client_config(), rikey: KEY, ping_interval: Duration::from_millis(100) };
Self {
stream: ControlStream::connect(config, Instant::ZERO, &mut common::SeqRng::new(seed)).unwrap(),
events: Vec::new(),
}
}
fn drain(&mut self) {
while let Some(e) = self.stream.poll_event() {
self.events.push(e);
}
}
fn messages(&self) -> Vec<HostMessage> {
self.events
.iter()
.filter_map(|e| match e {
ControlEvent::Message(m) => Some(m.clone()),
_ => None,
})
.collect()
}
}
impl Endpoint for StreamClient {
fn transmit(&mut self, now: Instant) -> Option<Vec<u8>> {
self.stream.poll_transmit(now)
}
fn receive(&mut self, now: Instant, datagram: &[u8]) {
let _ = self.stream.handle_datagram(now, datagram);
self.drain();
}
fn deadline(&self) -> Option<Instant> {
self.stream.poll_timeout()
}
fn tick(&mut self, now: Instant) {
self.stream.handle_timeout(now).unwrap();
self.drain();
}
}
/// A probe-style client: ENet plus the cipher, sending any plaintext or any frame (PROTOCOL.md 3.3: Moonshine
/// reads no body from START_B, PERIODIC_PING or the IDR request, so they go with empty bodies).
struct RawClient {
enet: EnetClient,
cipher: ControlCipher,
next_sequence: u32,
/// Host frames opened: (sequence, plaintext).
opened: Vec<(u32, Vec<u8>)>,
events: Vec<EnetEvent>,
}
impl RawClient {
fn new(seed: u64) -> Self {
Self {
enet: EnetClient::connect(enet_client_config(), Instant::ZERO, &mut common::SeqRng::new(seed)).unwrap(),
cipher: ControlCipher::new(KEY),
next_sequence: 0,
opened: Vec::new(),
events: Vec::new(),
}
}
fn send_frame(&mut self, now: Instant, frame: Vec<u8>) {
self.enet.send(now, 0, Delivery::Reliable, &frame).unwrap();
}
fn seal(&mut self, plain: &[u8]) -> Vec<u8> {
let f = self.cipher.seal(self.next_sequence, Direction::ClientToHost, plain).unwrap();
self.next_sequence += 1;
f
}
fn send_plain(&mut self, now: Instant, plain: &[u8]) {
let f = self.seal(plain);
self.send_frame(now, f);
}
fn drain(&mut self) {
while let Some(e) = self.enet.poll_event() {
if let EnetEvent::Received { data, .. } = &e {
self.opened.push(self.cipher.open(Direction::HostToClient, data).expect("host frames open with 'H'"));
}
self.events.push(e);
}
}
}
impl Endpoint for RawClient {
fn transmit(&mut self, now: Instant) -> Option<Vec<u8>> {
self.enet.poll_transmit(now)
}
fn receive(&mut self, now: Instant, datagram: &[u8]) {
let _ = self.enet.handle_datagram(now, datagram);
self.drain();
}
fn deadline(&self) -> Option<Instant> {
self.enet.poll_timeout()
}
fn tick(&mut self, now: Instant) {
self.enet.handle_timeout(now).unwrap();
self.drain();
}
}
/// The caller of the control host (one client address).
struct Host {
config: ControlHostConfig,
host: Option<ControlHost>,
events: Vec<ControlHostEvent>,
/// When each PingTimedOut was reported, ms.
ping_timeouts: Vec<u64>,
}
impl Host {
fn new(config: ControlHostConfig) -> Self {
Self { config, host: None, events: Vec::new(), ping_timeouts: Vec::new() }
}
fn h(&mut self) -> &mut ControlHost {
self.host.as_mut().expect("accepted")
}
fn drain(&mut self, now: Instant) {
if let Some(h) = self.host.as_mut() {
while let Some(e) = h.poll_event() {
if e == ControlHostEvent::PingTimedOut {
self.ping_timeouts.push(now.as_micros() / 1000);
}
self.events.push(e);
}
}
}
fn messages(&self) -> Vec<ClientControlMessage> {
self.events
.iter()
.filter_map(|e| match e {
ControlHostEvent::Message(m) => Some(m.clone()),
_ => None,
})
.collect()
}
/// Events after the first `Connected`, without it.
fn take(&mut self) -> Vec<ControlHostEvent> {
let out: Vec<ControlHostEvent> = self.events.drain(..).filter(|e| *e != ControlHostEvent::Connected).collect();
out
}
fn connected(&self) -> bool {
self.host.as_ref().is_some_and(|h| h.enet().state() == EnetHostState::Connected)
}
}
impl Endpoint for Host {
fn transmit(&mut self, now: Instant) -> Option<Vec<u8>> {
self.host.as_mut()?.poll_transmit(now)
}
fn receive(&mut self, now: Instant, datagram: &[u8]) {
match self.host.as_mut() {
None => {
if let Ok(h) = ControlHost::accept(self.config.clone(), now, datagram) {
self.host = Some(h);
}
}
Some(h) => {
let _ = h.handle_datagram(now, datagram);
}
}
self.drain(now);
}
fn deadline(&self) -> Option<Instant> {
self.host.as_ref()?.poll_timeout()
}
fn tick(&mut self, now: Instant) {
if let Some(h) = self.host.as_mut() {
h.handle_timeout(now).unwrap();
}
self.drain(now);
}
}
fn stream_session(to_host: Impair, to_client: Impair, stop: Option<Duration>, seed: u64) -> Wire<StreamClient, Host> {
let mut w = Wire::new(StreamClient::new(seed), Host::new(host_config(stop)), to_host, to_client, seed);
assert!(
w.run_until(30_000, |w| w.host.connected() && w.client.events.contains(&ControlEvent::Connected)),
"no connection"
);
assert_eq!(w.host.events, vec![ControlHostEvent::Connected]);
w.host.events.clear();
w
}
fn raw_session(stop: Option<Duration>, seed: u64) -> Wire<RawClient, Host> {
let mut w = Wire::new(RawClient::new(seed), Host::new(host_config(stop)), Impair::clean(3), Impair::clean(3), seed);
assert!(w.run_until(5_000, |w| w.host.connected() && w.client.enet.state() == EnetState::Connected));
assert_eq!(w.host.events, vec![ControlHostEvent::Connected]);
w.host.events.clear();
w
}
// ================================================================================================ input
fn every_input() -> Vec<InputEvent> {
vec![
InputEvent::MouseMoveRel { dx: -1, dy: 0 },
InputEvent::MouseMoveRel { dx: i16::MAX, dy: i16::MIN },
InputEvent::MouseMoveAbs { x: 1464, y: 528, width: 1919, height: 1079 },
InputEvent::MouseButton { pressed: true, button: MouseButton::Left },
InputEvent::MouseButton { pressed: false, button: MouseButton::Extra },
InputEvent::Key { pressed: true, flags: 0, key_code: 0x80A4, modifiers: 0x04 },
InputEvent::Key { pressed: false, flags: 0, key_code: 0x41, modifiers: 0 },
InputEvent::Scroll { amount: -120 },
InputEvent::HScroll { amount: 30 },
InputEvent::Gamepad(GamepadState {
controller: 0,
active_mask: 1,
buttons: ButtonFlags(0x0010_1001),
left_trigger: 0x10,
right_trigger: 0xFF,
left_stick_x: -32768,
left_stick_y: 32767,
right_stick_x: 5,
right_stick_y: -104,
}),
InputEvent::ControllerArrival {
controller: 1,
kind: ControllerKind::PlayStation,
capabilities: ControllerCapabilities(0x03),
supported_buttons: ButtonFlags(0x000F_F7FF),
},
]
}
#[test]
fn input_arrives_typed_and_byte_identical() {
let mut w = stream_session(Impair::clean(4), Impair::clean(4), None, 1);
let t = at(w.now_ms);
let mut sent = Vec::new();
for e in every_input() {
let m = ClientMessage::Input(e);
w.client.stream.send(t, &m).unwrap();
sent.push(m);
}
let invalidate = ClientMessage::InvalidateRefFrames { first: 17, last: 0xFFFF_FFF0 };
w.client.stream.send(t, &invalidate).unwrap();
w.run_for(500);
let got = w.host.messages();
assert_eq!(got.len(), sent.len() + 1, "{got:?}");
for (m, g) in sent.iter().zip(&got) {
let ClientMessage::Input(want) = m else { unreachable!() };
assert_eq!(g, &ClientControlMessage::Input(want.clone()));
let ClientControlMessage::Input(e) = g else { unreachable!() };
assert_eq!(encode_input(e).unwrap(), encode_client_message(m).unwrap(), "byte-identical: {e:?}");
}
assert_eq!(got[sent.len()], ClientControlMessage::InvalidateRefFrames { first: 17, last: 0xFFFF_FFF0 });
assert!(!w.host.events.contains(&ControlHostEvent::Dropped));
}
#[test]
fn input_vectors_from_the_wolf_tables() {
// PROTOCOL.md section 4, "Test vectors".
for (hex, want) in [
("06 02 0C 00 00 00 00 08 07 00 00 00 FF FF 00 00", InputEvent::MouseMoveRel { dx: -1, dy: 0 }),
(
"06 02 12 00 00 00 00 0E 05 00 00 00 05 B8 02 10 00 00 07 7F 04 37",
InputEvent::MouseMoveAbs { x: 1464, y: 528, width: 1919, height: 1079 },
),
(
"06 02 09 00 00 00 00 05 08 00 00 00 01",
InputEvent::MouseButton { pressed: true, button: MouseButton::Left },
),
(
"06 02 0E 00 00 00 00 0A 03 00 00 00 00 A4 80 04 00 00",
InputEvent::Key { pressed: true, flags: 0, key_code: 0x80A4, modifiers: 0x04 },
),
("06 02 0E 00 00 00 00 0A 0A 00 00 00 FF 88 FF 88 00 00", InputEvent::Scroll { amount: -120 }),
("06 02 0A 00 00 00 00 06 01 00 00 55 00 1E", InputEvent::HScroll { amount: 30 }),
] {
let bytes = common::hex(hex);
assert_eq!(parse_client_message(&bytes), Ok(ClientControlMessage::Input(want.clone())), "{hex}");
}
}
#[test]
fn input_the_host_cannot_read_is_reported_not_fatal() {
// TOUCH (layout UNKNOWN U21), an unknown input type, a wrong size field.
let mut touch = 0x0206u16.to_le_bytes().to_vec();
touch.extend_from_slice(&12u16.to_le_bytes());
touch.extend_from_slice(&8u32.to_be_bytes());
touch.extend_from_slice(&0x5500_0002u32.to_le_bytes());
touch.extend_from_slice(&[1, 2, 3, 4]);
let mut unknown = touch.clone();
unknown[8..12].copy_from_slice(&0x0000_0099u32.to_le_bytes());
let mut bad_size = touch.clone();
bad_size[4..8].copy_from_slice(&999u32.to_be_bytes());
for (m, what) in [(touch, "touch"), (unknown, "unknown type"), (bad_size, "size field")] {
match parse_client_message(&m) {
Ok(ClientControlMessage::InputRejected { body_len, .. }) => assert_eq!(body_len, m.len() - 4, "{what}"),
other => panic!("{what}: {other:?}"),
}
}
}
// ================================================================================================ other messages
#[test]
fn client_messages_from_the_field_tables() {
let invalidate = |first: u32, last: u32| {
let mut b = first.to_le_bytes().to_vec();
b.extend_from_slice(&[0; 4]);
b.extend_from_slice(&last.to_le_bytes());
b.extend_from_slice(&[0; 12]);
b
};
for (m, want) in [
(msg(0x0307, &[]), ClientControlMessage::StartB),
(msg(0x0307, &[1, 2, 3, 4]), ClientControlMessage::StartB),
(msg(0x0200, &[]), ClientControlMessage::PeriodicPing),
(msg(0x0200, &[9; 8]), ClientControlMessage::PeriodicPing),
(msg(0x0302, &[]), ClientControlMessage::IdrRequest),
(msg(0x0301, &invalidate(5, 9)), ClientControlMessage::InvalidateRefFrames { first: 5, last: 9 }),
// Short bodies read as zero from where they end (PROTOCOL.md 3.3).
(msg(0x0301, &[]), ClientControlMessage::InvalidateRefFrames { first: 0, last: 0 }),
(msg(0x0301, &7u32.to_le_bytes()), ClientControlMessage::InvalidateRefFrames { first: 7, last: 0 }),
(msg(0x0301, &invalidate(5, 9)[..12]), ClientControlMessage::InvalidateRefFrames { first: 5, last: 9 }),
(msg(0x0301, &invalidate(5, 9)[..11]), ClientControlMessage::InvalidateRefFrames { first: 5, last: 0 }),
(msg(0x0201, &[1, 2, 3]), ClientControlMessage::LossStats(vec![1, 2, 3])),
(msg(0x0204, &[]), ClientControlMessage::FrameStats(vec![])),
(msg(0x0305, &[]), ClientControlMessage::Unknown { message_type: 0x0305, body_len: 0 }),
(msg(0x7777, &[0; 3]), ClientControlMessage::Unknown { message_type: 0x7777, body_len: 3 }),
(msg(0x010b, &[0; 10]), ClientControlMessage::Unknown { message_type: 0x010b, body_len: 10 }),
] {
assert_eq!(parse_client_message(&m), Ok(want.clone()), "{want:?}");
}
assert_err!(parse_client_message(&[]), Error::Truncated { .. });
assert_err!(parse_client_message(&[0x07, 0x03, 0x00]), Error::Truncated { .. });
let mut lie = msg(0x0307, &[0; 4]);
lie[2] = 5;
assert_err!(parse_client_message(&lie), Error::Malformed { .. });
assert_too_large!(
parse_client_message(&msg(0x0201, &vec![0; MAX_MESSAGE_BYTES - 3])),
MAX_MESSAGE_BYTES,
MAX_MESSAGE_BYTES + 1
);
}
#[test]
fn start_ping_idr_and_stats_over_the_wire() {
let mut w = raw_session(None, 2);
let t = at(w.now_ms);
for m in [
msg(0x0305, &[]),
msg(0x0307, &[]),
msg(0x0200, &[]),
msg(0x0302, &[]),
msg(0x0201, &[0xAA; 32]),
msg(0x0204, &[0xBB; 5]),
msg(0x7777, &[1, 2, 3]),
] {
w.client.send_plain(t, &m);
}
w.run_for(200);
assert_eq!(
w.host.take(),
[
ClientControlMessage::Unknown { message_type: 0x0305, body_len: 0 },
ClientControlMessage::StartB,
ClientControlMessage::PeriodicPing,
ClientControlMessage::IdrRequest,
ClientControlMessage::LossStats(vec![0xAA; 32]),
ClientControlMessage::FrameStats(vec![0xBB; 5]),
ClientControlMessage::Unknown { message_type: 0x7777, body_len: 3 },
]
.into_iter()
.map(ControlHostEvent::Message)
.collect::<Vec<_>>()
);
}
// ================================================================================================ host to client
#[test]
fn host_message_layouts() {
for (m, hex) in [
(
HostMessage::Rumble { controller: 1, low_frequency: 0x7FFF, high_frequency: 0x8000 },
"0b010a00 00000000 0100 ff7f 0080",
),
(HostMessage::RumbleTriggers { controller: 2, left: 0x1234, right: 0xABCD }, "00550600 0200 3412 cdab"),
(HostMessage::Termination { error_code: Some(TERMINATION_GRACEFUL) }, "09010400 80030023"),
(HostMessage::Termination { error_code: Some(1) }, "09010400 00000001"),
(
HostMessage::MotionEvent { controller: 3, rate_hz: 200, kind: MotionKind::Gyroscope },
"01550500 0300 c800 02",
),
(HostMessage::RgbLed { controller: 3, r: 0x10, g: 0x20, b: 0xFF }, "02550500 0300 1020ff"),
] {
let bytes = encode_host_message(&m).unwrap();
assert_eq!(common::to_hex(&bytes), hex.replace(' ', ""), "{m:?}");
assert_eq!(parse_host_message(&bytes), Ok(m.clone()), "round trip through the client's parser");
}
// Not sent: the plain termination's body is UNKNOWN (U10), HDR mode's layout has GPL provenance ([M*]).
for m in [
HostMessage::Termination { error_code: None },
HostMessage::HdrMode { enabled: true, metadata: None },
HostMessage::HdrMode { enabled: true, metadata: Some(HdrMetadata::default()) },
HostMessage::Other { message_type: 0x5503, body_len: 0 },
] {
assert_err!(encode_host_message(&m), Error::Unsupported { .. }, "{m:?}");
}
}
#[test]
fn host_messages_reach_the_client() {
let mut w = stream_session(Impair::clean(4), Impair::clean(4), None, 3);
let t = at(w.now_ms);
let h = w.host.h();
h.send_rumble(t, 0, 0x1000, 0x2000).unwrap();
h.send_rumble_triggers(t, 1, 3, 4).unwrap();
h.send(t, &HostMessage::RgbLed { controller: 2, r: 1, g: 2, b: 3 }).unwrap();
h.send(t, &HostMessage::MotionEvent { controller: 2, rate_hz: 100, kind: MotionKind::Accelerometer }).unwrap();
h.send_termination(t, TERMINATION_GRACEFUL).unwrap();
assert_err!(h.send_hdr_mode(t, true, None), Error::Unsupported { .. });
w.run_for(300);
assert_eq!(
w.client.messages(),
vec![
HostMessage::Rumble { controller: 0, low_frequency: 0x1000, high_frequency: 0x2000 },
HostMessage::RumbleTriggers { controller: 1, left: 3, right: 4 },
HostMessage::RgbLed { controller: 2, r: 1, g: 2, b: 3 },
HostMessage::MotionEvent { controller: 2, rate_hz: 100, kind: MotionKind::Accelerometer },
HostMessage::Termination { error_code: Some(TERMINATION_GRACEFUL) },
]
);
assert!(!w.client.events.contains(&ControlEvent::Dropped));
}
#[test]
fn host_frames_count_up_from_zero_and_go_reliable_on_channel_0() {
let mut w = raw_session(None, 4);
let t = at(w.now_ms);
for c in 0..3u16 {
w.host.h().send_rumble(t, c, 1, 2).unwrap();
}
w.run_for(200);
let seqs: Vec<u32> = w.client.opened.iter().map(|(s, _)| *s).collect();
assert_eq!(seqs, vec![0, 1, 2], "host sequence numbers start at 0 and never repeat (U11)");
assert!(w.client.events.iter().all(|e| !matches!(e, EnetEvent::Received { channel, .. } if *channel != 0)));
}
// ================================================================================================ replay, forgery
#[test]
fn replays_and_forgeries_are_dropped() {
let mut w = raw_session(None, 5);
let t = at(w.now_ms);
let start_b = msg(0x0307, &[]);
let ping = msg(0x0200, &[]);
let c = &mut w.client;
let f5 = c.cipher.seal(5, Direction::ClientToHost, &start_b).unwrap();
c.send_frame(t, f5.clone());
c.send_frame(t, f5); // the very same frame again (a new ENet command): a replay
c.send_frame(t, c.cipher.seal(3, Direction::ClientToHost, &ping).unwrap()); // older
c.send_frame(t, c.cipher.seal(5, Direction::ClientToHost, &ping).unwrap()); // equal, other content
let mut bad = c.cipher.seal(6, Direction::ClientToHost, &ping).unwrap();
bad[26] ^= 0x10;
c.send_frame(t, bad); // bad tag (ciphertext changed)
c.send_frame(t, c.cipher.seal(6, Direction::HostToClient, &ping).unwrap()); // reflected host frame
c.send_frame(t, ControlCipher::new([0; 16]).seal(6, Direction::ClientToHost, &ping).unwrap()); // wrong key
c.send_frame(t, vec![0xFF; 40]); // not a frame
c.send_frame(t, ping.clone()); // a bare message outside the frame (control V2 only)
c.send_frame(t, c.cipher.seal(6, Direction::ClientToHost, &ping).unwrap()); // seq 6 still free
w.run_for(200);
use ClientControlMessage as M;
use ControlHostEvent as E;
assert_eq!(
w.host.take(),
vec![
E::Message(M::StartB),
E::Dropped,
E::Dropped,
E::Dropped,
E::Dropped,
E::Dropped,
E::Dropped,
E::Dropped,
E::Dropped,
E::Message(M::PeriodicPing),
]
);
}
#[test]
fn malformed_message_inside_a_good_frame_is_skipped() {
let mut w = raw_session(None, 6);
let t = at(w.now_ms);
let mut lie = msg(0x0307, &[0; 4]);
lie[2] = 9;
w.client.send_plain(t, &lie);
w.client.send_plain(t, &[0x07]);
w.client.send_plain(t, &msg(0x0307, &[]));
w.run_for(200);
assert_eq!(
w.host.take(),
vec![
ControlHostEvent::Dropped,
ControlHostEvent::Dropped,
ControlHostEvent::Message(ClientControlMessage::StartB)
]
);
}
#[test]
fn client_sequence_at_u32_wrap() {
let mut w = raw_session(None, 7);
let t = at(w.now_ms);
let ping = msg(0x0200, &[]);
for seq in [0xFFFF_FFFEu32, 0xFFFF_FFFF, 0, 1] {
let f = w.client.cipher.seal(seq, Direction::ClientToHost, &ping).unwrap();
w.client.send_frame(t, f);
}
w.run_for(200);
let p = ControlHostEvent::Message(ClientControlMessage::PeriodicPing);
assert_eq!(w.host.take(), vec![p.clone(), p, ControlHostEvent::Dropped, ControlHostEvent::Dropped]);
}
// ================================================================================================ stop deadline
#[test]
fn stop_deadline_rules() {
let mut d = StopDeadline::new(at(1_000), Duration::from_secs(60));
assert_eq!(d.deadline(), at(61_000));
assert!(!d.expired(at(60_999)));
assert!(d.expired(at(61_000)));
d.on_ping(at(30_000));
assert_eq!(d.deadline(), at(90_000));
assert!(!d.expired(at(61_000)));
// A ping never pulls the deadline back (time does not go backwards, but be strict anyway).
d.on_ping(at(10_000));
assert_eq!(d.deadline(), at(90_000));
assert_eq!(DEFAULT_STOP_TIMEOUT, Duration::from_secs(60));
}
#[test]
fn no_periodic_ping_ends_the_session() {
let stop = Duration::from_secs(2);
let mut w = raw_session(Some(stop), 8);
let connected_ms = w.now_ms;
let dl = w.host.h().stop_deadline().expect("the clock runs once connected");
assert!(dl <= at(connected_ms + 2_000) && dl >= at(connected_ms + 1_900), "{dl:?}");
// Pings every 500 ms for 10 s keep it alive.
for _ in 0..20 {
let t = at(w.now_ms);
w.client.send_plain(t, &msg(0x0200, &[]));
w.run_for(500);
}
assert!(w.host.ping_timeouts.is_empty(), "pinged: no stop");
let last_ping = w.now_ms - 500;
w.run_for(5_000);
assert_eq!(w.host.ping_timeouts.len(), 1, "reported once");
let at_ms = w.host.ping_timeouts[0];
assert!(at_ms >= last_ping + 2_000 && at_ms <= last_ping + 2_000 + 50, "stopped at {at_ms}, last ping {last_ping}");
// Other messages do not count as pings.
assert_eq!(w.host.h().stop_deadline(), None, "the clock stops once reported");
let t = at(w.now_ms);
w.client.send_plain(t, &msg(0x0200, &[]));
w.run_for(100);
assert!(w.host.h().stop_deadline().is_some(), "a later ping starts it again");
}
#[test]
fn only_pings_push_the_deadline() {
let mut w = raw_session(Some(Duration::from_secs(1)), 9);
for _ in 0..6 {
let t = at(w.now_ms);
w.client.send_plain(t, &msg(0x0307, &[]));
w.run_for(300);
}
assert_eq!(w.host.ping_timeouts.len(), 1, "START_B and friends are not pings");
}
#[test]
fn without_a_stop_timeout_the_session_never_stops_for_pings() {
let mut w = stream_session(Impair::clean(10), Impair::clean(10), None, 10);
w.run_for(120_000);
assert!(w.host.ping_timeouts.is_empty());
assert_eq!(w.host.h().stop_deadline(), None);
assert!(w.host.connected());
}
// ================================================================================================ loss, close
#[test]
fn lossy_session_delivers_everything_in_order() {
let mut w = stream_session(Impair::lossy(150, 15), Impair::lossy(150, 15), None, 11);
let inputs: Vec<InputEvent> = (0..120).map(|i| InputEvent::MouseMoveRel { dx: i, dy: -i }).collect();
for chunk in inputs.chunks(6) {
let t = at(w.now_ms);
for e in chunk {
w.client.stream.send(t, &ClientMessage::Input(e.clone())).unwrap();
if let InputEvent::MouseMoveRel { dx, .. } = *e {
w.host.h().send_rumble(t, 0, dx as u16, 0).unwrap();
}
}
w.run_for(40);
}
assert!(w.run_until(w.now_ms + 120_000, |w| w.host.messages().len() >= 120 && w.client.messages().len() >= 120));
assert_eq!(w.host.messages(), inputs.iter().cloned().map(ClientControlMessage::Input).collect::<Vec<_>>());
assert_eq!(
w.client.messages(),
(0..120u16)
.map(|i| HostMessage::Rumble { controller: 0, low_frequency: i, high_frequency: 0 })
.collect::<Vec<_>>()
);
assert!(!w.host.events.contains(&ControlHostEvent::Dropped));
}
#[test]
fn close_from_either_side() {
let mut w = stream_session(Impair::clean(4), Impair::clean(4), None, 12);
let t = at(w.now_ms);
w.client.stream.close(t).unwrap();
assert!(w.run_until(w.now_ms + 2_000, |w| w.host.events.contains(&ControlHostEvent::Disconnected)));
let mut w = stream_session(Impair::clean(4), Impair::clean(4), None, 13);
let t = at(w.now_ms);
w.host.h().send_termination(t, TERMINATION_GRACEFUL).unwrap();
w.host.h().close(t).unwrap();
assert_err!(w.host.h().close(t), Error::Closed);
assert!(w.run_until(w.now_ms + 2_000, |w| w.client.events.contains(&ControlEvent::Disconnected)));
assert_eq!(w.client.messages(), vec![HostMessage::Termination { error_code: Some(TERMINATION_GRACEFUL) }]);
assert_err!(w.host.h().send_rumble(at(w.now_ms), 0, 0, 0), Error::State { .. });
}
#[test]
fn vanished_client_times_out() {
let mut w = stream_session(Impair::clean(4), Impair::clean(4), None, 14);
w.to_host.cut = true;
assert!(w.run_until(w.now_ms + 40_000, |w| w.host.events.contains(&ControlHostEvent::TimedOut)));
}
#[test]
fn accept_refuses_what_enet_refuses() {
assert!(ControlHost::accept(host_config(None), at(0), &[1, 2, 3]).is_err());
assert!(ControlHost::accept(host_config(None), at(0), &[]).is_err());
}
#[test]
fn config_debug_never_prints_the_key() {
let s = format!("{:?}", host_config(Some(DEFAULT_STOP_TIMEOUT)));
assert!(s.contains("redacted"), "{s}");
assert!(!s.contains("lumen") && !s.contains(&format!("{:?}", &KEY[..4])), "{s}");
}
// ================================================================================================ properties
proptest! {
#![proptest_config(ProptestConfig { cases: 512, ..ProptestConfig::default() })]
#[test]
fn parse_client_message_never_panics(data in proptest::collection::vec(any::<u8>(), 0..300)) {
let r = parse_client_message(&data);
prop_assert!(common::implemented(&r));
match r {
Ok(ClientControlMessage::Unknown { body_len, .. } | ClientControlMessage::InputRejected { body_len, .. }) => {
prop_assert_eq!(body_len + 4, data.len())
}
Ok(ClientControlMessage::LossStats(b) | ClientControlMessage::FrameStats(b)) => prop_assert_eq!(b.len() + 4, data.len()),
_ => {}
}
}
#[test]
fn typed_messages_round_trip(dx in any::<i16>(), dy in any::<i16>(), first in any::<u32>(), last in any::<u32>()) {
for m in [ClientMessage::Input(InputEvent::MouseMoveRel { dx, dy }), ClientMessage::InvalidateRefFrames { first, last }] {
let bytes = encode_client_message(&m).unwrap();
let want = match &m {
ClientMessage::Input(e) => ClientControlMessage::Input(e.clone()),
ClientMessage::InvalidateRefFrames { first, last } => ClientControlMessage::InvalidateRefFrames { first: *first, last: *last },
_ => unreachable!(),
};
prop_assert_eq!(parse_client_message(&bytes), Ok(want));
}
}
}
proptest! {
#![proptest_config(ProptestConfig { cases: 64, ..ProptestConfig::default() })]
/// A connected control host fed arbitrary sealed plaintexts and arbitrary raw datagrams never panics.
#[test]
fn control_host_survives_arbitrary_input(
plains in proptest::collection::vec(proptest::collection::vec(any::<u8>(), 0..120), 0..16),
raws in proptest::collection::vec(proptest::collection::vec(any::<u8>(), 0..120), 0..16),
) {
let mut w = raw_session(Some(Duration::from_secs(1)), 15);
let t = at(w.now_ms);
for p in &plains {
w.client.send_plain(t, p);
}
w.run_for(100);
let h = w.host.h();
for (i, r) in raws.iter().enumerate() {
let t = at(w.now_ms + i as u64);
let res = h.handle_datagram(t, r);
prop_assert!(common::implemented(&res));
let _ = h.handle_timeout(t);
while h.poll_transmit(t).is_some() {}
while h.poll_event().is_some() {}
}
let messages = w.host.messages().len();
prop_assert!(messages <= plains.len());
}
}
+990
View File
@@ -0,0 +1,990 @@
//! The host side of ENet (`docs/PROTOCOL.md` 3.1, `enet::host`): our own [`EnetClient`] talks to an
//! [`EnetHostPeer`] over an in-memory wire with simulated time, loss, duplication and reordering; plus a scripted
//! client for the wire facts of stock ENet 1.3 (verify connect fields, session ids, what is acknowledged when).
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::indexing_slicing, missing_docs)]
mod common;
use core::time::Duration;
use common::wire::{Endpoint, Impair, Wire, at};
use domistream::enet::protocol::{
Command, CommandBody, ConnectParams, Datagram, MAX_DATAGRAM_BYTES, NO_PEER_ID, encode_datagram, parse_datagram,
};
use domistream::enet::{
Delivery, EnetClient, EnetConfig, EnetEvent, EnetHostConfig, EnetHostEvent, EnetHostPeer, EnetHostState, EnetState,
MAX_PACKET_BYTES, MAX_SEND_QUEUE, parse_connect_request,
};
use domistream::{Error, Instant};
use proptest::prelude::*;
// ================================================================================================ setup
const HOST_PEER_ID: u16 = 7;
fn host_config() -> EnetHostConfig {
EnetHostConfig {
peer_id: HOST_PEER_ID,
channel_limit: 0x30,
mtu: 1400,
ping_interval: Duration::from_millis(500),
timeout: Duration::from_secs(10),
}
}
fn client_config() -> EnetConfig {
EnetConfig {
channel_count: 2,
mtu: 1400,
connect_data: 0x0000_1234,
ping_interval: Duration::from_millis(500),
timeout: Duration::from_secs(10),
}
}
struct Client {
peer: EnetClient,
events: Vec<EnetEvent>,
count: usize,
}
impl Client {
fn new(config: EnetConfig, seed: u64) -> Self {
let peer = EnetClient::connect(config, Instant::ZERO, &mut common::SeqRng::new(seed)).unwrap();
Self { peer, events: Vec::new(), count: 0 }
}
fn drain(&mut self) {
while let Some(e) = self.peer.poll_event() {
self.count += usize::from(matches!(e, EnetEvent::Received { .. }));
self.events.push(e);
}
}
fn received(&self, channel: u8) -> Vec<Vec<u8>> {
self.events
.iter()
.filter_map(|e| match e {
EnetEvent::Received { channel: c, data } if *c == channel => Some(data.clone()),
_ => None,
})
.collect()
}
}
impl Endpoint for Client {
fn transmit(&mut self, now: Instant) -> Option<Vec<u8>> {
self.peer.poll_transmit(now)
}
fn receive(&mut self, now: Instant, datagram: &[u8]) {
let _ = self.peer.handle_datagram(now, datagram);
self.drain();
}
fn deadline(&self) -> Option<Instant> {
self.peer.poll_timeout()
}
fn tick(&mut self, now: Instant) {
self.peer.handle_timeout(now).unwrap();
self.drain();
}
}
/// The caller of the host: one address, so one slot; the first datagram goes to `accept`.
struct Host {
config: EnetHostConfig,
peer: Option<EnetHostPeer>,
events: Vec<EnetHostEvent>,
refused: usize,
/// Every datagram the host sent, parsed.
sent: Vec<Datagram>,
count: usize,
}
impl Host {
fn new(config: EnetHostConfig) -> Self {
Self { config, peer: None, events: Vec::new(), refused: 0, sent: Vec::new(), count: 0 }
}
fn peer(&mut self) -> &mut EnetHostPeer {
self.peer.as_mut().expect("accepted")
}
fn drain(&mut self) {
if let Some(p) = self.peer.as_mut() {
while let Some(e) = p.poll_event() {
self.count += usize::from(matches!(e, EnetHostEvent::Received { .. }));
self.events.push(e);
}
}
}
fn received(&self, channel: u8) -> Vec<Vec<u8>> {
self.events
.iter()
.filter_map(|e| match e {
EnetHostEvent::Received { channel: c, data } if *c == channel => Some(data.clone()),
_ => None,
})
.collect()
}
fn connected(&self) -> bool {
self.peer.as_ref().is_some_and(|p| p.state() == EnetHostState::Connected)
}
}
impl Endpoint for Host {
fn transmit(&mut self, now: Instant) -> Option<Vec<u8>> {
let d = self.peer.as_mut()?.poll_transmit(now)?;
let mtu = self.peer.as_ref().unwrap().mtu();
assert!(d.len() <= mtu, "host datagram of {} over the MTU {mtu}", d.len());
self.sent.push(parse_datagram(&d).expect("the host's datagrams parse"));
Some(d)
}
fn receive(&mut self, now: Instant, datagram: &[u8]) {
match self.peer.as_mut() {
None => match EnetHostPeer::accept(self.config, now, datagram) {
Ok(p) => self.peer = Some(p),
Err(_) => self.refused += 1,
},
Some(p) => {
let _ = p.handle_datagram(now, datagram);
}
}
self.drain();
}
fn deadline(&self) -> Option<Instant> {
self.peer.as_ref()?.poll_timeout()
}
fn tick(&mut self, now: Instant) {
if let Some(p) = self.peer.as_mut() {
p.handle_timeout(now).unwrap();
}
self.drain();
}
}
type W = Wire<Client, Host>;
fn wire(to_host: Impair, to_client: Impair, seed: u64) -> W {
wire_with(client_config(), host_config(), to_host, to_client, seed)
}
fn wire_with(client: EnetConfig, host: EnetHostConfig, to_host: Impair, to_client: Impair, seed: u64) -> W {
Wire::new(Client::new(client, seed), Host::new(host), to_host, to_client, seed)
}
/// Long timeouts for the loss tests: a command lost many times in a row must not end the connection.
fn lossy_wire(to_host: Impair, to_client: Impair, seed: u64) -> W {
let client = EnetConfig { timeout: Duration::from_secs(60), ..client_config() };
let host = EnetHostConfig { timeout: Duration::from_secs(60), ..host_config() };
wire_with(client, host, to_host, to_client, seed)
}
fn both_connected(w: &mut W) -> bool {
w.client.peer.state() == EnetState::Connected && w.host.connected()
}
fn connected_wire(to_host: Impair, to_client: Impair, seed: u64) -> W {
let mut w = wire(to_host, to_client, seed);
assert!(w.run_until(30_000, both_connected), "no connection (seed {seed})");
w
}
fn now(w: &W) -> Instant {
at(w.now_ms)
}
// ================================================================================================ scripted client
fn cmd(acknowledge: bool, channel_id: u8, reliable_sequence: u16, body: CommandBody) -> Command {
Command { acknowledge, channel_id, reliable_sequence, body }
}
fn connect_params(connect_id: u32) -> ConnectParams {
ConnectParams {
outgoing_peer_id: 0,
incoming_session_id: 0xFF,
outgoing_session_id: 0xFF,
mtu: 1400,
window_size: 65536,
channel_count: 2,
incoming_bandwidth: 0,
outgoing_bandwidth: 0,
packet_throttle_interval: 5000,
packet_throttle_acceleration: 2,
packet_throttle_deceleration: 2,
connect_id,
}
}
fn connect_datagram(params: ConnectParams, data: u32) -> Vec<u8> {
encode_datagram(&Datagram {
peer_id: NO_PEER_ID,
session_id: 0,
sent_time: Some(1),
commands: vec![cmd(true, 0xFF, 1, CommandBody::Connect { params, data })],
})
.unwrap()
}
fn to_host(session_id: u8, sent_time: Option<u16>, commands: Vec<Command>) -> Vec<u8> {
encode_datagram(&Datagram { peer_id: HOST_PEER_ID, session_id, sent_time, commands }).unwrap()
}
fn transmitted(peer: &mut EnetHostPeer, t: Instant) -> Vec<Datagram> {
let mut out = Vec::new();
while let Some(d) = peer.poll_transmit(t) {
assert!(d.len() <= peer.mtu());
out.push(parse_datagram(&d).expect("host datagrams parse"));
assert!(out.len() < 10_000, "poll_transmit never ends");
}
out
}
fn events(peer: &mut EnetHostPeer) -> Vec<EnetHostEvent> {
let mut out = Vec::new();
while let Some(e) = peer.poll_event() {
out.push(e);
assert!(out.len() < 100_000);
}
out
}
fn verify_of(ds: &[Datagram]) -> (Command, ConnectParams) {
ds.iter()
.flat_map(|d| &d.commands)
.find_map(|c| match &c.body {
CommandBody::VerifyConnect(p) => Some((c.clone(), *p)),
_ => None,
})
.expect("a verify connect")
}
/// A host that accepted a hand-built connect and had its verify acknowledged at 2 ms.
fn scripted_connected() -> EnetHostPeer {
let mut h = EnetHostPeer::accept(host_config(), at(1), &connect_datagram(connect_params(0xABCD), 9)).unwrap();
let sent = transmitted(&mut h, at(1));
let (v, _) = verify_of(&sent);
let ack = cmd(
false,
0xFF,
v.reliable_sequence,
CommandBody::Acknowledge {
received_reliable_sequence: v.reliable_sequence,
received_sent_time: sent[0].sent_time.unwrap(),
},
);
h.handle_datagram(at(2), &to_host(0, Some(2), vec![ack])).unwrap();
assert_eq!(events(&mut h), vec![EnetHostEvent::Connected { data: 9 }]);
assert_eq!(h.state(), EnetHostState::Connected);
h
}
// ================================================================================================ handshake
#[test]
fn handshake_over_a_clean_wire() {
let mut w = wire(Impair::clean(5), Impair::clean(5), 1);
assert!(w.run_until(1_000, both_connected));
assert_eq!(w.host.events, vec![EnetHostEvent::Connected { data: client_config().connect_data }]);
assert_eq!(w.client.events, vec![EnetEvent::Connected]);
let p = w.host.peer();
assert_eq!(p.channel_count(), 2, "min(client 2, limit 0x30)");
assert_eq!(p.mtu(), 1400);
assert_eq!(w.host.refused, 0);
// Every host datagram is addressed to the client's peer id (0) after the handshake.
assert!(w.host.sent.iter().all(|d| d.peer_id == 0));
}
#[test]
fn verify_connect_fields() {
let params = connect_params(0xDEAD_BEEF);
let d = connect_datagram(params, 0x55);
assert_eq!(parse_connect_request(&d).unwrap().params, params);
assert_eq!(parse_connect_request(&d).unwrap().data, 0x55);
let cfg = EnetHostConfig { mtu: 1200, ..host_config() };
let mut h = EnetHostPeer::accept(cfg, at(3), &d).unwrap();
assert_eq!(h.state(), EnetHostState::AcknowledgingConnect);
assert_eq!(h.connect_id(), 0xDEAD_BEEF);
assert!(events(&mut h).is_empty(), "connected only once the verify is acknowledged");
let sent = transmitted(&mut h, at(3));
assert_eq!(sent.len(), 1);
let dg = &sent[0];
assert_eq!(dg.peer_id, params.outgoing_peer_id, "addressed to the client's peer id");
assert_eq!(dg.session_id, 0);
assert_eq!(dg.sent_time, Some(3));
// Stock ENet answers a connect with the verify only: the verify itself retires the client's connect.
assert_eq!(dg.commands.len(), 1, "{:?}", dg.commands);
let (c, v) = verify_of(&sent);
assert!(c.acknowledge, "verify connect is reliable");
assert_eq!(c.channel_id, 0xFF);
assert_eq!(c.reliable_sequence, 1);
assert_eq!(v.outgoing_peer_id, HOST_PEER_ID);
assert_eq!(v.connect_id, 0xDEAD_BEEF);
assert_eq!((v.incoming_session_id, v.outgoing_session_id), (0, 0));
assert_eq!(v.mtu, 1200, "min(client, host)");
assert_eq!(v.window_size, 65536);
assert_eq!(v.channel_count, 2);
assert_eq!((v.incoming_bandwidth, v.outgoing_bandwidth), (0, 0), "our bandwidth: unlimited");
assert_eq!(
(v.packet_throttle_interval, v.packet_throttle_acceleration, v.packet_throttle_deceleration),
(5000, 2, 2),
"throttle echoed"
);
assert_eq!(h.mtu(), 1200);
}
#[test]
fn verify_clamps_what_the_client_offers() {
for (mtu, window, channels, want_mtu, want_window, want_channels) in [
(100u32, 1000u32, 200u32, 576u32, 4096u32, 0x30u32),
(9000, 1 << 20, 1, 1400, 65536, 1),
(576, 4096, 255, 576, 4096, 0x30),
(u32::MAX, 0, 0x30, 1400, 4096, 0x30),
] {
let p = ConnectParams { mtu, window_size: window, channel_count: channels, ..connect_params(1) };
let mut h = EnetHostPeer::accept(host_config(), at(0), &connect_datagram(p, 0)).unwrap();
let (_, v) = verify_of(&transmitted(&mut h, at(0)));
assert_eq!((v.mtu, v.window_size, v.channel_count), (want_mtu, want_window, want_channels), "{p:?}");
assert_eq!(u32::from(h.channel_count()), want_channels);
}
}
#[test]
fn session_ids_follow_stock_enet() {
// (client's incoming, outgoing) -> (verify incoming = host's outgoing, verify outgoing = host's incoming).
for (inc, out, want_in, want_out) in [(0xFFu8, 0xFFu8, 0u8, 0u8), (1, 2, 2, 3), (3, 0, 0, 1), (2, 2, 3, 3)] {
let p = ConnectParams { incoming_session_id: inc, outgoing_session_id: out, ..connect_params(5) };
let mut h = EnetHostPeer::accept(host_config(), at(0), &connect_datagram(p, 0)).unwrap();
let sent = transmitted(&mut h, at(0));
let (c, v) = verify_of(&sent);
assert_eq!((v.incoming_session_id, v.outgoing_session_id), (want_in, want_out), "connect {inc}/{out}");
assert_eq!(sent[0].session_id, want_in, "the host sends with the session the client takes as incoming");
// The client must send with the host's incoming session id; anything else is ignored.
let ack = cmd(
false,
0xFF,
1,
CommandBody::Acknowledge { received_reliable_sequence: c.reliable_sequence, received_sent_time: 0 },
);
let wrong = (want_out + 1) & 3;
h.handle_datagram(at(1), &to_host(wrong, Some(1), vec![ack.clone()])).unwrap();
assert_eq!(h.state(), EnetHostState::AcknowledgingConnect, "wrong session {wrong} ignored");
h.handle_datagram(at(1), &to_host(want_out, Some(1), vec![ack])).unwrap();
assert_eq!(h.state(), EnetHostState::Connected);
assert_eq!(events(&mut h), vec![EnetHostEvent::Connected { data: 0 }]);
}
}
#[test]
fn accept_refuses_what_is_not_a_connect() {
let good = connect_datagram(connect_params(1), 0);
assert!(EnetHostPeer::accept(host_config(), at(0), &good).is_ok());
assert!(EnetHostPeer::accept(host_config(), at(0), &[]).is_err());
assert!(EnetHostPeer::accept(host_config(), at(0), &[0xFF; 3]).is_err());
let ping = encode_datagram(&Datagram {
peer_id: NO_PEER_ID,
session_id: 0,
sent_time: Some(0),
commands: vec![cmd(true, 0xFF, 1, CommandBody::Ping)],
})
.unwrap();
assert_err!(EnetHostPeer::accept(host_config(), at(0), &ping), Error::UnexpectedValue { .. }, "no connect");
let mut addressed = parse_datagram(&good).unwrap();
addressed.peer_id = HOST_PEER_ID;
assert_err!(
EnetHostPeer::accept(host_config(), at(0), &encode_datagram(&addressed).unwrap()),
Error::UnexpectedValue { .. },
"a connect addressed to a peer"
);
for channels in [0u32, 256, u32::MAX] {
let p = ConnectParams { channel_count: channels, ..connect_params(1) };
assert_err!(
EnetHostPeer::accept(host_config(), at(0), &connect_datagram(p, 0)),
Error::UnexpectedValue { .. },
"{channels} channels"
);
assert!(parse_connect_request(&connect_datagram(p, 0)).is_err());
}
for bad in [
EnetHostConfig { mtu: 575, ..host_config() },
EnetHostConfig { mtu: 4097, ..host_config() },
EnetHostConfig { channel_limit: 0, ..host_config() },
EnetHostConfig { peer_id: NO_PEER_ID, ..host_config() },
EnetHostConfig { peer_id: 0xFFFF, ..host_config() },
] {
assert_err!(EnetHostPeer::accept(bad, at(0), &good), Error::Malformed { .. }, "{bad:?}");
}
}
#[test]
fn repeated_connect_is_ignored_and_a_new_connect_id_is_visible() {
let d = connect_datagram(connect_params(77), 0);
let mut h = EnetHostPeer::accept(host_config(), at(0), &d).unwrap();
let first = transmitted(&mut h, at(0));
assert_eq!(first.len(), 1);
// The client's connect retransmitted: no second verify, no new state.
assert_eq!(h.handle_datagram(at(5), &d), Ok(()));
assert!(transmitted(&mut h, at(5)).is_empty());
assert_eq!(h.state(), EnetHostState::AcknowledgingConnect);
// A client that restarted: the caller sees another connect id and replaces the peer.
let again = connect_datagram(connect_params(78), 0);
assert_eq!(h.handle_datagram(at(6), &again), Ok(()));
assert_eq!(h.connect_id(), 77);
assert_ne!(parse_connect_request(&again).unwrap().params.connect_id, h.connect_id());
}
#[test]
fn data_before_the_verify_ack_is_not_taken() {
let mut h = EnetHostPeer::accept(host_config(), at(0), &connect_datagram(connect_params(3), 0)).unwrap();
let sent = transmitted(&mut h, at(0));
let (v, _) = verify_of(&sent);
let data = cmd(true, 0, 1, CommandBody::SendReliable(b"early".to_vec()));
h.handle_datagram(at(1), &to_host(0, Some(1), vec![data.clone()])).unwrap();
assert!(events(&mut h).is_empty());
assert!(
!transmitted(&mut h, at(1))
.iter()
.flat_map(|d| &d.commands)
.any(|c| matches!(c.body, CommandBody::Acknowledge { .. })),
"not acknowledged, so the client sends it again"
);
let ack = cmd(
false,
0xFF,
1,
CommandBody::Acknowledge { received_reliable_sequence: v.reliable_sequence, received_sent_time: 0 },
);
h.handle_datagram(at(2), &to_host(0, Some(2), vec![ack, data])).unwrap();
assert_eq!(
events(&mut h),
vec![EnetHostEvent::Connected { data: 0 }, EnetHostEvent::Received { channel: 0, data: b"early".to_vec() }]
);
}
#[test]
fn lost_verify_is_retransmitted() {
let mut w = wire(Impair::clean(5), Impair::clean(5), 2);
w.to_client.cut = true;
w.run_for(50);
assert!(w.host.peer.is_some() && !both_connected(&mut w));
w.to_client.cut = false;
assert!(w.run_until(5_000, both_connected), "the verify is sent again");
}
#[test]
fn verify_never_acknowledged_times_out() {
let mut h = EnetHostPeer::accept(host_config(), at(0), &connect_datagram(connect_params(3), 0)).unwrap();
assert_eq!(transmitted(&mut h, at(0)).len(), 1, "the first verify");
let mut verifies = 0;
let mut guard = 0;
while h.state() != EnetHostState::Disconnected {
let t = h.poll_timeout().expect("a deadline while waiting");
assert!(t <= at(host_config().timeout.as_millis() as u64 + 1), "no timeout by {t:?}");
h.handle_timeout(t).unwrap();
verifies += transmitted(&mut h, t)
.iter()
.flat_map(|d| &d.commands)
.filter(|c| matches!(c.body, CommandBody::VerifyConnect(_)))
.count();
guard += 1;
assert!(guard < 10_000);
}
assert!(verifies >= 3, "the verify was retransmitted ({verifies})");
assert_eq!(events(&mut h), vec![EnetHostEvent::TimedOut]);
assert_eq!(h.poll_timeout(), None);
assert_err!(h.handle_datagram(at(20_000), &[0x00, 0x07]), Error::Closed);
}
// ================================================================================================ data
#[test]
fn reliable_both_ways_in_order() {
let mut w = connected_wire(Impair::clean(3), Impair::clean(3), 3);
let t = now(&w);
for i in 0..50u32 {
w.client.peer.send(t, (i % 2) as u8, Delivery::Reliable, &i.to_le_bytes()).unwrap();
w.host.peer().send(t, (i % 2) as u8, Delivery::Reliable, &(1000 + i).to_le_bytes()).unwrap();
}
w.run_for(1_000);
for ch in 0..2u8 {
let want: Vec<Vec<u8>> =
(0..50u32).filter(|i| i % 2 == u32::from(ch)).map(|i| i.to_le_bytes().to_vec()).collect();
assert_eq!(w.host.received(ch), want, "host, channel {ch}");
let want: Vec<Vec<u8>> =
(0..50u32).filter(|i| i % 2 == u32::from(ch)).map(|i| (1000 + i).to_le_bytes().to_vec()).collect();
assert_eq!(w.client.received(ch), want, "client, channel {ch}");
}
}
#[test]
fn large_packets_fragment_both_ways() {
let mut w = connected_wire(Impair::clean(2), Impair::clean(2), 4);
let up: Vec<u8> = (0..5000u32).map(|i| (i * 7) as u8).collect();
let down: Vec<u8> = (0..MAX_PACKET_BYTES as u32).map(|i| (i * 13 + 1) as u8).collect();
let t = now(&w);
w.client.peer.send(t, 1, Delivery::Reliable, &up).unwrap();
w.host.peer().send(t, 0, Delivery::Reliable, &down).unwrap();
w.run_for(2_000);
assert_eq!(w.host.received(1), vec![up]);
assert_eq!(w.client.received(0), vec![down]);
let frags =
w.host.sent.iter().flat_map(|d| &d.commands).filter(|c| matches!(c.body, CommandBody::SendFragment(_))).count();
assert!(frags > 40, "the host fragmented its 64 KiB packet ({frags})");
}
#[test]
fn unreliable_and_unsequenced_from_the_client() {
let mut w = connected_wire(Impair::clean(2), Impair::clean(2), 5);
let t = now(&w);
for i in 0..3u8 {
w.client.peer.send(t, 0, Delivery::Unreliable, &[b'u', i]).unwrap();
w.client.peer.send(t, 1, Delivery::Unsequenced, &[b's', i]).unwrap();
}
w.run_for(200);
assert_eq!(w.host.received(0), vec![vec![b'u', 0], vec![b'u', 1], vec![b'u', 2]]);
assert_eq!(w.host.received(1), vec![vec![b's', 0], vec![b's', 1], vec![b's', 2]]);
}
#[test]
fn unreliable_from_the_host() {
let mut w = connected_wire(Impair::clean(2), Impair::clean(2), 6);
let t = now(&w);
w.host.peer().send(t, 0, Delivery::Unreliable, b"u1").unwrap();
w.host.peer().send(t, 0, Delivery::Unsequenced, b"s1").unwrap();
w.run_for(100);
assert_eq!(w.client.received(0), vec![b"u1".to_vec(), b"s1".to_vec()]);
}
#[test]
fn duplicated_and_stale_datagrams_are_delivered_once() {
let mut h = scripted_connected();
let unseq = |group: u16, data: &[u8]| {
cmd(false, 0, 0, CommandBody::SendUnsequenced { unsequenced_group: group, data: data.to_vec() })
};
let unrel = |seq: u16, data: &[u8]| {
cmd(false, 0, 0, CommandBody::SendUnreliable { unreliable_sequence: seq, data: data.to_vec() })
};
let feed = |h: &mut EnetHostPeer, c: Command| h.handle_datagram(at(10), &to_host(0, Some(10), vec![c])).unwrap();
feed(&mut h, unseq(1, b"a"));
feed(&mut h, unseq(1, b"a"));
feed(&mut h, unseq(2, b"b"));
feed(&mut h, unseq(1, b"a"));
feed(&mut h, unrel(5, b"x"));
feed(&mut h, unrel(5, b"x"));
feed(&mut h, unrel(4, b"old"));
feed(&mut h, unrel(6, b"y"));
let got: Vec<Vec<u8>> = events(&mut h)
.into_iter()
.map(|e| match e {
EnetHostEvent::Received { data, .. } => data,
other => panic!("{other:?}"),
})
.collect();
assert_eq!(got, vec![b"a".to_vec(), b"b".to_vec(), b"x".to_vec(), b"y".to_vec()]);
// Far ahead of the unsequenced window: dropped.
feed(&mut h, unseq(40_000, b"far"));
assert!(events(&mut h).is_empty());
// The window moves forward with groups within reach.
feed(&mut h, unseq(3000, b"c"));
feed(&mut h, unseq(3000, b"c"));
feed(&mut h, unseq(2, b"b"));
assert_eq!(events(&mut h), vec![EnetHostEvent::Received { channel: 0, data: b"c".to_vec() }]);
}
#[test]
fn reliable_from_the_client_reordered_and_duplicated() {
let mut h = scripted_connected();
let rel = |seq: u16, data: &[u8]| cmd(true, 0, seq, CommandBody::SendReliable(data.to_vec()));
h.handle_datagram(at(10), &to_host(0, Some(10), vec![rel(3, b"3"), rel(2, b"2")])).unwrap();
assert!(events(&mut h).is_empty());
h.handle_datagram(at(11), &to_host(0, Some(11), vec![rel(1, b"1"), rel(2, b"2")])).unwrap();
h.handle_datagram(at(12), &to_host(0, Some(12), vec![rel(1, b"1")])).unwrap();
let got: Vec<EnetHostEvent> = events(&mut h);
assert_eq!(
got,
[b"1", b"2", b"3"].iter().map(|d| EnetHostEvent::Received { channel: 0, data: d.to_vec() }).collect::<Vec<_>>()
);
let acks: Vec<(u16, u16)> = transmitted(&mut h, at(12))
.iter()
.flat_map(|d| d.commands.clone())
.filter_map(|c| match c.body {
CommandBody::Acknowledge { received_reliable_sequence, received_sent_time } => {
Some((received_reliable_sequence, received_sent_time))
}
_ => None,
})
.collect();
for want in [(3, 10), (2, 10), (1, 11), (2, 11), (1, 12)] {
assert!(acks.contains(&want), "ack {want:?} (with the datagram's sent time) in {acks:?}");
}
// Far future and channels outside the grant: never delivered.
h.handle_datagram(at(13), &to_host(0, Some(13), vec![rel(40_000, b"evil")])).unwrap();
let _ = h.handle_datagram(
at(13),
&to_host(0, Some(13), vec![cmd(true, 9, 1, CommandBody::SendReliable(b"ch9".to_vec()))]),
);
assert!(events(&mut h).is_empty());
assert_eq!(h.state(), EnetHostState::Connected);
}
#[test]
fn acknowledged_commands_need_the_sent_time() {
// Stock ENet: a command that wants an acknowledgement in a datagram without sent time is handled but not
// acknowledged, and the rest of the datagram is skipped.
let mut h = scripted_connected();
let d = to_host(
0,
None,
vec![
cmd(true, 0, 1, CommandBody::SendReliable(b"a".to_vec())),
cmd(true, 0, 2, CommandBody::SendReliable(b"b".to_vec())),
],
);
h.handle_datagram(at(10), &d).unwrap();
assert_eq!(events(&mut h), vec![EnetHostEvent::Received { channel: 0, data: b"a".to_vec() }]);
assert!(
!transmitted(&mut h, at(10))
.iter()
.flat_map(|d| &d.commands)
.any(|c| matches!(c.body, CommandBody::Acknowledge { .. }))
);
}
#[test]
fn connection_commands_are_acknowledged() {
let mut h = scripted_connected();
let d = to_host(
0,
Some(0x0102),
vec![
cmd(true, 0xFF, 2, CommandBody::Ping),
cmd(true, 0xFF, 3, CommandBody::BandwidthLimit { incoming: 1_000_000, outgoing: 2_000_000 }),
cmd(true, 0xFF, 4, CommandBody::ThrottleConfigure { interval: 1000, acceleration: 3, deceleration: 4 }),
],
);
h.handle_datagram(at(10), &d).unwrap();
let acks: Vec<Command> = transmitted(&mut h, at(10))
.into_iter()
.flat_map(|d| d.commands)
.filter(|c| matches!(c.body, CommandBody::Acknowledge { .. }))
.collect();
for seq in [2u16, 3, 4] {
assert!(
acks.iter().any(|c| c.channel_id == 0xFF
&& c.body == CommandBody::Acknowledge { received_reliable_sequence: seq, received_sent_time: 0x0102 }),
"ack of {seq} in {acks:?}"
);
}
assert!(events(&mut h).is_empty());
assert_eq!(h.state(), EnetHostState::Connected);
}
#[test]
fn reliable_sequence_wraps_at_0xffff() {
let mut w = connected_wire(Impair::clean(1), Impair::clean(1), 7);
let total = 66_000u32;
let mut sent = 0u32;
while sent < total {
let t = now(&w);
for _ in 0..200 {
if sent < total {
w.client.peer.send(t, 0, Delivery::Reliable, &sent.to_le_bytes()).unwrap();
w.host.peer().send(t, 0, Delivery::Reliable, &sent.to_le_bytes()).unwrap();
sent += 1;
}
}
let want = sent as usize;
assert!(w.run_until(w.now_ms + 5_000, |w| w.host.count >= want && w.client.count >= want));
}
let got = w.host.received(0);
assert_eq!(got.len(), total as usize);
assert!(got.iter().enumerate().all(|(i, d)| *d == (i as u32).to_le_bytes()), "host order");
let got = w.client.received(0);
assert_eq!(got.len(), total as usize);
assert!(got.iter().enumerate().all(|(i, d)| *d == (i as u32).to_le_bytes()), "client order");
}
// ================================================================================================ loss and timers
/// Sends `n` reliable messages each way, a few at a time, over a lossy wire; returns what arrived.
fn exchange(w: &mut W, n: u32) -> (Vec<Vec<u8>>, Vec<Vec<u8>>) {
let mut i = 0;
while i < n {
let t = now(w);
for _ in 0..5 {
if i < n {
let _ = w.client.peer.send(t, 0, Delivery::Reliable, &i.to_le_bytes());
if let Some(p) = w.host.peer.as_mut() {
let _ = p.send(t, 0, Delivery::Reliable, &(i + 10_000).to_le_bytes());
}
i += 1;
}
}
w.run_for(30);
}
let n = n as usize;
w.run_until(w.now_ms + 120_000, |w| w.host.count >= n && w.client.count >= n);
(w.host.received(0), w.client.received(0))
}
#[test]
fn retransmission_under_loss_delivers_everything_in_order() {
let mut w = lossy_wire(Impair::lossy(200, 10), Impair::lossy(200, 10), 8);
assert!(w.run_until(60_000, both_connected));
let (up, down) = exchange(&mut w, 200);
assert_eq!(up, (0..200u32).map(|i| i.to_le_bytes().to_vec()).collect::<Vec<_>>());
assert_eq!(down, (0..200u32).map(|i| (i + 10_000).to_le_bytes().to_vec()).collect::<Vec<_>>());
assert!(w.to_host.lost > 0 && w.to_client.lost > 0, "the wire did lose datagrams");
assert!(!w.host.events.contains(&EnetHostEvent::TimedOut));
assert!(w.host.peer().round_trip_time().is_some());
}
#[test]
fn idle_connection_stays_up() {
let mut w = connected_wire(Impair::clean(20), Impair::clean(20), 9);
w.run_for(60_000);
assert!(both_connected(&mut w));
assert!(!w.host.events.contains(&EnetHostEvent::TimedOut));
assert!(!w.client.events.contains(&EnetEvent::TimedOut));
}
#[test]
fn the_host_pings_a_quiet_client() {
// A client that never pings by itself (only acknowledges): the host's pings keep the connection checked.
let quiet = EnetConfig { ping_interval: Duration::from_secs(3600), ..client_config() };
let mut w = wire_with(quiet, host_config(), Impair::clean(20), Impair::clean(20), 13);
assert!(w.run_until(1_000, both_connected));
let start = w.host.sent.len();
w.run_for(30_000);
assert!(both_connected(&mut w));
let pings = w.host.sent[start..]
.iter()
.flat_map(|d| &d.commands)
.filter(|c| c.body == CommandBody::Ping && c.acknowledge)
.count();
assert!(pings >= 30, "the host pings an idle client ({pings})");
// And when nothing comes back at all, its ping times out.
let mut h = scripted_connected();
let t = h.poll_timeout().expect("a ping deadline");
assert!(t <= at(2 + host_config().ping_interval.as_millis() as u64));
h.handle_timeout(t).unwrap();
assert!(
transmitted(&mut h, t)
.iter()
.flat_map(|d| &d.commands)
.any(|c| c.body == CommandBody::Ping && c.channel_id == 0xFF)
);
}
#[test]
fn vanished_client_times_out() {
let mut w = connected_wire(Impair::clean(5), Impair::clean(5), 10);
let cut_at = w.now_ms;
w.to_host.cut = true;
let limit =
cut_at + host_config().ping_interval.as_millis() as u64 + host_config().timeout.as_millis() as u64 + 1_000;
assert!(w.run_until(limit, |w| w.host.events.contains(&EnetHostEvent::TimedOut)), "no timeout by {limit} ms");
let earliest = cut_at + host_config().timeout.as_millis() as u64 - host_config().ping_interval.as_millis() as u64;
assert!(w.now_ms >= earliest, "not before the timeout");
assert_eq!(w.host.peer().state(), EnetHostState::Disconnected);
assert_eq!(w.host.peer().poll_timeout(), None);
let t = now(&w);
assert_err!(w.host.peer().send(t, 0, Delivery::Reliable, b"x"), Error::State { .. });
}
// ================================================================================================ disconnect
#[test]
fn client_disconnect_reaches_the_host() {
let mut w = connected_wire(Impair::clean(5), Impair::clean(5), 11);
let t = now(&w);
w.client.peer.disconnect(t, 77).unwrap();
assert!(w.run_until(w.now_ms + 2_000, |w| w.host.events.contains(&EnetHostEvent::Disconnected { data: 77 })));
assert_eq!(w.host.peer().state(), EnetHostState::Disconnected);
assert!(
w.run_until(w.now_ms + 2_000, |w| w.client.peer.state() == EnetState::Disconnected),
"the host acknowledged the disconnect after closing"
);
assert!(!w.client.events.contains(&EnetEvent::TimedOut));
}
#[test]
fn host_disconnect_reaches_the_client() {
let mut w = connected_wire(Impair::clean(5), Impair::clean(5), 12);
let t = now(&w);
w.host.peer().disconnect(t, 42).unwrap();
assert_eq!(w.host.peer().state(), EnetHostState::Disconnecting);
assert_err!(w.host.peer().disconnect(t, 1), Error::Closed);
assert_err!(w.host.peer().send(t, 0, Delivery::Reliable, b"late"), Error::State { .. });
assert!(w.run_until(w.now_ms + 2_000, |w| w.client.events.contains(&EnetEvent::Disconnected { data: 42 })));
assert!(w.run_until(w.now_ms + 2_000, |w| w.host.peer.as_ref().unwrap().state() == EnetHostState::Disconnected));
assert!(!w.host.events.contains(&EnetHostEvent::TimedOut));
}
#[test]
fn disconnect_during_the_handshake() {
let mut h = EnetHostPeer::accept(host_config(), at(0), &connect_datagram(connect_params(3), 0)).unwrap();
let _ = transmitted(&mut h, at(0));
h.handle_datagram(at(1), &to_host(0, Some(1), vec![cmd(true, 0xFF, 2, CommandBody::Disconnect { data: 5 })]))
.unwrap();
assert_eq!(h.state(), EnetHostState::Disconnected);
assert_eq!(events(&mut h), vec![EnetHostEvent::Disconnected { data: 5 }]);
}
// ================================================================================================ rules
#[test]
fn send_rules() {
let mut h = EnetHostPeer::accept(host_config(), at(0), &connect_datagram(connect_params(3), 0)).unwrap();
assert_err!(h.send(at(0), 0, Delivery::Reliable, b"x"), Error::State { .. }, "before the verify is acknowledged");
let mut h = scripted_connected();
assert_err!(h.send(at(3), 2, Delivery::Reliable, b"x"), Error::UnexpectedValue { .. }, "channel 2 of 2");
assert_too_large!(
h.send(at(3), 0, Delivery::Reliable, &vec![0; MAX_PACKET_BYTES + 1]),
MAX_PACKET_BYTES,
MAX_PACKET_BYTES + 1
);
assert!(matches!(h.send(at(3), 0, Delivery::Unsequenced, &[0; 1500]), Err(Error::TooLarge { .. })));
for i in 0..MAX_SEND_QUEUE {
h.send(at(3), 0, Delivery::Reliable, &[i as u8]).unwrap_or_else(|e| panic!("packet {i}: {e:?}"));
}
match h.send(at(3), 0, Delivery::Reliable, b"one too many") {
Err(Error::TooLarge { max, .. }) => assert_eq!(max, MAX_SEND_QUEUE),
other => panic!("{other:?}"),
}
// The queue drains within the MTU, and each datagram parses.
let sent = transmitted(&mut h, at(4));
assert!(!sent.is_empty());
}
#[test]
fn garbage_never_changes_state() {
let mut h = scripted_connected();
for bad in [&[][..], &[0x00][..], &[0x40, 0x07, 0x85, 0xFF, 0, 1][..], &[0x00, 0x07, 0x8F, 0, 0, 0][..]] {
assert!(h.handle_datagram(at(5), bad).is_err(), "{bad:?}");
assert_eq!(h.state(), EnetHostState::Connected);
}
assert_too_large!(
h.handle_datagram(at(5), &vec![0; MAX_DATAGRAM_BYTES + 1]),
MAX_DATAGRAM_BYTES,
MAX_DATAGRAM_BYTES + 1
);
// Another peer id: dropped without error.
let other = encode_datagram(&Datagram {
peer_id: HOST_PEER_ID + 1,
session_id: 0,
sent_time: Some(1),
commands: vec![cmd(true, 0, 1, CommandBody::SendReliable(b"not for us".to_vec()))],
})
.unwrap();
assert_eq!(h.handle_datagram(at(5), &other), Ok(()));
assert!(events(&mut h).is_empty());
assert_eq!(h.state(), EnetHostState::Connected);
}
#[test]
fn fragments_with_lying_lengths() {
let frag = |count: u32, number: u32, total: u32, offset: u32, len: usize| {
cmd(
true,
0,
1,
CommandBody::SendFragment(domistream::enet::protocol::Fragment {
start_sequence: 1u16.wrapping_sub(number as u16),
fragment_count: count,
fragment_number: number,
total_length: total,
fragment_offset: offset,
data: vec![0; len],
}),
)
};
let mut h = scripted_connected();
assert_too_large!(
h.handle_datagram(at(5), &to_host(0, Some(5), vec![frag(2, 0, MAX_PACKET_BYTES as u32 + 1, 0, 100)])),
MAX_PACKET_BYTES,
MAX_PACKET_BYTES + 1
);
for f in [
frag(0, 0, 10, 0, 10),
frag(2, 2, 20, 0, 10),
frag(2, 0, 20, 15, 10),
frag(2, 0, 5, 0, 10),
frag(u32::MAX, 0, 100, 0, 10),
frag(2, 0, u32::MAX, 0, 10),
] {
let mut h = scripted_connected();
let _ = h.handle_datagram(at(5), &to_host(0, Some(5), vec![f.clone()]));
assert!(events(&mut h).is_empty(), "{f:?}");
assert_eq!(h.state(), EnetHostState::Connected);
}
}
// ================================================================================================ properties
proptest! {
#![proptest_config(ProptestConfig { cases: 128, ..ProptestConfig::default() })]
/// Arbitrary bytes never panic `accept`, and what it accepts it answers with datagrams that parse.
#[test]
fn accept_never_panics(data in proptest::collection::vec(any::<u8>(), 0..200)) {
let r = EnetHostPeer::accept(host_config(), at(0), &data);
prop_assert!(common::implemented(&r));
if let Ok(mut h) = r {
prop_assert!(!transmitted(&mut h, at(0)).is_empty());
}
}
/// A connected host fed arbitrary datagrams (raw, or with our header so they reach the command loop) never
/// panics; what it delivers fits the cap; what it sends parses and fits the MTU.
#[test]
fn host_survives_arbitrary_datagrams(
datagrams in proptest::collection::vec((any::<bool>(), proptest::collection::vec(any::<u8>(), 0..200)), 1..20)
) {
let mut h = scripted_connected();
for (i, (headed, d)) in datagrams.into_iter().enumerate() {
let t = at(10 + i as u64 * 50);
let bytes = if headed {
let mut b = vec![0x80, HOST_PEER_ID as u8, 0, 10];
b.extend_from_slice(&d);
b
} else {
d
};
let r = h.handle_datagram(t, &bytes);
prop_assert!(common::implemented(&r));
let _ = h.handle_timeout(t);
let _ = transmitted(&mut h, t);
for e in events(&mut h) {
if let EnetHostEvent::Received { data, .. } = e {
prop_assert!(data.len() <= MAX_PACKET_BYTES);
}
}
}
}
}
proptest! {
#![proptest_config(ProptestConfig { cases: 24, ..ProptestConfig::default() })]
/// Random loss, duplication, reordering and latency: the connection comes up and every reliable message
/// arrives exactly once, in order, both ways.
#[test]
fn random_loss_patterns_deliver_reliable_messages_in_order(
seed in any::<u64>(),
loss in 0u32..300,
duplicate in 0u32..150,
reorder in 0u32..400,
latency in 1u64..60,
) {
let impair = Impair { loss, duplicate, reorder, reorder_ms: 40, latency_ms: latency };
let mut w = lossy_wire(impair, impair, seed);
prop_assert!(w.run_until(60_000, both_connected), "no connection");
let (up, down) = exchange(&mut w, 40);
prop_assert_eq!(up, (0..40u32).map(|i| i.to_le_bytes().to_vec()).collect::<Vec<_>>());
prop_assert_eq!(down, (0..40u32).map(|i| (i + 10_000).to_le_bytes().to_vec()).collect::<Vec<_>>());
}
}
File diff suppressed because it is too large Load Diff
+6
View File
@@ -51,6 +51,8 @@ copied into DomiStream, and settled by our own measurement instead. Known cases:
| `src/session/stream/control/mod.rs` | HDR mode payload "matches Sunshine's" struct | Field layout logged as `[M*]`, confirm by measurement before relying on it |
| fec-rs `src/reed_solomon.rs` tests (`test_partial_eq_reflects_parity_matrix_changes`) | the same audio parity matrix as Moonshine's encoder | Not taken, same rule. Seen while reading fec-rs on 2026-11-25. |
| `src/rtsp.rs` | `surround-params` digit packing "matching moonlight-common-c" | The Wolf example `surround-params=21101` gives the same packing independently, so we use the Wolf source |
| `src/rtsp.rs` (read again as S-30) | `encoderCscMode` bit layout (comment cites Sunshine's colour-space function); `maxNumReferenceFrames` 0 = "host's choice" (comment cites moonlight-common-c); the 5.1/7.1 mapping rotation (comment cites GFE and Moonlight) | Not taken: the host parser keeps both numbers raw and writes the mappings as configured (PROTOCOL.md 2.5, U6, U26) |
| `src/session/stream/video/mod.rs` (S-31) | how the stored bitrate is reduced for FEC and audio (comment: "as Sunshine computes it") | Not taken; the parser hands over the client's bitrate unchanged |
## How code gets written
@@ -91,3 +93,7 @@ All entries by the DomiStream protocol engineer. Pinned commits are the ones rea
| S-23 | 2026-12-04 | NVIDIA [video-sdk-samples](https://github.com/NVIDIA/video-sdk-samples) at `aa3544d`: `Samples/NvCodec/NvEncoder/nvEncodeAPI.h` (API 8.1, sha256 `4d061c34…6042a`); NVIDIA [VideoProcessingFramework](https://github.com/NVIDIA/VideoProcessingFramework) at `e82364f`: `src/TC/third_party/nvEncodeAPI.h` (API 12.0, sha256 `067c5159…b4ad`); GitHub repository metadata of both | Both headers carry NVIDIA's MIT notice for the header file; the repositories are Apache-2.0 / unlicensed samples and the second is archived. Declarations used for the L0 spike shim (struct versions, preset and tuning enums, `NvEncGetEncodePresetConfigEx`, resource registration). No sample `.cpp` file was opened. |
| S-24 | 2026-12-04 | [NVENC Video Encoder API Programming Guide](https://docs.nvidia.com/video-technologies/video-codec-sdk/13.0/nvenc-video-encoder-api-prog-guide/index.html) (SDK 13.0) | Loading `nvEncodeAPI` at run time and `NvEncodeAPICreateInstance`; `NV_ENC_DEVICE_TYPE_DIRECTX` sessions; registering, mapping and unmapping D3D11 textures; tuning info (low latency, ultra low latency), presets P1-P7, CBR filler, forcing IDR, `NvEncInvalidateRefFrames`, intra refresh, look-ahead latency; lock/unlock of the bitstream; async mode only on Windows 10+ WDDM, recommended there; Main10 settings. |
| S-25 | 2026-12-04 | Licences via the GitHub and crates.io APIs and `COPYING` files: nefarius/ViGEmClient (MIT, archived), nefarius/ViGEmBus (BSD-3-Clause, archived), xiph/opus `COPYING` (BSD-style), crates `opus`, `audiopus_sys`, `vigem-client`, `nvidia-video-codec-sdk`, `nvenc`, `windows` | Licence and status only; no source files of these projects were opened. |
| S-30 | 2026-12-04 | [Moonshine](https://github.com/hgaiser/moonshine) at `f184d5e3693e09c3a6ab1025bde6cdb67f36a6bc` (same pin as S-9): `src/rtsp.rs` again, read for the host side | BSD-2, facts only. One request per TCP connection, the note that Moonlight opens a connection per request; `CSeq` required (connection closed without it); no method order and no `Session` check; statuses 200/400/500 only; OPTIONS `Public`; SETUP needs `Transport` (400 without), stream from the first `streamid=` query segment, answer `Session: MoonshineSession;timeout = 90` and `Transport: server_port=<port>`; DESCRIBE line order and values (`featureFlags:3`, `encryptionSupported` 5 or 7, `sprop-parameter-sets=AAAAAU`, invalidation, AV1, H.264, surround lines); ANNOUNCE: the ten required attributes (400 when missing), the defaults of the optional ones (`maxNumReferenceFrames` 1, `dynamicRangeMode`/`chromaSamplingType`/`encoderCscMode`/`encryptionEnabled`/`surround.enable` 0, `numChannels` 2, `channelMask` 0x3, `AudioQuality` 1), `maxFPS` 0 refused, bitrate ×1000 must fit a u32, QoS off for `0`. The comments citing Sunshine, moonlight-common-c or GFE are logged as second-hand GPL facts above and not used. |
| S-31 | 2026-12-04 | Moonshine at `f184d5e`: `src/session/stream/mod.rs`, `src/session/stream/video/mod.rs`; the repository tree listing (GitHub API) | BSD-2, facts only. `bitStreamFormat` 0 H.264 (default), 1 HEVC, 2 AV1, others invalid; dynamic range 0 SDR (default), 1 HDR; chroma 0 4:2:0 (default), 1 4:4:4; valid video packet size 200..=65471 (one stream packet in an IPv6 UDP datagram), below 200 refused; FEC default 20 %. The bitrate comment citing Sunshine is logged above and not used. |
| S-32 | 2026-12-04 | [Wolf: RTSP](https://games-on-whales.github.io/wolf/stable/protocols/rtsp.html) again (as S-3); [RFC 2326](https://www.rfc-editor.org/rfc/rfc2326.txt) | Wolf: nothing new for the host (no per-method answers, no ANNOUNCE list). RFC 2326: reason phrases of 400, 451, 454, 455, 501 (7.1.1); a missing `Content-Length` means zero (4.4); OPTIONS may be sent at any time (10.1); session ids at least 8 random octets (3.4); `Public` as a comma-separated list (10.1 example). |
| S-34 | 2026-12-04 | [Stock ENet](https://github.com/lsalzman/enet) v1.3.18 (`2662c0d`, same pin as S-17), read again for the host side: `protocol.c` (`enet_protocol_handle_connect`, `_verify_connect`, `_disconnect`, `_ping`, `_bandwidth_limit`, `_throttle_configure`, `_acknowledge`, `_send_unsequenced`, `_send_unreliable_fragment`, `_send_reliable`/`_send_fragment` state checks, the acknowledgement rules of `_handle_incoming_commands`, the ping condition of `_send_outgoing_commands`) and `include/enet/enet.h` (peer window constants) | MIT. Facts for PROTOCOL.md 3.1 "The accepting side" and `enet::host`: a CONNECT is answered by a reliable verify on channel 0xFF and is not itself acknowledged; repeated connects from a live peer are refused; session id derivation (offered id or the slot's, plus one mod 4, skipping the slot's previous id) and which verify field carries which; MTU, window and channel clamping, bandwidths are the host's own, throttle echoed, connect data reported with the connect event; connected on the acknowledgement of the verify; acknowledgements only while connected and only with a sent time, a failing command ends the datagram; ping, bandwidth and throttle need the connected state; unsequenced window 1024 groups, 32 free windows; pings when nothing was received for the ping interval and nothing reliable is in flight. Read through an automated summary of the raw files at the pinned commit; no code copied. |
+113
View File
@@ -221,6 +221,76 @@ SDP attribute lines `a=<name>:<value>`. Names the host reads [M]; values and the
Settle U6: lab capture of an ANNOUNCE accepted by Sunshine, then vary one attribute at a time.
### 2.5 Host side (Lumen): `rtsp::server`
Facts from Moonshine's host code (`src/rtsp.rs`, `src/session/stream/video/mod.rs` at `f184d5e`, S-30, S-31) and
RFC 2326 (S-32); our own choices are marked as such.
**Connections and framing.** Moonshine reads one request per TCP connection and notes that Moonlight opens a
connection per request [M]. So the host's state belongs to the launched session, not to a connection: every
connection of that session feeds the same `RtspServer` (UNKNOWN U5 for other clients). A request without
`Content-Length` has no payload (RFC 2326 4.4); the host's framer (`RtspFramer::for_requests`) ends it at the empty
line. Every answer carries `Content-Length` (ours), so the client never waits for a close. Moonshine needs a parseable
`CSeq` and closes without an answer when it is missing [M]; we answer 400 and let the caller close.
**Order and statuses.** Moonshine checks no order and no `Session` [M]. We enforce 2.2: OPTIONS, DESCRIBE, the three
SETUPs (any order, each once: ours, U5), ANNOUNCE, PLAY. OPTIONS may come at any time and changes nothing else
(RFC 2326 10.1). Moonshine answers only 200, 400 and 500 [M]; we use the RFC 2326 7.1.1 codes: 400 malformed request
or ANNOUNCE payload, 451 a request the offer does not cover (codec, encryption bits, HDR, 4:4:4), 454 a `Session`
that is not this session's, 455 a method out of order, 501 an unknown method (TEARDOWN, GET_PARAMETER...). A refused
request changes no state; the caller decides whether to close.
**Session.** Moonshine sends the fixed id `MoonshineSession` and never reads it back [M]. We send a random id
(8 bytes from the caller's `RandomSource`, hex; RFC 2326 3.4 asks for at least 8 random octets) as
`Session: <id>;timeout = 90` [M]. A `Session` header that is present must carry that id (454 otherwise, and before
the first SETUP any id is wrong); a missing one is accepted unless the host config requires it (U5).
**Answers** [M]: OPTIONS `Public` (we list `OPTIONS, DESCRIBE, SETUP, ANNOUNCE, PLAY`; Moonshine leaves ANNOUNCE
out); DESCRIBE the SDP below; SETUP needs a `Transport` header (400 without), takes the stream from the first
`streamid=<audio|video|control>` of the target (400 otherwise) and answers `Session` and
`Transport: server_port=<port>`; ANNOUNCE and PLAY answer with no payload.
**DESCRIBE lines, in Moonshine's order** [M]: `a=x-ss-general.featureFlags:3`, `a=x-ss-general.encryptionSupported:`
5 or 7 (7 when video encryption is on), `sprop-parameter-sets=AAAAAU`, `a=x-nv-video[0].refPicInvalidation:1`,
`a=rtpmap:98 AV1/90000`, `a=fmtp:96 packetization-mode=1`, then one `a=fmtp:97 surround-params=` per Opus
configuration. Moonshine writes all of them unconditionally; our writer leaves out the invalidation, AV1 and H.264
lines when the host does not offer them. HEVC, HDR and 4:4:4 have no DESCRIBE line (serverinfo, 1.2, U25). Moonshine
rotates the 5.1/7.1 normal-quality mappings with a comment that cites GFE and Moonlight [M*]: not used, U26.
**ANNOUNCE as Moonshine reads it.** Missing or unparseable required attributes give 400 [M]; optional ones fall back
to their default [M]. Our parser keeps the required set and the defaults, refuses out-of-range values instead of
clamping, refuses a known attribute given twice, and counts unknown attributes.
| Attribute | Required? | Default | Accepted (ours unless tagged) | Meaning |
| :-- | :-- | :-- | :-- | :-- |
| `x-nv-video[0].clientViewportWd`, `…Ht` | yes [M] | | 1..=16384 | resolution |
| `x-nv-video[0].maxFPS` | yes [M] | | 1..=1000 (0 refused [M]) | frame rate |
| `x-nv-video[0].packetSize` | yes [M] | | 200..=65471 [M] (Moonshine clamps above its own cap; we refuse) | video packet size |
| `x-ml-video.configuredBitrateKbps` | yes [M] | | 1..=4294967 (×1000 must fit a u32 [M]) | bitrate |
| `x-nv-vqos[0].bitStreamFormat` | yes [M] | | 0 H.264, 1 HEVC, 2 AV1 [M]; others refused [M] | codec |
| `x-nv-vqos[0].fec.minRequiredFecPackets` | yes [M] | | 0..=255 | minimum parity per block |
| `x-nv-vqos[0].qosTrafficType`, `x-nv-aqos.qosTrafficType` | yes [M] | | any u32, kept raw (Moonshine: QoS off for `0` [M]) | DSCP class |
| `x-nv-aqos.packetDuration` | yes [M] | | 1..=120 ms (longest Opus packet, RFC 6716) | audio packet duration |
| `x-nv-video[0].maxNumReferenceFrames` | no | 1 [M] | any u32, raw (what 0 means is [M*]) | reference frames |
| `x-nv-video[0].refPicInvalidation` | no (Moonshine does not read it) | 0: UNKNOWN U6 | 0, 1 | client can invalidate |
| `x-nv-video[0].dynamicRangeMode` | no | 0 [M] | any u32, raw; Moonshine: 0 SDR, 1 HDR [M]; a non-zero value needs the host's HDR offer (ours) | U6 |
| `x-nv-video[0].encoderCscMode` | no | 0 [M] | any u32, raw; the bit layout is [M*] (Moonshine cites Sunshine) | U6 |
| `x-ss-video[0].chromaSamplingType` | no | 0 [M] | 0 4:2:0, 1 4:4:4 [M] | chroma |
| `x-ss-general.encryptionEnabled` | no | 0 [M] | 0..=255, only offered bits (ours) | 2.3 bits |
| `x-nv-audio.surround.enable` | no | 0 [M] | 0, 1 | when 0, the layout comes from launch's `surroundAudioInfo` [M] |
| `x-nv-audio.surround.numChannels` | no | 2 [M] | 1..=8 | channels |
| `x-nv-audio.surround.channelMask` | no | 0x3 [M] | any u32, raw | speaker mask |
| `x-nv-audio.surround.AudioQuality` | no | 1 [M] | 0, 1 | high quality |
`bitStreamFormat` 0/1/2 [M] confirms the values our client sends (`rtsp::sdp`, previously a judgment). Payload caps
(ours): 32 KiB, 1024 non-empty lines, 1024 bytes per line, 512 `a=` attributes; blanks around values are trimmed.
UNKNOWNs left for black-box measurement (Arena Domi Remote and the Moonlight PC app as Lumen's clients, decision D2):
U5 (connection per request, the SETUP target form, whether clients echo `Session`, whether every client starts with
OPTIONS), U6 (whether real clients always send the ten required attributes, `refPicInvalidation`'s default, the
meanings of `dynamicRangeMode` and `encoderCscMode` per client setting, whether `qosTrafficType` is always a number,
how many attributes a real ANNOUNCE has), U26 (mapping rotation).
---
## 3. Control channel (ENet + AES-GCM)
@@ -270,6 +340,38 @@ UNKNOWN U9 (narrowed): anything Sunshine's ENet sends that stock 1.3 does not; t
data` a client offers; whether the client sets non-default ping or timeout values. Settle: the lab capture's control
port datagrams, decoded with our parser (LAB_CAPTURE.md). Until then our client offers stock defaults.
**The accepting side, as stock ENet 1.3 does it** [E] (S-17, S-34; DomiStream `enet::host`, the Lumen host):
- A datagram addressed to `0xFFF` is looked at only for a CONNECT at its start; anything else in it is ignored. A
CONNECT asking for 0 or more than 255 channels is refused. A CONNECT repeated by a client whose connection already
exists (same address, same connect id) is ignored: no second peer, no acknowledgement.
- The CONNECT is **not acknowledged**; the host answers with a reliable VERIFY CONNECT on channel `0xFF` (the
connection channel's first reliable sequence number, 1), and the verify retires the client's connect.
- Session ids: the host's outgoing id is the client's offered *incoming* id (or, for `0xFF`, the slot's previous
outgoing id) plus one, modulo 4, bumped once more if it equals the slot's previous outgoing id; the host's
incoming id likewise from the client's offered *outgoing* id. A fresh slot has `0xFF` for both, so a client offering
`0xFF`/`0xFF` gets 0/0. The verify carries `incoming session = the host's outgoing` and `outgoing session = the
host's incoming`, i.e. both fields from the client's point of view; a sender puts its outgoing id in the header
(only once the remote peer id is known), a receiver drops datagrams whose id is not its incoming id.
- Verify fields: `outgoing peer id` = the host's own peer id (the client addresses it from then on); MTU = the
client's clamped to 576-4096, then at most the host's; window = the client's, at most 65536 when the host's
bandwidth is unlimited, clamped to 4096-65536; channel count = the client's, at most the host's channel limit;
bandwidths = the host's own (0 = unlimited); throttle interval, acceleration and deceleration echoed; connect id
echoed. The connect's `data` word is what the host's connect event reports.
- The peer is connected when the client **acknowledges the verify**. Before that, data, pings and bandwidth or
throttle commands from the client are not taken and not acknowledged (the client sends them again).
- Acknowledgements: a command with the acknowledge flag is acknowledged only while connected, echoing the datagram's
sent time; in a datagram **without** sent time such a command is handled but not acknowledged and the rest of the
datagram is skipped. A failing command also ends the datagram.
- Disconnect from the client while connected: acknowledged (if flagged), the connection closes with the client's
data word. Ping, bandwidth limit and throttle configure need the connected state.
- Unsequenced duplicates are dropped with a window of 1024 groups; groups up to 32 windows ahead move the window,
older or farther ones are dropped.
- The host pings a connected peer when nothing was **received** from it for the ping interval (500 ms by default)
and no reliable command is in flight.
Not in DomiStream's host: the checksum and compression (see above), throttling what it sends by bandwidth, and
unreliable fragments (dropped: every control message is small and reliable).
### 3.2 Encrypted frame
Every control message is wrapped [W4] (little-endian):
@@ -322,6 +424,17 @@ does not match, **ends the session** when it arrives outside the encrypted frame
message is skipped, and so is a frame that fails decryption. Whether Sunshine reads bodies (and which) is what U10
still settles live: the probe sends empty bodies first ([LIVE-INTEROP.md](LIVE-INTEROP.md), table V).
How DomiStream's host side reads the client (`control::host`, for Lumen; ours, on [M] above): frames open with the
client-to-host nonce; a frame that fails, or whose sequence number is not above the last accepted one, is dropped
without moving the replay state (U11: the first number is not checked); a malformed message inside a good frame is
skipped. Bodies of START_B, PERIODIC_PING and the IDR request are ignored, LOSS_STATS and FRAME_STATS are kept raw,
INVALIDATE_REF_FRAMES reads `first`/`last` with missing bytes as 0, INPUT_DATA goes through section 4 (a layout we
cannot read is reported, not fatal), every other type (START_A among them) is skipped. Only control V2 is spoken: a
bare message outside the frame is dropped. Host messages: rumble, trigger rumble, motion event, RGB LED and the
extended termination are sent, reliable on channel 0, numbered from 0; the plain TERMINATION (body U10) and
HDR_MODE (`[M*]`) are refused until measured. Each PERIODIC_PING moves the stop deadline (default 60 s) out; when it
passes, the host reports it once and the caller ends the session.
---
## 4. Input and gamepad packets
+31
View File
@@ -218,3 +218,34 @@ path = "fuzz_targets/video_packetizer_roundtrip.rs"
test = false
doc = false
bench = false
[[bin]]
name = "enet_host"
path = "fuzz_targets/enet_host.rs"
test = false
doc = false
bench = false
[[bin]]
name = "rtsp_server"
path = "fuzz_targets/rtsp_server.rs"
test = false
doc = false
bench = false
[[bin]]
name = "announce"
path = "fuzz_targets/announce.rs"
test = false
doc = false
bench = false
test = false
doc = false
bench = false
[[bin]]
name = "control_host"
path = "fuzz_targets/control_host.rs"
test = false
doc = false
bench = false
+26
View File
@@ -0,0 +1,26 @@
//! Fuzzes the host's ANNOUNCE parser (hostile client SDP).
//! Asserts invariants, not only "no panic": an accepted payload is within every range and cap, and writing it back
//! gives the same config.
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
#![no_main]
use libfuzzer_sys::fuzz_target;
use domistream::rtsp::server::{
MAX_ANNOUNCE_ATTRIBUTES, MAX_AUDIO_PACKET_DURATION_MS, MAX_BITRATE_KBPS, MAX_DIMENSION, MAX_FPS, MAX_PACKET_SIZE,
MIN_PACKET_SIZE, StreamConfig, parse_announce, write_announce,
};
fuzz_target!(|data: &[u8]| {
let Ok(c) = parse_announce(data) else { return };
assert!((1..=MAX_DIMENSION).contains(&c.width) && (1..=MAX_DIMENSION).contains(&c.height));
assert!((1..=MAX_FPS).contains(&c.max_fps));
assert!((MIN_PACKET_SIZE..=MAX_PACKET_SIZE).contains(&c.packet_size));
assert!((1..=MAX_BITRATE_KBPS).contains(&c.bitrate_kbps));
assert!((1..=MAX_AUDIO_PACKET_DURATION_MS).contains(&c.audio_packet_duration_ms));
assert!((1..=8).contains(&c.surround.channels));
assert!(c.unknown_attributes as usize <= MAX_ANNOUNCE_ATTRIBUTES);
let again = parse_announce(&write_announce(&c)).expect("what was accepted writes back");
assert_eq!(again, StreamConfig { unknown_attributes: 0, ..c });
});
+165
View File
@@ -0,0 +1,165 @@
//! Fuzzes the control host: a connected ControlHost fed a mix of raw datagrams, arbitrary plaintexts sealed with
//! the session key (so the decrypted-message path is reached), arbitrary frames inside valid ENet commands, and
//! time steps; plus `parse_client_message` on every chunk.
//! Asserts invariants, not only "no panic": a client message always splits as a message first; kept bodies and
//! reported lengths match the input; outgoing datagrams parse; a message event never outnumbers what was sealed.
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
#![no_main]
use libfuzzer_sys::fuzz_target;
use core::time::Duration;
use domistream::Instant;
use domistream::control::{
ClientControlMessage, ControlCipher, ControlHost, ControlHostConfig, ControlHostEvent, Direction,
parse_client_message, parse_message,
};
use domistream::enet::EnetHostConfig;
use domistream::enet::protocol::{
Command, CommandBody, ConnectParams, Datagram, NO_PEER_ID, encode_datagram, parse_datagram,
};
const PEER_ID: u16 = 3;
const KEY: [u8; 16] = [7; 16];
fn datagram(peer_id: u16, sent_time: u16, commands: Vec<Command>) -> Option<Vec<u8>> {
encode_datagram(&Datagram { peer_id, session_id: 0, sent_time: Some(sent_time), commands }).ok()
}
fn connected() -> ControlHost {
let params = ConnectParams {
outgoing_peer_id: 0,
incoming_session_id: 0xFF,
outgoing_session_id: 0xFF,
mtu: 1400,
window_size: 65536,
channel_count: 1,
incoming_bandwidth: 0,
outgoing_bandwidth: 0,
packet_throttle_interval: 5000,
packet_throttle_acceleration: 2,
packet_throttle_deceleration: 2,
connect_id: 1,
};
let connect = Command {
acknowledge: true,
channel_id: 0xFF,
reliable_sequence: 1,
body: CommandBody::Connect { params, data: 0 },
};
let config = ControlHostConfig {
enet: EnetHostConfig {
peer_id: PEER_ID,
channel_limit: 1,
mtu: 1400,
ping_interval: Duration::from_millis(500),
timeout: Duration::from_secs(10),
},
rikey: KEY,
stop_timeout: Some(Duration::from_secs(2)),
};
let mut h = ControlHost::accept(config, Instant::ZERO, &datagram(NO_PEER_ID, 0, vec![connect]).expect("connect"))
.expect("canned connect");
while h.poll_transmit(Instant::ZERO).is_some() {}
let ack = Command {
acknowledge: false,
channel_id: 0xFF,
reliable_sequence: 1,
body: CommandBody::Acknowledge { received_reliable_sequence: 1, received_sent_time: 0 },
};
h.handle_datagram(Instant::from_micros(1000), &datagram(PEER_ID, 1, vec![ack]).expect("ack")).expect("canned ack");
assert_eq!(h.poll_event(), Some(ControlHostEvent::Connected));
h
}
fn check_parse(chunk: &[u8]) {
let raw = parse_message(chunk);
match parse_client_message(chunk) {
Ok(m) => {
assert!(raw.is_ok(), "a client message must split as a message first");
match m {
ClientControlMessage::Unknown { body_len, .. }
| ClientControlMessage::InputRejected { body_len, .. } => {
assert_eq!(body_len + 4, chunk.len());
}
ClientControlMessage::LossStats(b) | ClientControlMessage::FrameStats(b) => {
assert_eq!(&b[..], &chunk[4..]);
}
_ => {}
}
}
Err(_) => assert!(raw.is_err(), "only the split can fail"),
}
}
fuzz_target!(|data: &[u8]| {
let mut h = connected();
let cipher = ControlCipher::new(KEY);
let mut reliable = 0u16;
let mut sequence = 0u32;
let mut sealed = 0usize;
let mut messages = 0usize;
let mut ms = 2u64;
let mut rest = data;
while let Some((&op, tail)) = rest.split_first() {
if tail.len() < 2 {
break;
}
let len = usize::from(u16::from_be_bytes([tail[0], tail[1]])).min(tail.len() - 2);
let (chunk, t) = tail[2..].split_at(len);
rest = t;
ms += u64::from(op >> 3) * 13;
let now = Instant::from_micros(ms * 1000);
check_parse(chunk);
let wrap = |frame: Vec<u8>, reliable: &mut u16| {
*reliable = reliable.wrapping_add(1);
let c = Command {
acknowledge: true,
channel_id: 0,
reliable_sequence: *reliable,
body: CommandBody::SendReliable(frame),
};
datagram(PEER_ID, (ms & 0xFFFF) as u16, vec![c])
};
let bytes = match op & 0x07 {
// An arbitrary plaintext, sealed with the next sequence number.
0 | 1 | 2 => cipher.seal(sequence, Direction::ClientToHost, chunk).ok().and_then(|f| {
sequence = sequence.wrapping_add(1);
sealed += 1;
wrap(f, &mut reliable)
}),
// An arbitrary plaintext sealed with a sequence number from the chunk (replays, gaps).
3 => {
let seq = chunk.get(..4).map_or(0, |b| u32::from_le_bytes([b[0], b[1], b[2], b[3]]));
cipher.seal(seq, Direction::ClientToHost, chunk).ok().and_then(|f| {
sealed += 1;
wrap(f, &mut reliable)
})
}
// Arbitrary bytes as the frame inside a valid reliable command.
4 => wrap(chunk.to_vec(), &mut reliable),
// A host message.
5 => {
let _ = h.send_rumble(now, u16::from(op), 1, 2);
None
}
// Raw datagram.
_ => Some(chunk.to_vec()),
};
if let Some(b) = bytes {
let _ = h.handle_datagram(now, &b);
}
let _ = h.handle_timeout(now);
while let Some(out) = h.poll_transmit(now) {
parse_datagram(&out).expect("the host's own datagrams parse");
}
while let Some(e) = h.poll_event() {
if let ControlHostEvent::Message(_) = e {
messages += 1;
}
}
assert!(messages <= sealed, "{messages} messages from {sealed} sealed frames");
}
});
+130
View File
@@ -0,0 +1,130 @@
//! Fuzzes the ENet host-side peer: `accept` on the first datagram (or a canned CONNECT, then the verify
//! acknowledged, so the connected state is reached), then a sequence of datagrams, some given our header so they
//! reach the command loop.
//! Asserts invariants, not only "no panic": delivered packets are within MAX_PACKET_BYTES; outgoing datagrams parse
//! and stay within the MTU; a disconnected peer has no deadline.
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
#![no_main]
use libfuzzer_sys::fuzz_target;
use core::time::Duration;
use domistream::Instant;
use domistream::enet::protocol::{
Command, CommandBody, ConnectParams, Datagram, NO_PEER_ID, encode_datagram, parse_datagram,
};
use domistream::enet::{EnetHostConfig, EnetHostEvent, EnetHostPeer, EnetHostState, MAX_PACKET_BYTES};
const PEER_ID: u16 = 3;
fn config() -> EnetHostConfig {
EnetHostConfig {
peer_id: PEER_ID,
channel_limit: 4,
mtu: 1400,
ping_interval: Duration::from_millis(500),
timeout: Duration::from_secs(10),
}
}
fn datagram(peer_id: u16, commands: Vec<Command>) -> Vec<u8> {
encode_datagram(&Datagram { peer_id, session_id: 0, sent_time: Some(0), commands }).expect("canned datagram")
}
fn canned_connect() -> Vec<u8> {
let params = ConnectParams {
outgoing_peer_id: 0,
incoming_session_id: 0xFF,
outgoing_session_id: 0xFF,
mtu: 1400,
window_size: 65536,
channel_count: 2,
incoming_bandwidth: 0,
outgoing_bandwidth: 0,
packet_throttle_interval: 5000,
packet_throttle_acceleration: 2,
packet_throttle_deceleration: 2,
connect_id: 1,
};
let c = Command {
acknowledge: true,
channel_id: 0xFF,
reliable_sequence: 1,
body: CommandBody::Connect { params, data: 0 },
};
datagram(NO_PEER_ID, vec![c])
}
fn drive(h: &mut EnetHostPeer, now: Instant) {
let _ = h.handle_timeout(now);
while let Some(out) = h.poll_transmit(now) {
assert!(out.len() <= h.mtu());
parse_datagram(&out).expect("the host's own datagrams parse");
}
while let Some(e) = h.poll_event() {
if let EnetHostEvent::Received { data, .. } = e {
assert!(data.len() <= MAX_PACKET_BYTES);
}
}
if h.state() == EnetHostState::Disconnected {
assert_eq!(h.poll_timeout(), None);
}
}
/// The next datagram: a flag byte, a 2-byte big-endian length, the bytes.
fn next(rest: &mut &[u8]) -> Option<(u8, Vec<u8>)> {
let (&flags, tail) = rest.split_first()?;
if tail.len() < 2 {
return None;
}
let len = usize::from(u16::from_be_bytes([tail[0], tail[1]])).min(tail.len() - 2);
let (d, t) = tail[2..].split_at(len);
*rest = t;
Some((flags, d.to_vec()))
}
fuzz_target!(|data: &[u8]| {
let Some((&mode, mut rest)) = data.split_first() else { return };
let mut h = if mode & 1 == 0 {
let Some((_, first)) = next(&mut rest) else { return };
match EnetHostPeer::accept(config(), Instant::ZERO, &first) {
Ok(h) => h,
Err(_) => return,
}
} else {
let mut h = EnetHostPeer::accept(config(), Instant::ZERO, &canned_connect()).expect("canned connect");
while h.poll_transmit(Instant::ZERO).is_some() {}
if mode & 2 != 0 {
let ack = Command {
acknowledge: false,
channel_id: 0xFF,
reliable_sequence: 1,
body: CommandBody::Acknowledge { received_reliable_sequence: 1, received_sent_time: 0 },
};
h.handle_datagram(Instant::from_micros(1000), &datagram(PEER_ID, vec![ack])).expect("canned ack");
assert_eq!(h.state(), EnetHostState::Connected);
}
h
};
let mut ms = 1u64;
while let Some((flags, d)) = next(&mut rest) {
ms += u64::from(flags >> 2) * 7;
let now = Instant::from_micros(ms * 1000);
let bytes = if flags & 1 != 0 {
let mut b = (0x8000 | PEER_ID).to_be_bytes().to_vec();
b.extend_from_slice(&((ms & 0xFFFF) as u16).to_be_bytes());
b.extend_from_slice(&d);
b
} else {
d
};
let _ = h.handle_datagram(now, &bytes);
if flags & 2 != 0 {
let _ = h.send(now, flags % 3, domistream::enet::Delivery::Reliable, &bytes);
}
drive(&mut h, now);
}
});
+172
View File
@@ -0,0 +1,172 @@
//! Fuzzes the host's RTSP session with arbitrary requests, optionally after a valid prefix of the negotiation so the
//! later states are reached too.
//! Asserts invariants, not only "no panic": every answer parses with a documented status, 200 exactly when nothing
//! was refused, the state only moves forward and never on a refusal, and the events come once each, in order.
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
#![no_main]
use libfuzzer_sys::fuzz_target;
use domistream::RandomSource;
use domistream::rtsp::client::VideoCodec;
use domistream::rtsp::sdp::FeatureFlags;
use domistream::rtsp::server::{ChromaSampling, StreamConfig, SurroundSettings, parse_announce, write_announce};
use domistream::rtsp::{
EncryptionFlags, HostOffer, OpusConfig, RtspFramer, RtspServer, RtspServerState, ServerConfig, ServerEvent,
StreamPorts, parse_response,
};
struct Fixed(u8);
impl RandomSource for Fixed {
fn fill(&mut self, dest: &mut [u8]) {
dest.fill(self.0);
}
}
fn rank(s: RtspServerState) -> u8 {
match s {
RtspServerState::Options => 0,
RtspServerState::Describe => 1,
RtspServerState::Setup => 2,
RtspServerState::Announce => 3,
RtspServerState::Play => 4,
RtspServerState::Playing => 5,
}
}
fn announce() -> StreamConfig {
StreamConfig {
width: 1920,
height: 1080,
max_fps: 60,
packet_size: 1024,
bitrate_kbps: 20_000,
codec: VideoCodec::Hevc,
min_fec_packets: 2,
video_qos_traffic_type: 5,
audio_packet_duration_ms: 5,
audio_qos_traffic_type: 4,
max_reference_frames: 0,
reference_frame_invalidation: true,
dynamic_range_mode: 0,
encoder_csc_mode: 0,
chroma: ChromaSampling::Yuv420,
encryption: EncryptionFlags(7),
surround: SurroundSettings::default(),
unknown_attributes: 0,
}
}
/// The valid negotiation, one request each.
fn prelude(session: &str) -> Vec<Vec<u8>> {
let body = write_announce(&announce());
let mut v = vec![
b"OPTIONS rtsp://192.0.2.10:48010 RTSP/1.0\r\nCSeq: 1\r\n\r\n".to_vec(),
b"DESCRIBE rtsp://192.0.2.10:48010 RTSP/1.0\r\nCSeq: 2\r\n\r\n".to_vec(),
];
for (i, s) in ["audio", "video", "control"].iter().enumerate() {
v.push(
format!("SETUP streamid={s}/0/0 RTSP/1.0\r\nCSeq: {}\r\nSession: {session}\r\nTransport: x\r\n\r\n", i + 3)
.into_bytes(),
);
}
let mut a = format!("ANNOUNCE streamid=control/13/0 RTSP/1.0\r\nCSeq: 6\r\nContent-Length: {}\r\n\r\n", body.len())
.into_bytes();
a.extend_from_slice(&body);
v.push(a);
v.push(b"PLAY rtsp://192.0.2.10:48010 RTSP/1.0\r\nCSeq: 7\r\n\r\n".to_vec());
// The first SETUP carries no session: none was issued yet.
if let Some(first) = v.get_mut(2) {
*first = b"SETUP streamid=audio/0/0 RTSP/1.0\r\nCSeq: 3\r\nTransport: x\r\n\r\n".to_vec();
}
v
}
struct Checker {
announced: u32,
played: u32,
}
impl Checker {
fn feed(&mut self, s: &mut RtspServer, message: &[u8]) {
let before = s.state();
let reply = s.handle_request(message);
let r = parse_response(&reply.bytes).expect("every answer parses");
assert_eq!(r.status, reply.status);
assert!([200, 400, 451, 454, 455, 501].contains(&reply.status), "status {}", reply.status);
assert_eq!(reply.status == 200, reply.error.is_none());
assert!(rank(s.state()) >= rank(before), "state went back");
if reply.status != 200 {
assert_eq!(s.state(), before, "a refusal changed the state");
}
while let Some(e) = s.poll_event() {
match e {
ServerEvent::Announced(c) => {
assert_eq!(self.announced, 0);
self.announced += 1;
let again = parse_announce(&write_announce(&c)).expect("an accepted ANNOUNCE writes back");
assert_eq!(again, StreamConfig { unknown_attributes: 0, ..c });
}
ServerEvent::PlayRequested => {
assert_eq!((self.announced, self.played), (1, 0));
self.played += 1;
}
}
}
assert_eq!(self.played == 1, s.state() == RtspServerState::Playing);
}
}
fuzz_target!(|data: &[u8]| {
let Some((&mode, rest)) = data.split_first() else { return };
let config = ServerConfig {
ports: StreamPorts { audio: 48000, video: 47998, control: 47999 },
offer: HostOffer {
feature_flags: FeatureFlags(3),
encryption_supported: EncryptionFlags(7),
reference_frame_invalidation: true,
h264: true,
hevc: true,
av1: mode & 0x40 != 0,
hdr: mode & 0x80 != 0,
yuv444: false,
opus_configs: vec![OpusConfig::stereo()],
},
required_encryption: EncryptionFlags(1),
require_session_header: mode & 0x20 != 0,
session_timeout_secs: 90,
};
let mut s = RtspServer::new(config, &mut Fixed(mode)).expect("a valid config");
let mut check = Checker { announced: 0, played: 0 };
let session = s.session_id().to_string();
// Bits 2..=4: how many valid requests come first (0..=7).
for m in prelude(&session).iter().take(usize::from((mode >> 2) & 0x07)) {
check.feed(&mut s, m);
}
if mode & 0x01 == 0 {
// Messages separated by NUL bytes, each fed whole.
for m in rest.split(|b| *b == 0).take(32) {
check.feed(&mut s, m);
}
} else {
// A byte stream through the request framer.
let mut f = RtspFramer::for_requests();
for chunk in rest.chunks(if mode & 0x02 == 0 { 7 } else { 512 }) {
if f.push(chunk).is_err() {
return;
}
loop {
match f.next_message() {
Ok(Some(m)) => check.feed(&mut s, &m),
Ok(None) => break,
Err(_) => return,
}
}
}
if let Ok(Some(m)) = f.finish() {
check.feed(&mut s, &m);
}
}
});