[domistream] Control host: ControlHost (client frames opened with replay refusal, typed client messages, host messages, stop deadline)
parse_client_message types START_B, PERIODIC_PING, INPUT_DATA (through input::parse_input), IDR, INVALIDATE_REF_FRAMES, LOSS_STATS and FRAME_STATS (raw bodies) and skips anything else as Unknown. encode_host_message sends rumble, trigger rumble, motion, RGB LED and the extended termination; the plain termination (U10) and HDR_MODE (GPL-provenance layout) stay Unsupported. StopDeadline ends a session without PERIODIC_PING (default 60 s).
This commit is contained in:
@@ -1,9 +1,22 @@
|
|||||||
//! The host side of the control stream (`docs/PROTOCOL.md` 3.2, 3.3), over one [`EnetHostPeer`].
|
//! 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 core::time::Duration;
|
||||||
|
use std::collections::VecDeque;
|
||||||
|
|
||||||
use super::message::{HdrMetadata, HostMessage};
|
use super::frame::{ControlCipher, Direction};
|
||||||
use crate::enet::{EnetHostConfig, EnetHostPeer};
|
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::input::InputEvent;
|
||||||
use crate::{Error, Instant, Result};
|
use crate::{Error, Instant, Result};
|
||||||
|
|
||||||
@@ -11,6 +24,8 @@ use crate::{Error, Instant, Result};
|
|||||||
pub const DEFAULT_STOP_TIMEOUT: Duration = Duration::from_secs(60);
|
pub const DEFAULT_STOP_TIMEOUT: Duration = Duration::from_secs(60);
|
||||||
/// The extended termination code for a graceful end (PROTOCOL.md 3.3).
|
/// The extended termination code for a graceful end (PROTOCOL.md 3.3).
|
||||||
pub const TERMINATION_GRACEFUL: u32 = 0x8003_0023;
|
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.
|
/// Settings of the host side of one control stream. `Debug` never prints the key.
|
||||||
#[derive(Clone, PartialEq, Eq)]
|
#[derive(Clone, PartialEq, Eq)]
|
||||||
@@ -19,7 +34,8 @@ pub struct ControlHostConfig {
|
|||||||
pub enet: EnetHostConfig,
|
pub enet: EnetHostConfig,
|
||||||
/// The session's `rikey`.
|
/// The session's `rikey`.
|
||||||
pub rikey: [u8; 16],
|
pub rikey: [u8; 16],
|
||||||
/// End the session after this long without a `PERIODIC_PING`; `None` never ends it for that.
|
/// End the session after this long without a `PERIODIC_PING` ([`DEFAULT_STOP_TIMEOUT`] is Moonshine's);
|
||||||
|
/// `None` never ends it for that.
|
||||||
pub stop_timeout: Option<Duration>,
|
pub stop_timeout: Option<Duration>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -33,25 +49,27 @@ impl core::fmt::Debug for ControlHostConfig {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A message from the client, as the host reads it.
|
/// A message from the client, as the host reads it (PROTOCOL.md 3.3).
|
||||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
pub enum ClientControlMessage {
|
pub enum ClientControlMessage {
|
||||||
/// `START_B`: start video and audio.
|
/// `START_B`: start video and audio. Any body is ignored (PROTOCOL.md 3.3: Moonshine reads none).
|
||||||
StartB,
|
StartB,
|
||||||
/// `PERIODIC_PING`: the client is still there.
|
/// `PERIODIC_PING`: the client is still there. Any body is ignored.
|
||||||
PeriodicPing,
|
PeriodicPing,
|
||||||
/// `INPUT_DATA` with a known layout.
|
/// `INPUT_DATA` with a known layout (PROTOCOL.md 4).
|
||||||
Input(InputEvent),
|
Input(InputEvent),
|
||||||
/// `INPUT_DATA` that [`crate::input::parse_input`] refused (unknown or unsupported layout).
|
/// `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 {
|
InputRejected {
|
||||||
/// Body length.
|
/// Body length.
|
||||||
body_len: usize,
|
body_len: usize,
|
||||||
/// Why.
|
/// Why.
|
||||||
error: Error,
|
error: Error,
|
||||||
},
|
},
|
||||||
/// `IDR_FRAME`: send a key frame.
|
/// `IDR_FRAME`: send a key frame. Any body is ignored.
|
||||||
IdrRequest,
|
IdrRequest,
|
||||||
/// `INVALIDATE_REF_FRAMES`: stop referencing frames `first..=last`.
|
/// `INVALIDATE_REF_FRAMES`: stop referencing frames `first..=last`. A field the body is too short for reads
|
||||||
|
/// as 0 (PROTOCOL.md 3.3).
|
||||||
InvalidateRefFrames {
|
InvalidateRefFrames {
|
||||||
/// First lost frame.
|
/// First lost frame.
|
||||||
first: u32,
|
first: u32,
|
||||||
@@ -62,7 +80,7 @@ pub enum ClientControlMessage {
|
|||||||
LossStats(Vec<u8>),
|
LossStats(Vec<u8>),
|
||||||
/// `FRAME_STATS`, body kept as it came (layout UNKNOWN U10).
|
/// `FRAME_STATS`, body kept as it came (layout UNKNOWN U10).
|
||||||
FrameStats(Vec<u8>),
|
FrameStats(Vec<u8>),
|
||||||
/// Any other type (including `START_A`), skipped.
|
/// Any other type, `START_A` among them (PROTOCOL.md 3.3: skipped inside the encrypted frame).
|
||||||
Unknown {
|
Unknown {
|
||||||
/// Type code.
|
/// Type code.
|
||||||
message_type: u16,
|
message_type: u16,
|
||||||
@@ -71,25 +89,94 @@ pub enum ClientControlMessage {
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Interprets a decrypted message from the client.
|
/// 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
|
/// # Errors
|
||||||
/// As [`super::message::parse_message`].
|
/// As [`parse_message`]: [`Error::TooLarge`] over [`MAX_MESSAGE_BYTES`], [`Error::Truncated`] under the 4-byte
|
||||||
|
/// header, [`Error::Malformed`] when the length field does not match.
|
||||||
pub fn parse_client_message(message: &[u8]) -> Result<ClientControlMessage> {
|
pub fn parse_client_message(message: &[u8]) -> Result<ClientControlMessage> {
|
||||||
let _ = message;
|
let raw = parse_message(message)?;
|
||||||
Err(Error::Unimplemented)
|
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() },
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Serializes a message to the client (type, length, body), ready for [`super::ControlCipher::seal`].
|
/// Type, length, body.
|
||||||
|
fn framed(message_type: MessageType, body: &[u8]) -> Result<Vec<u8>> {
|
||||||
|
crate::util::cap("host message", MAX_MESSAGE_BYTES, MESSAGE_HEADER_LEN.saturating_add(body.len()))?;
|
||||||
|
let len = u16::try_from(body.len()).map_err(|_| crate::util::malformed("host message length"))?;
|
||||||
|
let mut m = Vec::with_capacity(MESSAGE_HEADER_LEN + body.len());
|
||||||
|
m.extend_from_slice(&(message_type as u16).to_le_bytes());
|
||||||
|
m.extend_from_slice(&len.to_le_bytes());
|
||||||
|
m.extend_from_slice(body);
|
||||||
|
Ok(m)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Serializes a message to the client (type, length, body), ready for [`ControlCipher::seal`]: the inverse of
|
||||||
|
/// [`super::parse_host_message`]. Bodies are little-endian (UNKNOWN U23), the extended termination code big-endian
|
||||||
|
/// (PROTOCOL.md 3.3).
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`Error::Unsupported`] for a message whose layout is not known well enough to send.
|
/// [`Error::Unsupported`] for a message whose layout is not known well enough to send: the plain `TERMINATION`
|
||||||
|
/// (body UNKNOWN U10), `HDR_MODE` (layout of GPL provenance, `[M*]`) and [`HostMessage::Other`].
|
||||||
pub fn encode_host_message(message: &HostMessage) -> Result<Vec<u8>> {
|
pub fn encode_host_message(message: &HostMessage) -> Result<Vec<u8>> {
|
||||||
let _ = message;
|
match *message {
|
||||||
Err(Error::Unimplemented)
|
HostMessage::Rumble { controller, low_frequency, high_frequency } => {
|
||||||
|
let mut b = vec![0u8; 4];
|
||||||
|
for v in [controller, low_frequency, high_frequency] {
|
||||||
|
b.extend_from_slice(&v.to_le_bytes());
|
||||||
|
}
|
||||||
|
framed(MessageType::RumbleData, &b)
|
||||||
|
}
|
||||||
|
HostMessage::RumbleTriggers { controller, left, right } => {
|
||||||
|
let b: Vec<u8> = [controller, left, right].iter().flat_map(|v| v.to_le_bytes()).collect();
|
||||||
|
framed(MessageType::RumbleTriggers, &b)
|
||||||
|
}
|
||||||
|
HostMessage::MotionEvent { controller, rate_hz, kind } => {
|
||||||
|
let mut b: Vec<u8> = [controller, rate_hz].iter().flat_map(|v| v.to_le_bytes()).collect();
|
||||||
|
b.push(match kind {
|
||||||
|
super::message::MotionKind::Accelerometer => 1,
|
||||||
|
super::message::MotionKind::Gyroscope => 2,
|
||||||
|
});
|
||||||
|
framed(MessageType::MotionEvent, &b)
|
||||||
|
}
|
||||||
|
HostMessage::RgbLed { controller, r, g, b } => {
|
||||||
|
let mut body = controller.to_le_bytes().to_vec();
|
||||||
|
body.extend_from_slice(&[r, g, b]);
|
||||||
|
framed(MessageType::RgbLed, &body)
|
||||||
|
}
|
||||||
|
HostMessage::Termination { error_code: Some(code) } => {
|
||||||
|
framed(MessageType::TerminationExtended, &code.to_be_bytes())
|
||||||
|
}
|
||||||
|
HostMessage::Termination { error_code: None } => {
|
||||||
|
Err(Error::Unsupported { what: "the plain TERMINATION message (body UNKNOWN U10)" })
|
||||||
|
}
|
||||||
|
// HDR_MODE: Moonshine's layout for it cites Sunshine, so it is GPL provenance ([M*], CLEAN_ROOM.md) and
|
||||||
|
// stays unused until our own measurement settles it. Lumen streams SDR until then.
|
||||||
|
HostMessage::HdrMode { .. } => {
|
||||||
|
Err(Error::Unsupported { what: "HDR_MODE (its layout is GPL provenance [M*], not measured yet)" })
|
||||||
|
}
|
||||||
|
HostMessage::Other { .. } => Err(Error::Unsupported { what: "a host message without a known layout" }),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The stop deadline of PROTOCOL.md 3.3: each `PERIODIC_PING` pushes it out by the timeout.
|
/// 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)]
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||||
pub struct StopDeadline {
|
pub struct StopDeadline {
|
||||||
timeout: Duration,
|
timeout: Duration,
|
||||||
@@ -103,9 +190,9 @@ impl StopDeadline {
|
|||||||
Self { timeout, deadline: now.saturating_add(timeout) }
|
Self { timeout, deadline: now.saturating_add(timeout) }
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A ping arrived at `now`.
|
/// A ping arrived at `now`. The deadline never moves back.
|
||||||
pub fn on_ping(&mut self, now: Instant) {
|
pub fn on_ping(&mut self, now: Instant) {
|
||||||
let _ = now;
|
self.deadline = self.deadline.max(now.saturating_add(self.timeout));
|
||||||
}
|
}
|
||||||
|
|
||||||
/// When the session ends without another ping.
|
/// When the session ends without another ping.
|
||||||
@@ -117,8 +204,7 @@ impl StopDeadline {
|
|||||||
/// Whether the deadline has passed at `now`.
|
/// Whether the deadline has passed at `now`.
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn expired(&self, now: Instant) -> bool {
|
pub fn expired(&self, now: Instant) -> bool {
|
||||||
let _ = now;
|
now >= self.deadline
|
||||||
false
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -129,9 +215,11 @@ pub enum ControlHostEvent {
|
|||||||
Connected,
|
Connected,
|
||||||
/// A message from the client.
|
/// A message from the client.
|
||||||
Message(ClientControlMessage),
|
Message(ClientControlMessage),
|
||||||
/// A client frame failed its tag, came out of order or held a malformed message, and was skipped.
|
/// A client frame failed its tag, came out of order or held a malformed message, and was skipped (counted,
|
||||||
|
/// never fatal).
|
||||||
Dropped,
|
Dropped,
|
||||||
/// No `PERIODIC_PING` within the stop timeout: the session should end.
|
/// No `PERIODIC_PING` within the stop timeout: the session should end. Reported once; a later ping starts the
|
||||||
|
/// clock again.
|
||||||
PingTimedOut,
|
PingTimedOut,
|
||||||
/// The client closed the stream.
|
/// The client closed the stream.
|
||||||
Disconnected,
|
Disconnected,
|
||||||
@@ -143,41 +231,118 @@ pub enum ControlHostEvent {
|
|||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct ControlHost {
|
pub struct ControlHost {
|
||||||
enet: EnetHostPeer,
|
enet: EnetHostPeer,
|
||||||
|
cipher: ControlCipher,
|
||||||
|
/// Next sequence number to seal with; `u32::MAX + 1` once the space is used up.
|
||||||
|
next_sequence: u64,
|
||||||
|
/// Highest client sequence number accepted so far.
|
||||||
|
last_client_sequence: Option<u32>,
|
||||||
|
stop_timeout: Option<Duration>,
|
||||||
|
stop: Option<StopDeadline>,
|
||||||
|
events: VecDeque<ControlHostEvent>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ControlHost {
|
impl ControlHost {
|
||||||
/// Accepts a client's ENet CONNECT datagram.
|
/// Accepts a client's ENet CONNECT datagram (see [`crate::enet::host`] for the caller's demultiplexing).
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// As [`EnetHostPeer::accept`].
|
/// As [`EnetHostPeer::accept`].
|
||||||
pub fn accept(config: ControlHostConfig, now: Instant, datagram: &[u8]) -> Result<Self> {
|
pub fn accept(config: ControlHostConfig, now: Instant, datagram: &[u8]) -> Result<Self> {
|
||||||
let _ = (config, now, datagram);
|
Ok(Self {
|
||||||
Err(Error::Unimplemented)
|
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.
|
/// Feeds one datagram from the client.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// As [`EnetHostPeer::handle_datagram`].
|
/// 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<()> {
|
pub fn handle_datagram(&mut self, now: Instant, datagram: &[u8]) -> Result<()> {
|
||||||
let _ = (now, datagram);
|
let r = self.enet.handle_datagram(now, datagram);
|
||||||
Err(Error::Unimplemented)
|
self.drain(now);
|
||||||
|
r
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Seals and queues a message to the client.
|
/// Seals and queues a message to the client (reliable, channel 0).
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// As [`encode_host_message`] and [`EnetHostPeer::send`].
|
/// 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<()> {
|
pub fn send(&mut self, now: Instant, message: &HostMessage) -> Result<()> {
|
||||||
let _ = (now, message);
|
let plain = encode_host_message(message)?;
|
||||||
Err(Error::Unimplemented)
|
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.
|
/// Rumbles a controller.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// As [`Self::send`].
|
/// As [`Self::send`].
|
||||||
pub fn send_rumble(&mut self, now: Instant, controller: u16, low_frequency: u16, high_frequency: u16) -> Result<()> {
|
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 })
|
self.send(now, &HostMessage::Rumble { controller, low_frequency, high_frequency })
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -189,7 +354,8 @@ impl ControlHost {
|
|||||||
self.send(now, &HostMessage::RumbleTriggers { controller, left, right })
|
self.send(now, &HostMessage::RumbleTriggers { controller, left, right })
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Ends the session with an extended termination code ([`TERMINATION_GRACEFUL`] for a normal end).
|
/// 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
|
/// # Errors
|
||||||
/// As [`Self::send`].
|
/// As [`Self::send`].
|
||||||
@@ -197,10 +363,11 @@ impl ControlHost {
|
|||||||
self.send(now, &HostMessage::Termination { error_code: Some(error_code) })
|
self.send(now, &HostMessage::Termination { error_code: Some(error_code) })
|
||||||
}
|
}
|
||||||
|
|
||||||
/// HDR mode: not implemented.
|
/// 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
|
/// # Errors
|
||||||
/// Always [`Error::Unsupported`].
|
/// Always [`Error::Unsupported`]; nothing is queued.
|
||||||
pub fn send_hdr_mode(&mut self, now: Instant, enabled: bool, metadata: Option<HdrMetadata>) -> Result<()> {
|
pub fn send_hdr_mode(&mut self, now: Instant, enabled: bool, metadata: Option<HdrMetadata>) -> Result<()> {
|
||||||
self.send(now, &HostMessage::HdrMode { enabled, metadata })
|
self.send(now, &HostMessage::HdrMode { enabled, metadata })
|
||||||
}
|
}
|
||||||
@@ -212,29 +379,39 @@ impl ControlHost {
|
|||||||
|
|
||||||
/// The next event.
|
/// The next event.
|
||||||
pub fn poll_event(&mut self) -> Option<ControlHostEvent> {
|
pub fn poll_event(&mut self) -> Option<ControlHostEvent> {
|
||||||
None
|
self.events.pop_front()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// When [`Self::handle_timeout`] is due.
|
/// When [`Self::handle_timeout`] is due (ENet timers or the stop deadline).
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn poll_timeout(&self) -> Option<Instant> {
|
pub fn poll_timeout(&self) -> Option<Instant> {
|
||||||
None
|
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.
|
/// Advances timers: ENet's, then the stop deadline ([`ControlHostEvent::PingTimedOut`]).
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// As [`EnetHostPeer::handle_timeout`].
|
/// As [`EnetHostPeer::handle_timeout`].
|
||||||
pub fn handle_timeout(&mut self, now: Instant) -> Result<()> {
|
pub fn handle_timeout(&mut self, now: Instant) -> Result<()> {
|
||||||
let _ = now;
|
let r = self.enet.handle_timeout(now);
|
||||||
Err(Error::Unimplemented)
|
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).
|
/// Closes the stream gracefully (ENet disconnect; messages queued before it go out first).
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`Error::Closed`] when already closed.
|
/// [`Error::Closed`] when already closed.
|
||||||
pub fn close(&mut self, now: Instant) -> Result<()> {
|
pub fn close(&mut self, now: Instant) -> Result<()> {
|
||||||
|
self.stop = None;
|
||||||
self.enet.disconnect(now, 0)
|
self.enet.disconnect(now, 0)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -244,9 +421,13 @@ impl ControlHost {
|
|||||||
&self.enet
|
&self.enet
|
||||||
}
|
}
|
||||||
|
|
||||||
/// When the session ends without another `PERIODIC_PING`, while that clock runs.
|
/// 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]
|
#[must_use]
|
||||||
pub const fn stop_deadline(&self) -> Option<Instant> {
|
pub fn stop_deadline(&self) -> Option<Instant> {
|
||||||
None
|
if self.enet.state() == EnetHostState::Disconnected {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
self.stop.map(|s| s.deadline())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -21,8 +21,8 @@
|
|||||||
//! | [`http`] | serverinfo, applist, launch/resume/cancel (section 1) |
|
//! | [`http`] | serverinfo, applist, launch/resume/cancel (section 1) |
|
||||||
//! | [`pairing`] | the PIN handshake and the client certificate (section 1.5) |
|
//! | [`pairing`] | the PIN handshake and the client certificate (section 1.5) |
|
||||||
//! | [`rtsp`] | OPTIONS, DESCRIBE, SETUP, ANNOUNCE, PLAY and SDP (section 2) |
|
//! | [`rtsp`] | OPTIONS, DESCRIBE, SETUP, ANNOUNCE, PLAY and SDP (section 2) |
|
||||||
//! | [`enet`] | the ENet-compatible reliable UDP layer under the control stream (section 3.1) |
|
//! | [`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 (sections 3.2, 3.3) |
|
//! | [`control`] | AES-GCM framing and control messages, client and host side (sections 3.2, 3.3) |
|
||||||
//! | [`input`] | input and gamepad packets (section 4) |
|
//! | [`input`] | input and gamepad packets (section 4) |
|
||||||
//! | [`rtp`] | the RTP header shared by video and audio |
|
//! | [`rtp`] | the RTP header shared by video and audio |
|
||||||
//! | [`fec`] | Reed-Solomon erasure coding over GF(2^8) |
|
//! | [`fec`] | Reed-Solomon erasure coding over GF(2^8) |
|
||||||
|
|||||||
@@ -130,7 +130,8 @@ fn host_parsers_never_allocate_past_their_caps() {
|
|||||||
let mut h = ControlHost::accept(config, Instant::ZERO, &connect()).unwrap();
|
let mut h = ControlHost::accept(config, Instant::ZERO, &connect()).unwrap();
|
||||||
let cipher = ControlCipher::new([3; 16]);
|
let cipher = ControlCipher::new([3; 16]);
|
||||||
for seq in 0..64u32 {
|
for seq in 0..64u32 {
|
||||||
let frame = cipher.seal(seq, Direction::ClientToHost, &[0x06, 0x02, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]).unwrap();
|
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];
|
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(&((seq + 1) as u16).to_be_bytes());
|
||||||
d.extend_from_slice(&(frame.len() as u16).to_be_bytes());
|
d.extend_from_slice(&(frame.len() as u16).to_be_bytes());
|
||||||
|
|||||||
@@ -67,8 +67,12 @@ struct StreamClient {
|
|||||||
|
|
||||||
impl StreamClient {
|
impl StreamClient {
|
||||||
fn new(seed: u64) -> Self {
|
fn new(seed: u64) -> Self {
|
||||||
let config = ControlConfig { enet: enet_client_config(), rikey: KEY, ping_interval: Duration::from_millis(100) };
|
let config =
|
||||||
Self { stream: ControlStream::connect(config, Instant::ZERO, &mut common::SeqRng::new(seed)).unwrap(), events: Vec::new() }
|
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) {
|
fn drain(&mut self) {
|
||||||
@@ -210,8 +214,7 @@ impl Host {
|
|||||||
|
|
||||||
/// Events after the first `Connected`, without it.
|
/// Events after the first `Connected`, without it.
|
||||||
fn take(&mut self) -> Vec<ControlHostEvent> {
|
fn take(&mut self) -> Vec<ControlHostEvent> {
|
||||||
let out: Vec<ControlHostEvent> =
|
let out: Vec<ControlHostEvent> = self.events.drain(..).filter(|e| *e != ControlHostEvent::Connected).collect();
|
||||||
self.events.drain(..).filter(|e| *e != ControlHostEvent::Connected).collect();
|
|
||||||
out
|
out
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -334,7 +337,10 @@ fn input_vectors_from_the_wolf_tables() {
|
|||||||
"06 02 12 00 00 00 00 0E 05 00 00 00 05 B8 02 10 00 00 07 7F 04 37",
|
"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 },
|
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 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",
|
"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 },
|
InputEvent::Key { pressed: true, flags: 0, key_code: 0x80A4, modifiers: 0x04 },
|
||||||
@@ -448,11 +454,17 @@ fn start_ping_idr_and_stats_over_the_wire() {
|
|||||||
#[test]
|
#[test]
|
||||||
fn host_message_layouts() {
|
fn host_message_layouts() {
|
||||||
for (m, hex) in [
|
for (m, hex) in [
|
||||||
(HostMessage::Rumble { controller: 1, low_frequency: 0x7FFF, high_frequency: 0x8000 }, "0b010a00 00000000 0100 ff7f 0080"),
|
(
|
||||||
|
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::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(TERMINATION_GRACEFUL) }, "09010400 80030023"),
|
||||||
(HostMessage::Termination { error_code: Some(1) }, "09010400 00000001"),
|
(HostMessage::Termination { error_code: Some(1) }, "09010400 00000001"),
|
||||||
(HostMessage::MotionEvent { controller: 3, rate_hz: 200, kind: MotionKind::Gyroscope }, "01550500 0300 c800 02"),
|
(
|
||||||
|
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"),
|
(HostMessage::RgbLed { controller: 3, r: 0x10, g: 0x20, b: 0xFF }, "02550500 0300 1020ff"),
|
||||||
] {
|
] {
|
||||||
let bytes = encode_host_message(&m).unwrap();
|
let bytes = encode_host_message(&m).unwrap();
|
||||||
@@ -523,8 +535,8 @@ fn replays_and_forgeries_are_dropped() {
|
|||||||
c.send_frame(t, c.cipher.seal(3, Direction::ClientToHost, &ping).unwrap()); // older
|
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
|
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();
|
let mut bad = c.cipher.seal(6, Direction::ClientToHost, &ping).unwrap();
|
||||||
bad[30] ^= 0x10;
|
bad[26] ^= 0x10;
|
||||||
c.send_frame(t, bad); // bad tag
|
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, 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, 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, vec![0xFF; 40]); // not a frame
|
||||||
@@ -562,7 +574,11 @@ fn malformed_message_inside_a_good_frame_is_skipped() {
|
|||||||
w.run_for(200);
|
w.run_for(200);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
w.host.take(),
|
w.host.take(),
|
||||||
vec![ControlHostEvent::Dropped, ControlHostEvent::Dropped, ControlHostEvent::Message(ClientControlMessage::StartB)]
|
vec![
|
||||||
|
ControlHostEvent::Dropped,
|
||||||
|
ControlHostEvent::Dropped,
|
||||||
|
ControlHostEvent::Message(ClientControlMessage::StartB)
|
||||||
|
]
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -664,7 +680,9 @@ fn lossy_session_delivers_everything_in_order() {
|
|||||||
assert_eq!(w.host.messages(), inputs.iter().cloned().map(ClientControlMessage::Input).collect::<Vec<_>>());
|
assert_eq!(w.host.messages(), inputs.iter().cloned().map(ClientControlMessage::Input).collect::<Vec<_>>());
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
w.client.messages(),
|
w.client.messages(),
|
||||||
(0..120u16).map(|i| HostMessage::Rumble { controller: 0, low_frequency: i, high_frequency: 0 }).collect::<Vec<_>>()
|
(0..120u16)
|
||||||
|
.map(|i| HostMessage::Rumble { controller: 0, low_frequency: i, high_frequency: 0 })
|
||||||
|
.collect::<Vec<_>>()
|
||||||
);
|
);
|
||||||
assert!(!w.host.events.contains(&ControlHostEvent::Dropped));
|
assert!(!w.host.events.contains(&ControlHostEvent::Dropped));
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user