[domistream] Control API: AES-GCM frame, control messages, control stream

This commit is contained in:
2026-11-25 11:47:25 +01:00
parent 213f87b871
commit c01f980292
4 changed files with 441 additions and 0 deletions
+104
View File
@@ -0,0 +1,104 @@
//! The AES-128-GCM frame around every control message (`docs/PROTOCOL.md` 3.2).
//!
//! ```text
//! 0 2 4 8 24
//! | 0x0001 | len | seq (LE) | GCM tag (16) | ciphertext … | len = 4 + 16 + ciphertext
//! nonce = seq (LE, 4) ‖ 0 × 6 ‖ direction ('C' client→host, 'H' host→client) ‖ 'C'
//! ```
use core::fmt;
use crate::Result;
/// Type field of an encrypted frame.
pub const ENCRYPTED_FRAME_TYPE: u16 = 0x0001;
/// GCM tag length.
pub const GCM_TAG_LEN: usize = 16;
/// Bytes before the ciphertext (type, length, sequence, tag).
pub const FRAME_HEADER_LEN: usize = 2 + 2 + 4 + GCM_TAG_LEN;
/// Smallest valid frame: header plus a 4-byte message header inside.
pub const MIN_FRAME_BYTES: usize = FRAME_HEADER_LEN + 4;
/// Maximum frame size accepted or produced, in bytes.
pub const MAX_FRAME_BYTES: usize = 4096;
/// GCM nonce length.
pub const NONCE_LEN: usize = 12;
/// Which way a frame travels; selects byte 10 of the nonce.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Direction {
/// Client to host (`'C'`).
ClientToHost,
/// Host to client (`'H'`).
HostToClient,
}
/// The nonce for sequence number `sequence` in `direction`.
///
/// # Errors
/// Phase A: always [`crate::Error::Unimplemented`].
pub fn nonce(sequence: u32, direction: Direction) -> Result<[u8; NONCE_LEN]> {
let _ = (sequence, direction);
Err(crate::Error::Unimplemented)
}
/// A frame split into its fields, not yet decrypted.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct EncryptedFrame<'a> {
/// Sequence number.
pub sequence: u32,
/// GCM tag.
pub tag: [u8; GCM_TAG_LEN],
/// Ciphertext.
pub ciphertext: &'a [u8],
}
/// Splits a frame (one ENet packet) into its fields. The length field must match the bytes present exactly.
///
/// # Errors
/// [`crate::Error::TooLarge`] over [`MAX_FRAME_BYTES`], [`crate::Error::Truncated`] under [`MIN_FRAME_BYTES`],
/// [`crate::Error::UnexpectedValue`] for a type other than [`ENCRYPTED_FRAME_TYPE`], [`crate::Error::Malformed`]
/// for a length that does not match. Phase A: always [`crate::Error::Unimplemented`].
pub fn parse_encrypted_frame(frame: &[u8]) -> Result<EncryptedFrame<'_>> {
let _ = frame;
Err(crate::Error::Unimplemented)
}
/// AES-128-GCM with the session's `rikey`. `Debug` never prints the key.
#[derive(Clone)]
pub struct ControlCipher {
key: [u8; 16],
}
impl ControlCipher {
/// A cipher for `rikey`.
#[must_use]
pub const fn new(rikey: [u8; 16]) -> Self {
Self { key: rikey }
}
/// Encrypts one message (plaintext = type, length, body) into a whole frame.
///
/// # Errors
/// [`crate::Error::TooLarge`] when the frame would exceed [`MAX_FRAME_BYTES`]. Phase A: always
/// [`crate::Error::Unimplemented`].
pub fn seal(&self, sequence: u32, direction: Direction, plaintext: &[u8]) -> Result<Vec<u8>> {
let _ = (sequence, direction, plaintext, &self.key);
Err(crate::Error::Unimplemented)
}
/// Checks and decrypts one frame; returns its sequence number and the plaintext message.
///
/// # Errors
/// Parser errors as [`parse_encrypted_frame`]; [`crate::Error::Crypto`] when the tag does not verify. Phase A:
/// always [`crate::Error::Unimplemented`].
pub fn open(&self, direction: Direction, frame: &[u8]) -> Result<(u32, Vec<u8>)> {
let _ = (direction, frame);
Err(crate::Error::Unimplemented)
}
}
impl fmt::Debug for ControlCipher {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("ControlCipher(<redacted>)")
}
}
+212
View File
@@ -0,0 +1,212 @@
//! Control messages inside the encrypted frame (`docs/PROTOCOL.md` 3.3): `type u16 LE`, `length u16 LE`, body.
use crate::Result;
use crate::input::InputEvent;
/// Length of the message header (type + length).
pub const MESSAGE_HEADER_LEN: usize = 4;
/// Maximum size of one decrypted message, in bytes.
pub const MAX_MESSAGE_BYTES: usize = super::frame::MAX_FRAME_BYTES - super::frame::FRAME_HEADER_LEN;
/// Length of the HDR metadata block in `HDR_MODE` (15 × u16).
pub const HDR_METADATA_LEN: usize = 30;
/// Known message type codes.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[repr(u16)]
pub enum MessageType {
/// Start, part A (client → host).
StartA = 0x0305,
/// Start, part B (client → host); the host starts video and audio on it.
StartB = 0x0307,
/// Reference frame invalidation request (client → host).
InvalidateRefFrames = 0x0301,
/// IDR frame request (client → host).
IdrFrame = 0x0302,
/// Loss statistics (client → host).
LossStats = 0x0201,
/// Frame statistics (client → host).
FrameStats = 0x0204,
/// Input (client → host).
InputData = 0x0206,
/// Keep-alive (client → host).
PeriodicPing = 0x0200,
/// Termination (host → client).
Termination = 0x0100,
/// Termination with a 32-bit error code (host → client).
TerminationExtended = 0x0109,
/// HDR mode change (host → client).
HdrMode = 0x010e,
/// Rumble (host → client).
RumbleData = 0x010b,
/// Trigger rumble (host → client).
RumbleTriggers = 0x5500,
/// Start or stop motion events (host → client).
MotionEvent = 0x5501,
/// Controller LED colour (host → client).
RgbLed = 0x5502,
/// Adaptive trigger effect (host → client), layout UNKNOWN.
TriggerEffect = 0x5503,
}
impl TryFrom<u16> for MessageType {
type Error = crate::Error;
/// # Errors
/// [`crate::Error::UnexpectedValue`] for an unknown code. Phase A: always [`crate::Error::Unimplemented`].
fn try_from(code: u16) -> Result<Self> {
let _ = code;
Err(crate::Error::Unimplemented)
}
}
/// A message split into type and body, not interpreted.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct RawMessage<'a> {
/// Type code (possibly unknown).
pub message_type: u16,
/// Body, exactly `length` bytes.
pub body: &'a [u8],
}
/// Splits a decrypted message. The length field must equal the bytes after the header.
///
/// # Errors
/// [`crate::Error::TooLarge`] over [`MAX_MESSAGE_BYTES`], [`crate::Error::Truncated`] under
/// [`MESSAGE_HEADER_LEN`], [`crate::Error::Malformed`] for a length that does not match. Phase A: always
/// [`crate::Error::Unimplemented`].
pub fn parse_message(message: &[u8]) -> Result<RawMessage<'_>> {
let _ = message;
Err(crate::Error::Unimplemented)
}
/// Motion sensor kinds of `MOTION_EVENT`.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum MotionKind {
/// Accelerometer (1).
Accelerometer,
/// Gyroscope (2).
Gyroscope,
}
/// HDR mastering metadata as sent in `HDR_MODE` (15 little-endian u16 fields, layout `[M*]`, unconfirmed).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct HdrMetadata {
/// Display primaries x/y for R, G, B.
pub display_primaries: [(u16, u16); 3],
/// White point x/y.
pub white_point: (u16, u16),
/// Maximum display luminance, nits.
pub max_display_luminance: u16,
/// Minimum display luminance, 1/10000 nit.
pub min_display_luminance: u16,
/// Maximum content light level, nits.
pub max_content_light_level: u16,
/// Maximum frame-average light level, nits.
pub max_frame_average_light_level: u16,
/// Maximum full-frame luminance, nits.
pub max_full_frame_luminance: u16,
}
/// A message from the host.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum HostMessage {
/// Rumble a controller.
Rumble {
/// Controller number.
controller: u16,
/// Low-frequency motor.
low_frequency: u16,
/// High-frequency motor.
high_frequency: u16,
},
/// Rumble the triggers.
RumbleTriggers {
/// Controller number.
controller: u16,
/// Left trigger.
left: u16,
/// Right trigger.
right: u16,
},
/// Start (rate > 0) or stop (rate 0) sending motion events.
MotionEvent {
/// Controller number.
controller: u16,
/// Report rate, Hz.
rate_hz: u16,
/// Sensor.
kind: MotionKind,
},
/// Set a controller's LED colour.
RgbLed {
/// Controller number.
controller: u16,
/// Red.
r: u8,
/// Green.
g: u8,
/// Blue.
b: u8,
},
/// HDR turned on or off.
HdrMode {
/// HDR on.
enabled: bool,
/// Mastering metadata, if the body carries it.
metadata: Option<HdrMetadata>,
},
/// The host ended the session.
Termination {
/// Error code (extended form), `None` for the plain form. `0x80030023` = graceful.
error_code: Option<u32>,
},
/// A known or unknown type this client does not interpret; kept for stats and logs.
Other {
/// Type code.
message_type: u16,
/// Body length (the body itself is not kept).
body_len: usize,
},
}
/// Interprets a decrypted message from the host.
///
/// # Errors
/// As [`parse_message`]; [`crate::Error::Malformed`] when a known type's body has the wrong length;
/// [`crate::Error::UnexpectedValue`] for an unknown motion kind. Phase A: always [`crate::Error::Unimplemented`].
pub fn parse_host_message(message: &[u8]) -> Result<HostMessage> {
let _ = message;
Err(crate::Error::Unimplemented)
}
/// A message to the host.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ClientMessage {
/// `START_A` (body UNKNOWN U10).
StartA,
/// `START_B` (body UNKNOWN U10): the host starts video and audio.
StartB,
/// Keep-alive (body UNKNOWN U10).
PeriodicPing,
/// Ask for an IDR frame (body UNKNOWN U10).
RequestIdrFrame,
/// Ask the host to stop referencing frames `first..=last`.
InvalidateRefFrames {
/// First lost frame index.
first: u32,
/// Last lost frame index.
last: u32,
},
/// User input.
Input(InputEvent),
}
/// Serializes a message to the host (type, length, body), ready for [`super::ControlCipher::seal`].
///
/// # Errors
/// [`crate::Error::Unsupported`] for a message whose body is still UNKNOWN; input errors as
/// [`crate::input::encode_input`]. Phase A: always [`crate::Error::Unimplemented`].
pub fn encode_client_message(message: &ClientMessage) -> Result<Vec<u8>> {
let _ = message;
Err(crate::Error::Unimplemented)
}
+124
View File
@@ -0,0 +1,124 @@
//! The control stream (`docs/PROTOCOL.md` section 3): ENet underneath, AES-GCM frames, control messages.
//!
//! [`ControlStream`] ties them together: it connects the ENet peer, seals every [`ClientMessage`] with an
//! increasing sequence number, opens every host frame (dropping replays and frames that fail the tag), and reports
//! [`HostMessage`]s.
use core::time::Duration;
use crate::enet::EnetConfig;
use crate::{Instant, RandomSource, Result};
pub mod frame;
pub mod message;
pub use frame::{ControlCipher, Direction, EncryptedFrame, parse_encrypted_frame};
pub use message::{ClientMessage, HostMessage, MessageType, parse_host_message, parse_message};
/// Settings of one control stream. `Debug` never prints the key.
#[derive(Clone, PartialEq, Eq)]
pub struct ControlConfig {
/// The ENet connection to offer.
pub enet: EnetConfig,
/// The session's `rikey`.
pub rikey: [u8; 16],
/// Send `PERIODIC_PING` this often (UNKNOWN U10).
pub ping_interval: Duration,
}
impl core::fmt::Debug for ControlConfig {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("ControlConfig")
.field("enet", &self.enet)
.field("rikey", &"<redacted>")
.field("ping_interval", &self.ping_interval)
.finish()
}
}
/// What happened on the control stream.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ControlEvent {
/// ENet connected; the client sends `START_A`/`START_B` next.
Connected,
/// A message from the host.
Message(HostMessage),
/// A host frame failed its tag or came out of order and was dropped (counted, never fatal).
Dropped,
/// The host closed the stream.
Disconnected,
/// The host stopped answering.
TimedOut,
}
/// One control stream.
#[derive(Debug)]
pub struct ControlStream {
next_sequence: u32,
}
impl ControlStream {
/// Starts connecting.
///
/// # Errors
/// As [`crate::enet::EnetClient::connect`]. Phase A: always [`crate::Error::Unimplemented`].
pub fn connect(config: ControlConfig, now: Instant, rng: &mut dyn RandomSource) -> Result<Self> {
let _ = (config, now, rng);
Err(crate::Error::Unimplemented)
}
/// Feeds one datagram from the control port.
///
/// # Errors
/// As [`crate::enet::EnetClient::handle_datagram`]. Bad frames inside a good datagram are not errors; they
/// become [`ControlEvent::Dropped`]. Phase A: always [`crate::Error::Unimplemented`].
pub fn handle_datagram(&mut self, now: Instant, datagram: &[u8]) -> Result<()> {
let _ = (now, datagram);
Err(crate::Error::Unimplemented)
}
/// Seals and queues a message (reliable, channel 0 unless measurement says otherwise).
///
/// # Errors
/// As [`message::encode_client_message`] and [`crate::enet::EnetClient::send`]; [`crate::Error::Closed`] once
/// the sequence space is used up (2^32 messages). Phase A: always [`crate::Error::Unimplemented`].
pub fn send(&mut self, now: Instant, message: &ClientMessage) -> Result<()> {
let _ = (now, message, self.next_sequence);
Err(crate::Error::Unimplemented)
}
/// The next datagram to send.
pub fn poll_transmit(&mut self, now: Instant) -> Option<Vec<u8>> {
let _ = now;
None
}
/// The next event.
pub fn poll_event(&mut self) -> Option<ControlEvent> {
None
}
/// When [`Self::handle_timeout`] is due.
#[must_use]
pub fn poll_timeout(&self) -> Option<Instant> {
None
}
/// Advances timers (ENet, periodic ping).
///
/// # Errors
/// Phase A: always [`crate::Error::Unimplemented`].
pub fn handle_timeout(&mut self, now: Instant) -> Result<()> {
let _ = now;
Err(crate::Error::Unimplemented)
}
/// Closes the stream gracefully.
///
/// # Errors
/// [`crate::Error::Closed`] when already closed. Phase A: always [`crate::Error::Unimplemented`].
pub fn close(&mut self, now: Instant) -> Result<()> {
let _ = now;
Err(crate::Error::Unimplemented)
}
}
+1
View File
@@ -35,6 +35,7 @@
#![forbid(unsafe_code)]
#![deny(missing_docs)]
pub mod control;
pub mod enet;
pub mod entropy;
pub mod error;