diff --git a/crates/domistream/src/control/host.rs b/crates/domistream/src/control/host.rs new file mode 100644 index 0000000..86cf126 --- /dev/null +++ b/crates/domistream/src/control/host.rs @@ -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, +} + +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", &"") + .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), + /// `FRAME_STATS`, body kept as it came (layout UNKNOWN U10). + FrameStats(Vec), + /// 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 { + 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> { + 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> { + 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 = [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 = [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, + stop_timeout: Option, + stop: Option, + events: VecDeque, +} + +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 { + 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) -> Result<()> { + self.send(now, &HostMessage::HdrMode { enabled, metadata }) + } + + /// The next datagram to send. + pub fn poll_transmit(&mut self, now: Instant) -> Option> { + self.enet.poll_transmit(now) + } + + /// The next event. + pub fn poll_event(&mut self) -> Option { + self.events.pop_front() + } + + /// When [`Self::handle_timeout`] is due (ENet timers or the stop deadline). + #[must_use] + pub fn poll_timeout(&self) -> Option { + 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 { + if self.enet.state() == EnetHostState::Disconnected { + return None; + } + self.stop.map(|s| s.deadline()) + } +} diff --git a/crates/domistream/src/control/mod.rs b/crates/domistream/src/control/mod.rs index c0ec5cc..967e48b 100644 --- a/crates/domistream/src/control/mod.rs +++ b/crates/domistream/src/control/mod.rs @@ -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. diff --git a/crates/domistream/src/enet/host.rs b/crates/domistream/src/enet/host.rs new file mode 100644 index 0000000..3c3252e --- /dev/null +++ b/crates/domistream/src/enet/host.rs @@ -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, + }, + /// 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 { + 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, + outgoing: VecDeque, + queued_packets: usize, + resend: VecDeque, + acks: VecDeque, + in_flight: Vec, + reassemblies: Vec, + events: VecDeque, + last_receive: Instant, + srtt: Option, + 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 { + 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) { + 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, 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, 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> { + let budget = self.mtu; + let mut size = 4; + let mut commands: Vec = 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 { + 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 { + 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 { + self.srtt + } + + /// The configuration. + #[must_use] + pub const fn config(&self) -> &EnetHostConfig { + &self.config + } +} diff --git a/crates/domistream/src/enet/mod.rs b/crates/domistream/src/enet/mod.rs index 8448d93..76a42e3 100644 --- a/crates/domistream/src/enet/mod.rs +++ b/crates/domistream/src/enet/mod.rs @@ -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. diff --git a/crates/domistream/src/lib.rs b/crates/domistream/src/lib.rs index b3abff6..7e00523 100644 --- a/crates/domistream/src/lib.rs +++ b/crates/domistream/src/lib.rs @@ -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) | diff --git a/crates/domistream/tests/alloc_caps_host.rs b/crates/domistream/tests/alloc_caps_host.rs new file mode 100644 index 0000000..0481854 --- /dev/null +++ b/crates/domistream/tests/alloc_caps_host.rs @@ -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(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 { + 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::(), 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(); +} diff --git a/crates/domistream/tests/common/mod.rs b/crates/domistream/tests/common/mod.rs index 8838ee0..10f33d4 100644 --- a/crates/domistream/tests/common/mod.rs +++ b/crates/domistream/tests/common/mod.rs @@ -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. diff --git a/crates/domistream/tests/common/wire.rs b/crates/domistream/tests/common/wire.rs new file mode 100644 index 0000000..104b6ba --- /dev/null +++ b/crates/domistream/tests/common/wire.rs @@ -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>; + /// A datagram arrived. + fn receive(&mut self, now: Instant, datagram: &[u8]); + /// When this side wants [`Endpoint::tick`]. + fn deadline(&self) -> Option; + /// 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)>, + 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) { + 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 { + self.queue.iter().map(|(d, _, _)| *d).min() + } + + /// Datagrams due by `now_ms`, in delivery order. + pub fn due(&mut self, now_ms: u64) -> Vec> { + let mut ready: Vec<(u64, u64, Vec)> = 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 { + pub client: C, + pub host: H, + pub to_host: Link, + pub to_client: Link, + pub now_ms: u64, +} + +impl Wire { + 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 { + [ + 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); + } +} diff --git a/crates/domistream/tests/control_host.rs b/crates/domistream/tests/control_host.rs new file mode 100644 index 0000000..a069a9d --- /dev/null +++ b/crates/domistream/tests/control_host.rs @@ -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) -> 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 { + 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, +} + +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 { + 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> { + 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 { + 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)>, + events: Vec, +} + +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) { + self.enet.send(now, 0, Delivery::Reliable, &frame).unwrap(); + } + + fn seal(&mut self, plain: &[u8]) -> Vec { + 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> { + 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 { + 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, + events: Vec, + /// When each PingTimedOut was reported, ms. + ping_timeouts: Vec, +} + +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 { + 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 { + let out: Vec = 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> { + 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 { + 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, seed: u64) -> Wire { + 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, seed: u64) -> Wire { + 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 { + 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::>() + ); +} + +// ================================================================================================ 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 = 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 = (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::>()); + assert_eq!( + w.client.messages(), + (0..120u16) + .map(|i| HostMessage::Rumble { controller: 0, low_frequency: i, high_frequency: 0 }) + .collect::>() + ); + 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::(), 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::(), dy in any::(), first in any::(), last in any::()) { + 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::(), 0..120), 0..16), + raws in proptest::collection::vec(proptest::collection::vec(any::(), 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()); + } +} diff --git a/crates/domistream/tests/enet_host.rs b/crates/domistream/tests/enet_host.rs new file mode 100644 index 0000000..72760f5 --- /dev/null +++ b/crates/domistream/tests/enet_host.rs @@ -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, + 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> { + 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> { + 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 { + 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, + events: Vec, + refused: usize, + /// Every datagram the host sent, parsed. + sent: Vec, + 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> { + 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> { + 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 { + 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; + +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 { + 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, commands: Vec) -> Vec { + encode_datagram(&Datagram { peer_id: HOST_PEER_ID, session_id, sent_time, commands }).unwrap() +} + +fn transmitted(peer: &mut EnetHostPeer, t: Instant) -> Vec { + 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 { + 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> = + (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> = + (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 = (0..5000u32).map(|i| (i * 7) as u8).collect(); + let down: Vec = (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> = 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 = events(&mut h); + assert_eq!( + got, + [b"1", b"2", b"3"].iter().map(|d| EnetHostEvent::Received { channel: 0, data: d.to_vec() }).collect::>() + ); + 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 = 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>) { + 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::>()); + assert_eq!(down, (0..200u32).map(|i| (i + 10_000).to_le_bytes().to_vec()).collect::>()); + 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::(), 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::(), proptest::collection::vec(any::(), 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::(), + 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::>()); + prop_assert_eq!(down, (0..40u32).map(|i| (i + 10_000).to_le_bytes().to_vec()).collect::>()); + } +} diff --git a/docs/CLEAN_ROOM.md b/docs/CLEAN_ROOM.md index 4d6e33a..332f640 100644 --- a/docs/CLEAN_ROOM.md +++ b/docs/CLEAN_ROOM.md @@ -96,3 +96,4 @@ All entries by the DomiStream protocol engineer. Pinned commits are the ones rea | 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=`; 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. | diff --git a/docs/PROTOCOL.md b/docs/PROTOCOL.md index 0738bef..1cacee6 100644 --- a/docs/PROTOCOL.md +++ b/docs/PROTOCOL.md @@ -340,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): @@ -392,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 diff --git a/fuzz/Cargo.toml b/fuzz/Cargo.toml index 0509116..5f9fa17 100644 --- a/fuzz/Cargo.toml +++ b/fuzz/Cargo.toml @@ -219,6 +219,13 @@ 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" @@ -232,3 +239,13 @@ 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 diff --git a/fuzz/fuzz_targets/control_host.rs b/fuzz/fuzz_targets/control_host.rs new file mode 100644 index 0000000..0b4fced --- /dev/null +++ b/fuzz/fuzz_targets/control_host.rs @@ -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) -> Option> { + 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, 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"); + } +}); diff --git a/fuzz/fuzz_targets/enet_host.rs b/fuzz/fuzz_targets/enet_host.rs new file mode 100644 index 0000000..50314f2 --- /dev/null +++ b/fuzz/fuzz_targets/enet_host.rs @@ -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) -> Vec { + encode_datagram(&Datagram { peer_id, session_id: 0, sent_time: Some(0), commands }).expect("canned datagram") +} + +fn canned_connect() -> Vec { + 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)> { + 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); + } +});