[repo] Workspace: one crate, forbid(unsafe), no-panic lints, RustCrypto picked; Error, Instant, RandomSource, SessionKeys

This commit is contained in:
2026-11-25 11:45:23 +01:00
parent 184f4024c7
commit cb8e7ed4c3
9 changed files with 854 additions and 0 deletions
+11
View File
@@ -0,0 +1,11 @@
//! Randomness comes in from the caller, so every test is deterministic.
/// A source of random bytes supplied by the caller.
///
/// In production this must be a cryptographically secure generator (the OS generator). Tests pass a fixed,
/// seeded source. DomiStream never reads randomness any other way: salts, challenges, secrets, the client key,
/// `rikey`, ENet connect ids and PINs all come from here.
pub trait RandomSource {
/// Fills `dest` completely with random bytes.
fn fill(&mut self, dest: &mut [u8]);
}
+94
View File
@@ -0,0 +1,94 @@
//! The one error type of the crate.
use core::fmt;
/// Result with the crate's [`Error`].
pub type Result<T> = core::result::Result<T, Error>;
/// Everything that can go wrong. Errors never carry key material or decrypted bytes.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Error {
/// Phase A: the API exists, the logic does not yet.
Unimplemented,
/// Input is larger than the parser's `MAX_*` constant. Checked before anything is allocated.
TooLarge {
/// What was being parsed, e.g. `"rtsp message"`.
what: &'static str,
/// The cap.
max: usize,
/// The size that was offered.
actual: usize,
},
/// Input ends before a field it announces.
Truncated {
/// What was being parsed.
what: &'static str,
/// Bytes the field needs.
needed: usize,
/// Bytes that were there.
actual: usize,
},
/// Input does not follow the format (bad syntax, bad length field, wrong constant, bad encoding).
Malformed {
/// What was being parsed and what was wrong, a fixed string.
what: &'static str,
},
/// A field holds a value this client does not accept (unknown type code, out-of-range number).
UnexpectedValue {
/// The field.
what: &'static str,
/// The value seen.
value: u64,
},
/// The host answered with a non-200 `status_code` (HTTP XML) or RTSP status.
HostStatus {
/// The status code.
code: u32,
},
/// Decryption, tag or signature check failed. Deliberately without detail.
Crypto,
/// Pairing refused: wrong PIN, failed host proof (possible man in the middle), or `paired=0`.
PairingRefused,
/// The host does not offer something this client requires (for example control encryption).
Unsupported {
/// What is missing.
what: &'static str,
},
/// The call is not valid in the current state of the state machine.
State {
/// The state the call needs, a fixed string.
expected: &'static str,
},
/// The peer stopped answering within its timeout.
TimedOut,
/// The session is closed; no more calls are accepted.
Closed,
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Unimplemented => f.write_str("not implemented yet"),
Self::TooLarge { what, max, actual } => {
write!(f, "{what}: {actual} bytes is over the {max}-byte limit")
}
Self::Truncated { what, needed, actual } => {
write!(f, "{what}: needs {needed} bytes, got {actual}")
}
Self::Malformed { what } => write!(f, "malformed {what}"),
Self::UnexpectedValue { what, value } => {
write!(f, "{what}: unexpected value {value:#x}")
}
Self::HostStatus { code } => write!(f, "host answered with status {code}"),
Self::Crypto => f.write_str("cryptographic check failed"),
Self::PairingRefused => f.write_str("pairing refused"),
Self::Unsupported { what } => write!(f, "host does not support {what}"),
Self::State { expected } => write!(f, "not allowed now: needs state {expected}"),
Self::TimedOut => f.write_str("timed out"),
Self::Closed => f.write_str("session closed"),
}
}
}
impl std::error::Error for Error {}
+38
View File
@@ -0,0 +1,38 @@
//! The per-session stream key handed to the host in `launch` / `resume` (`docs/PROTOCOL.md` 1.4, 7).
use core::fmt;
use crate::{RandomSource, Result};
/// Length of `rikey` in bytes (AES-128).
pub const RIKEY_LEN: usize = 16;
/// The stream key pair of one session: `rikey` (AES-128 key for control, audio and video) and `rikeyid`
/// (feeds the audio IV).
///
/// A fresh pair is generated for every launch and resume, because the GCM nonce counters restart per session.
/// `Debug` never prints the key.
#[derive(Clone, PartialEq, Eq)]
pub struct SessionKeys {
/// AES-128 key, sent hex-encoded as the `rikey` launch parameter.
pub rikey: [u8; RIKEY_LEN],
/// Key id, sent as the decimal `rikeyid` launch parameter.
pub rikeyid: u32,
}
impl SessionKeys {
/// Draws a fresh key and key id from `rng`.
///
/// # Errors
/// Phase A: always [`crate::Error::Unimplemented`].
pub fn generate(rng: &mut dyn RandomSource) -> Result<Self> {
let _ = rng;
Err(crate::Error::Unimplemented)
}
}
impl fmt::Debug for SessionKeys {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("SessionKeys").field("rikey", &"<redacted>").field("rikeyid", &self.rikeyid).finish()
}
}
+46
View File
@@ -0,0 +1,46 @@
//! DomiStream: a sans-I/O GameStream client (the protocol Sunshine hosts and Moonlight clients speak), for
//! Arena Domi TV and the other Play remotely clients.
//!
//! **Phase A.** This crate holds the public API only. Every function that does protocol work returns
//! [`Error::Unimplemented`] (or `None` for `poll_*` functions); QA writes the mandatory tests against these
//! signatures before the logic lands. Plain data (constants, enum codes, field structs) is final.
//!
//! # Shape
//!
//! Nothing here opens a socket, reads a clock, spawns a thread or touches a file. The caller:
//! - feeds received bytes in (`handle_*` / `push` / `parse_*`, always `&[u8]`),
//! - passes the current time in as [`Instant`] and randomness as a [`RandomSource`],
//! - sends the bytes the state machines hand out (`poll_transmit`, [`http::HttpRequest`]),
//! - reacts to events (`poll_event`) and wakes the machine at its deadline (`poll_timeout` / `handle_timeout`).
//!
//! Every parser has a `MAX_*` constant and refuses larger input before it allocates.
//!
//! # Modules, in session order
//!
//! | Module | Protocol (see `docs/PROTOCOL.md`) |
//! | :-- | :-- |
//! | [`http`] | serverinfo, applist, launch/resume/cancel (section 1) |
//! | [`pairing`] | the PIN handshake and the client certificate (section 1.5) |
//! | [`rtsp`] | OPTIONS, DESCRIBE, SETUP, ANNOUNCE, PLAY and SDP (section 2) |
//! | [`enet`] | the ENet-compatible reliable UDP layer under the control stream (section 3.1) |
//! | [`control`] | AES-GCM framing and control messages (sections 3.2, 3.3) |
//! | [`input`] | input and gamepad packets (section 4) |
//! | [`rtp`] | the RTP header shared by video and audio |
//! | [`fec`] | Reed-Solomon erasure coding over GF(2^8) |
//! | [`video`] | video depacketizer with FEC recovery and decryption (section 5) |
//! | [`audio`] | audio depacketizer with FEC recovery and decryption (section 6) |
//!
//! Opus and video decoding are not here: they belong to the platform layer (ArenaTV).
#![forbid(unsafe_code)]
#![deny(missing_docs)]
pub mod entropy;
pub mod error;
pub mod keys;
pub mod time;
pub use entropy::RandomSource;
pub use error::{Error, Result};
pub use keys::SessionKeys;
pub use time::Instant;
+39
View File
@@ -0,0 +1,39 @@
//! Time comes in from the caller as an [`Instant`]; DomiStream never reads a clock.
use core::time::Duration;
/// A point on the caller's monotonic clock, in microseconds since an epoch the caller chooses.
///
/// Only differences between instants matter. The caller must never let it go backwards within one session.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Instant(u64);
impl Instant {
/// The caller's epoch.
pub const ZERO: Self = Self(0);
/// An instant `micros` microseconds after the caller's epoch.
#[must_use]
pub const fn from_micros(micros: u64) -> Self {
Self(micros)
}
/// Microseconds since the caller's epoch.
#[must_use]
pub const fn as_micros(self) -> u64 {
self.0
}
/// `self + d`, saturating at the end of the clock.
#[must_use]
pub fn saturating_add(self, d: Duration) -> Self {
let micros = u64::try_from(d.as_micros()).unwrap_or(u64::MAX);
Self(self.0.saturating_add(micros))
}
/// `self - earlier`, or zero when `earlier` is later.
#[must_use]
pub fn saturating_duration_since(self, earlier: Self) -> Duration {
Duration::from_micros(self.0.saturating_sub(earlier.0))
}
}