//! 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()) } }