From 67ae663764f7be1df9ab6e62ee34479aa11cb1b2 Mon Sep 17 00:00:00 2001 From: mnovak Date: Fri, 4 Dec 2026 12:24:14 +0100 Subject: [PATCH] [domistream] Control host: tests first (ControlStream against ControlHost, replay, stop deadline), API stubs Input arrives typed and byte-identical to what the client encoded; host rumble, trigger rumble, LED, motion and termination reach the client; replays, forgeries and malformed messages are dropped; the stop deadline ends a session without PERIODIC_PING. Alloc caps for the host parsers. They fail against the stubs. --- crates/domistream/src/control/host.rs | 252 +++++++ crates/domistream/src/control/mod.rs | 5 + crates/domistream/tests/alloc_caps_host.rs | 156 +++++ crates/domistream/tests/control_host.rs | 768 +++++++++++++++++++++ 4 files changed, 1181 insertions(+) create mode 100644 crates/domistream/src/control/host.rs create mode 100644 crates/domistream/tests/alloc_caps_host.rs create mode 100644 crates/domistream/tests/control_host.rs diff --git a/crates/domistream/src/control/host.rs b/crates/domistream/src/control/host.rs new file mode 100644 index 0000000..675108d --- /dev/null +++ b/crates/domistream/src/control/host.rs @@ -0,0 +1,252 @@ +//! The host side of the control stream (`docs/PROTOCOL.md` 3.2, 3.3), over one [`EnetHostPeer`]. + +use core::time::Duration; + +use super::message::{HdrMetadata, HostMessage}; +use crate::enet::{EnetHostConfig, EnetHostPeer}; +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; + +/// 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`; `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. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum ClientControlMessage { + /// `START_B`: start video and audio. + StartB, + /// `PERIODIC_PING`: the client is still there. + PeriodicPing, + /// `INPUT_DATA` with a known layout. + Input(InputEvent), + /// `INPUT_DATA` that [`crate::input::parse_input`] refused (unknown or unsupported layout). + InputRejected { + /// Body length. + body_len: usize, + /// Why. + error: Error, + }, + /// `IDR_FRAME`: send a key frame. + IdrRequest, + /// `INVALIDATE_REF_FRAMES`: stop referencing frames `first..=last`. + 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 (including `START_A`), skipped. + Unknown { + /// Type code. + message_type: u16, + /// Body length. + body_len: usize, + }, +} + +/// Interprets a decrypted message from the client. +/// +/// # Errors +/// As [`super::message::parse_message`]. +pub fn parse_client_message(message: &[u8]) -> Result { + let _ = message; + Err(Error::Unimplemented) +} + +/// Serializes a message to the client (type, length, body), ready for [`super::ControlCipher::seal`]. +/// +/// # Errors +/// [`Error::Unsupported`] for a message whose layout is not known well enough to send. +pub fn encode_host_message(message: &HostMessage) -> Result> { + let _ = message; + Err(Error::Unimplemented) +} + +/// The stop deadline of PROTOCOL.md 3.3: each `PERIODIC_PING` pushes it out by the timeout. +#[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`. + pub fn on_ping(&mut self, now: Instant) { + let _ = now; + } + + /// 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 { + let _ = now; + false + } +} + +/// 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. + Dropped, + /// No `PERIODIC_PING` within the stop timeout: the session should end. + 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, +} + +impl ControlHost { + /// Accepts a client's ENet CONNECT datagram. + /// + /// # Errors + /// As [`EnetHostPeer::accept`]. + pub fn accept(config: ControlHostConfig, now: Instant, datagram: &[u8]) -> Result { + let _ = (config, now, datagram); + Err(Error::Unimplemented) + } + + /// Feeds one datagram from the client. + /// + /// # Errors + /// As [`EnetHostPeer::handle_datagram`]. + pub fn handle_datagram(&mut self, now: Instant, datagram: &[u8]) -> Result<()> { + let _ = (now, datagram); + Err(Error::Unimplemented) + } + + /// Seals and queues a message to the client. + /// + /// # Errors + /// As [`encode_host_message`] and [`EnetHostPeer::send`]. + pub fn send(&mut self, now: Instant, message: &HostMessage) -> Result<()> { + let _ = (now, message); + Err(Error::Unimplemented) + } + + /// 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). + /// + /// # 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: not implemented. + /// + /// # Errors + /// Always [`Error::Unsupported`]. + 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 { + None + } + + /// When [`Self::handle_timeout`] is due. + #[must_use] + pub fn poll_timeout(&self) -> Option { + None + } + + /// Advances timers. + /// + /// # Errors + /// As [`EnetHostPeer::handle_timeout`]. + pub fn handle_timeout(&mut self, now: Instant) -> Result<()> { + let _ = now; + Err(Error::Unimplemented) + } + + /// Closes the stream gracefully (ENet disconnect). + /// + /// # Errors + /// [`Error::Closed`] when already closed. + pub fn close(&mut self, now: Instant) -> Result<()> { + 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. + #[must_use] + pub const fn stop_deadline(&self) -> Option { + None + } +} 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/tests/alloc_caps_host.rs b/crates/domistream/tests/alloc_caps_host.rs new file mode 100644 index 0000000..54d1c4e --- /dev/null +++ b/crates/domistream/tests/alloc_caps_host.rs @@ -0,0 +1,156 @@ +//! "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/control_host.rs b/crates/domistream/tests/control_host.rs new file mode 100644 index 0000000..89310b9 --- /dev/null +++ b/crates/domistream/tests/control_host.rs @@ -0,0 +1,768 @@ +//! 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[30] ^= 0x10; + c.send_frame(t, bad); // bad tag + 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()); + } +}