Compare commits

..

22 Commits

Author SHA1 Message Date
mnovak a65bc54878 [fuzz] rustfmt of the host targets 2026-12-04 12:36:17 +01:00
mnovak e0b7456bd5 [fuzz] host_http_request and host_pairing targets (head cutter agrees with the parser, query round trip, never Paired without the client key, Failed is terminal) 2026-12-04 12:36:01 +01:00
mnovak 632561ef16 [domistream] Host pairing: the host's state machine (pending-PIN slot, proof and signature checks, deadlines from the caller, trusted clients without a PIN) 2026-12-04 12:30:30 +01:00
mnovak 2ba0926cd6 [domistream] Host HTTP: strict request head and query parsing into typed routes, XML answers the client parsers accept (head-end test corrected: a 64 KiB buffer without the empty line is already over the cap) 2026-12-04 12:30:29 +01:00
mnovak befcd7320a [domistream] Host pairing: tests first (client and host paired in memory, wrong PIN on both sides, order, timeouts, trusted clients) 2026-12-04 12:24:43 +01:00
mnovak 43bb6843c8 [domistream] Host HTTP: tests first (request head and query parsing, caps, XML answers read back by the client parsers); API stubs return Unimplemented 2026-12-04 12:24:42 +01:00
mnovak 514565dbd7 [repo] Merge: docs/lumen-l0 (Lumen L0 results, PR #8) 2026-12-04 12:08:00 +01:00
mnovak 284bf7cc17 [repo] Docs: Lumen L0 results (licences, FP16 capture, NVENC API 12.0, timings); S-23 to S-25 2026-12-04 12:07:53 +01:00
mnovak e4fdca794b [repo] Merge: docs/lumen-decisions (Lumen decisions D1-D6 and the iOS phase, PR #7) 2026-12-04 11:55:55 +01:00
mnovak 73deb851ae [repo] Docs: Lumen decisions D1-D6 (Mark, 2026-12-04), iOS as a later client phase, OBS/FFmpeg forbidden for host work 2026-12-04 11:55:48 +01:00
mnovak 813a0ab8c4 [repo] Merge: docs/lumen-host-plan (Lumen host plan, PR #6) 2026-12-04 11:27:42 +01:00
mnovak 3794ed0e7f [repo] Docs: Lumen host plan (architecture, migration from Sunshine, milestones, risks, tests); S-22 Microsoft Learn sources 2026-12-04 11:27:20 +01:00
mnovak 89de3210be [repo] Merge: feature/probe (gs-probe and the live-interop run book, PR #5) 2026-11-30 11:02:20 +01:00
mnovak 3e09dbc09a [probe] U10 candidates from Moonshine: empty control bodies as defaults; run book P3/P4
Moonshine f184d5e (BSD-2, CLEAN_ROOM S-21) reads no body from START_B, PERIODIC_PING or the IDR request, ignores
LOSS_STATS and FRAME_STATS, does not know START_A (skipped inside the encrypted frame, fatal outside it), and stops a
stream after 60 s without a ping. No GPL-provenance value taken.

- Probe defaults: START_A and START_B empty, PERIODIC_PING empty every 500 ms, an empty IDR request on frame loss;
  every body stays overridable by hex or `none`.
- Tests: the candidates' plaintext headers, their sealed frame layout and Moonshine's client-to-host IV, and the
  INVALIDATE_REF_FRAMES field offsets Moonshine reads.
- PROTOCOL.md 3.3 and the U10 row narrowed with the [M] facts.
- LIVE-INTEROP.md: P3 decided (dev-only `sunshine-api` in arena-host behind a never-shipped feature, credentials from
  Custos), P4 done, table V rewritten without guessed bodies, first launch 90 s to outlast a 60 s ping deadline, the
  black-box list pointed at PLAY-REMOTELY's handover, §8 and §15 (§17 is the installer spec).
2026-11-30 11:01:41 +01:00
mnovak 07ccff4241 [probe] gs-probe: desktop GameStream probe client and the live interop run book
tools/gs-probe (own workspace, never published): `probe serverinfo | pair | apps | launch <app-id> | quit | unpair`
against one host address, driving DomiStream's pairing, HTTP, RTSP, ENet, control, video and audio state machines
over real sockets. Structured JSONL log per run (requests, answers, timings, the U each record bears on, parser
errors with their bytes), secrets redacted (rikey, pairing values; PIN never logged; registered key hex scrubbed from
every line). Test-only client key and cert in --out. Video: frames, decode-ready frames, FEC recoveries, losses,
elementary-stream dump, live U14 parity check; audio: packets, losses, decrypting vs plain receivers (U17), packet
dump and offline U16 solver (`solve-audio-fec`). START_A/START_B/PERIODIC_PING/IDR bodies come from the command line
(U10).

docs/LIVE-INTEROP.md: the sitting's run book (preparation, sequence S0-S5 with the U each step settles, variants,
log reading, where each fact lands in PROTOCOL.md and the code, stop-and-report rule, clean-up, Mark's timeline).

Built and unit-tested only (41 tests, clippy -D warnings, fmt); never run against a host.
2026-11-30 10:57:07 +01:00
mnovak a3c8cea7a6 [repo] Merge: docs/load-rule-2026-11-29 (load rule, PR #4) 2026-11-29 01:53:35 +01:00
mnovak beeb72cec8 [repo] Rules: drives at 95 %; the load gates builds and tests only (Mark, 2026-11-29) 2026-11-29 01:53:10 +01:00
mnovak c21e68565b [repo] Merge: feature/client (stream-v0.1.0, the GameStream client, PR #3) 2026-11-26 04:01:43 +01:00
mnovak 8bc8b4f7ab [repo] Merge: docs/rule-90-percent (90 % rule, PR #2) 2026-11-25 12:28:00 +01:00
mnovak ff62498c9e [repo] Rules: no builds or tests above 90 % CPU, RAM or disk (Mark, 2026-11-25) 2026-11-25 12:27:43 +01:00
mnovak f72babc5b5 [repo] Merge: docs/sources (clean-room sources, PR #1) 2026-11-25 12:13:32 +01:00
mnovak ccfcdcc36c [repo] Clean room: stock ENet, tokio-enet and fec-rs allowed with attribution (Mark, 2026-11-25) 2026-11-25 12:13:30 +01:00
34 changed files with 8644 additions and 8 deletions
+8
View File
@@ -10,6 +10,8 @@ Days 1-2 wrap Sunshine; from Day 3 the engine is Lumen (own Rust code). Roadmap:
### Rules that never bend ### Rules that never bend
- Clean room: never open, paste or port GPL code (Sunshine, Moonlight, Apollo, Vibeshine, Rubylight, moonlight-common-c) - Clean room: never open, paste or port GPL code (Sunshine, Moonlight, Apollo, Vibeshine, Rubylight, moonlight-common-c)
into Domi repos. Allowed sources: Wolf protocol docs, Moonshine (BSD-2, attribute), our own measurements. into Domi repos. Allowed sources: Wolf protocol docs, Moonshine (BSD-2, attribute), our own measurements.
- Also allowed for the wire format, with attribution (Mark, 2026-11-25): stock ENet (MIT), tokio-enet (BSD-2),
fec-rs (BSD-2). GPL code stays off limits.
- Sunshine is never patched, linked or bundled: official release, sha256-pinned, separate program, local API only. - Sunshine is never patched, linked or bundled: official release, sha256-pinned, separate program, local API only.
- Sunshine and Lumen listen only on the Via Domi interface and loopback (home LAN only when Via isn't installed). - Sunshine and Lumen listen only on the Via Domi interface and loopback (home LAN only when Via isn't installed).
- Every device must hold a Tessera identity with a grant from the PC's owner. No PIN shown to the user, ever. - Every device must hold a Tessera identity with a grant from the PC's owner. No PIN shown to the user, ever.
@@ -28,3 +30,9 @@ Days 1-2 wrap Sunshine; from Day 3 the engine is Lumen (own Rust code). Roadmap:
- Commits: `[<crate>] <Feature>: <description>`, `[repo]` for repo-wide changes. No AI attribution in commits, PRs or tags. - Commits: `[<crate>] <Feature>: <description>`, `[repo]` for repo-wide changes. No AI attribution in commits, PRs or tags.
- No binaries, captures or test videos in git. - No binaries, captures or test videos in git.
- Cargo builds: the machine-wide `CARGO_HOME` config sends the build dir to `D:\cargo-build`. Never set `CARGO_TARGET_DIR`. - Cargo builds: the machine-wide `CARGO_HOME` config sends the build dir to `D:\cargo-build`. Never set `CARGO_TARGET_DIR`.
- Never start a build or a test run (cargo, npm/pnpm, Gradle, dotnet, Playwright, e2e, emulator, Fabrica runs) while this
PC's CPU or RAM is more than 90 % used, or any drive the work writes to (D:, E:, F:) is more than 95 % used
(Mark, 2026-11-25: "CPU, RAM and disk all 90%"; drives raised to 95 % on 2026-11-29). Check first. If any is over,
don't start; wait and check again later. Don't stop other sessions' work to make room.
- The limits gate builds and tests only. Merging, writing docs or CLAUDE.md and finishing a job never wait for the load
(Mark, 2026-11-29: "No merge you can do even on 100 percent CPU same as writing to claude.md and finishing job").
+276
View File
@@ -0,0 +1,276 @@
//! The host's XML answers (`docs/PROTOCOL.md` 1.1-1.5): every body is `<root status_code="…">` with elements
//! inside. Text and attribute values are escaped; a value the client's parser would refuse (too long, empty where
//! required, control characters) is refused here first, so the host never sends what its clients cannot read.
use crate::Result;
use crate::host::pairing::PairAnswer;
use crate::http::applist::{MAX_APP_TITLE_BYTES, MAX_APPLIST_BYTES, MAX_APPS};
use crate::http::launch::MAX_SESSION_URL_BYTES;
use crate::http::serverinfo::{MAX_SERVERINFO_BYTES, MAX_SERVERINFO_FIELD_BYTES};
use crate::http::xml::MAX_XML_ELEMENTS;
use crate::http::{App, Scheme};
use crate::pairing::identity::MAX_CERT_PEM_BYTES;
use crate::pairing::{MAX_PAIR_RESPONSE_BYTES, MAX_SIGNATURE_BYTES, SECRET_LEN};
use crate::util::{cap, check_rtsp_url, hex_encode, malformed};
/// What the host says about itself in `serverinfo` (`docs/PROTOCOL.md` 1.2).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct HostInfo {
/// `hostname`: the name the client shows. Non-empty.
pub hostname: String,
/// `appversion`, the protocol version string, e.g. `7.1.431.-1`.
pub app_version: String,
/// `GfeVersion`, the compatibility version string.
pub gfe_version: String,
/// `uniqueid`: the host's stable id. Non-empty.
pub unique_id: String,
/// `HttpsPort`.
pub https_port: u16,
/// `ExternalPort`: the HTTP port.
pub http_port: u16,
/// `mac` for Wake-on-LAN, written `aa:bb:cc:dd:ee:ff`; `None` writes an empty element.
pub mac: Option<[u8; 6]>,
/// `LocalIP`: the host's address as this client reached it; empty is allowed.
pub local_ip: String,
/// `MaxLumaPixelsHEVC`; 0 = no HEVC.
pub max_luma_pixels_hevc: u64,
/// `ServerCodecModeSupport` bitmask (bit meanings UNKNOWN U25).
pub codec_mode_support: u32,
/// `currentgame`: id of the running app, 0 = none.
pub current_game: u32,
/// Prefix of `state`: written `<prefix>_SERVER_BUSY` when `current_game != 0`, else `<prefix>_SERVER_FREE`.
/// Letters, digits and `_` only.
pub state_prefix: String,
}
/// Maximum length of an error's `status_message`, in bytes.
pub const MAX_STATUS_MESSAGE_BYTES: usize = 256;
/// Most apps one `applist` answer carries: the client's [`crate::http::applist::MAX_APPS`], lowered so the
/// document stays within the client's [`crate::http::xml::MAX_XML_ELEMENTS`] (the root plus four elements per app).
pub const MAX_WRITTEN_APPS: usize = {
let by_elements = (MAX_XML_ELEMENTS - 1) / 4;
if MAX_APPS < by_elements { MAX_APPS } else { by_elements }
};
/// The declaration every answer starts with.
const DECLARATION: &str = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
/// Checks a value for the client's cap (counted unescaped, as the client counts it) and refuses control
/// characters (XML 1.0 cannot carry most of them, and none belongs in these fields).
fn check_text(what: &'static str, s: &str, max: usize) -> Result<()> {
cap(what, max, s.len())?;
if s.chars().any(char::is_control) {
return Err(malformed(what));
}
Ok(())
}
/// Length of `s` once escaped by [`escape_into`].
fn escaped_len(s: &str) -> usize {
s.chars()
.map(|c| match c {
'&' => 5,
'<' | '>' => 4,
'"' | '\'' => 6,
_ => c.len_utf8(),
})
.sum()
}
/// Appends `s` with the five XML special characters escaped (text and attribute values alike).
fn escape_into(out: &mut String, s: &str) {
for c in s.chars() {
match c {
'&' => out.push_str("&amp;"),
'<' => out.push_str("&lt;"),
'>' => out.push_str("&gt;"),
'"' => out.push_str("&quot;"),
'\'' => out.push_str("&apos;"),
_ => out.push(c),
}
}
}
/// `<name>escaped text</name>`.
fn element(out: &mut String, name: &str, text: &str) {
out.push('<');
out.push_str(name);
out.push('>');
escape_into(out, text);
out.push_str("</");
out.push_str(name);
out.push('>');
}
/// The whole body: declaration, `<root status_code="200">`, `inner`, `</root>`.
fn ok_document(inner: &str) -> Vec<u8> {
format!("{DECLARATION}<root status_code=\"200\">{inner}</root>\n").into_bytes()
}
/// `serverinfo`. `PairStatus` is 1 only when the request came over HTTPS (`scheme`) with a paired client certificate
/// (`client_paired`); over plain HTTP it is always 0 (`docs/PROTOCOL.md` 1.2). `SupportedDisplayMode` is written
/// empty (its content is not documented).
///
/// # Errors
/// [`crate::Error::Malformed`] for an empty `hostname` or `unique_id`, a bad `state_prefix`, or control characters;
/// [`crate::Error::TooLarge`] for a field over [`MAX_SERVERINFO_FIELD_BYTES`].
pub fn server_info_xml(info: &HostInfo, scheme: Scheme, client_paired: bool) -> Result<Vec<u8>> {
const BUSY: &str = "_SERVER_BUSY";
const FREE: &str = "_SERVER_FREE";
for (what, value) in [
("serverinfo hostname", &info.hostname),
("serverinfo appversion", &info.app_version),
("serverinfo GfeVersion", &info.gfe_version),
("serverinfo uniqueid", &info.unique_id),
("serverinfo LocalIP", &info.local_ip),
] {
check_text(what, value, MAX_SERVERINFO_FIELD_BYTES)?;
}
if info.hostname.is_empty() || info.unique_id.is_empty() {
return Err(malformed("serverinfo: empty hostname or uniqueid"));
}
cap("serverinfo state", MAX_SERVERINFO_FIELD_BYTES - BUSY.len(), info.state_prefix.len())?;
if info.state_prefix.is_empty() || !info.state_prefix.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_') {
return Err(malformed("serverinfo state prefix"));
}
let mac = info.mac.map(|m| m.iter().map(|b| format!("{b:02x}")).collect::<Vec<_>>().join(":")).unwrap_or_default();
let paired = scheme == Scheme::Https && client_paired;
let state = format!("{}{}", info.state_prefix, if info.current_game != 0 { BUSY } else { FREE });
let mut s = String::new();
element(&mut s, "hostname", &info.hostname);
element(&mut s, "appversion", &info.app_version);
element(&mut s, "GfeVersion", &info.gfe_version);
element(&mut s, "uniqueid", &info.unique_id);
element(&mut s, "HttpsPort", &info.https_port.to_string());
element(&mut s, "ExternalPort", &info.http_port.to_string());
element(&mut s, "mac", &mac);
element(&mut s, "LocalIP", &info.local_ip);
element(&mut s, "MaxLumaPixelsHEVC", &info.max_luma_pixels_hevc.to_string());
element(&mut s, "ServerCodecModeSupport", &info.codec_mode_support.to_string());
element(&mut s, "SupportedDisplayMode", "");
element(&mut s, "PairStatus", if paired { "1" } else { "0" });
element(&mut s, "currentgame", &info.current_game.to_string());
element(&mut s, "state", &state);
let body = ok_document(&s);
cap("serverinfo", MAX_SERVERINFO_BYTES, body.len())?;
Ok(body)
}
/// `applist`: one `<App>` per app with `AppTitle`, `ID` and `IsHdrSupported`, in the given order.
///
/// # Errors
/// [`crate::Error::TooLarge`] over [`MAX_WRITTEN_APPS`] apps, a title over [`MAX_APP_TITLE_BYTES`] or a body over
/// [`MAX_APPLIST_BYTES`]; [`crate::Error::Malformed`] for a duplicate id or control characters.
pub fn app_list_xml(apps: &[App]) -> Result<Vec<u8>> {
// `<App><AppTitle></AppTitle><ID>4294967295</ID><IsHdrSupported>0</IsHdrSupported></App>` without the title.
const PER_APP: usize = 85;
cap("applist apps", MAX_WRITTEN_APPS, apps.len())?;
let mut ids = std::collections::BTreeSet::new();
let mut size = DECLARATION.len() + 64;
for app in apps {
check_text("applist AppTitle", &app.title, MAX_APP_TITLE_BYTES)?;
if !ids.insert(app.id) {
return Err(malformed("applist: duplicate ID"));
}
size = size.saturating_add(PER_APP + escaped_len(&app.title));
}
cap("applist", MAX_APPLIST_BYTES, size)?;
let mut s = String::with_capacity(size);
for app in apps {
s.push_str("<App>");
element(&mut s, "AppTitle", &app.title);
element(&mut s, "ID", &app.id.to_string());
element(&mut s, "IsHdrSupported", if app.hdr_supported { "1" } else { "0" });
s.push_str("</App>");
}
let body = ok_document(&s);
cap("applist", MAX_APPLIST_BYTES, body.len())?;
Ok(body)
}
/// `gamesession=1` and `sessionUrl0`.
fn session_xml(rtsp_host: &str, rtsp_port: u16) -> Result<Vec<u8>> {
const SCHEME: &str = "rtsp://";
let port = rtsp_port.to_string();
let len = SCHEME.len().saturating_add(rtsp_host.len()).saturating_add(1 + port.len());
cap("sessionUrl0", MAX_SESSION_URL_BYTES, len)?;
let url = format!("{SCHEME}{rtsp_host}:{port}");
check_rtsp_url("sessionUrl0", &url)?;
let mut s = String::new();
element(&mut s, "gamesession", "1");
element(&mut s, "sessionUrl0", &url);
Ok(ok_document(&s))
}
/// `launch`: `gamesession=1` and `sessionUrl0=rtsp://<rtsp_host>:<rtsp_port>` (`docs/PROTOCOL.md` 1.4).
///
/// # Errors
/// [`crate::Error::Malformed`] unless `rtsp_host` is a host name, an IPv4 address or a bracketed IPv6 literal and the
/// port is not 0; [`crate::Error::TooLarge`] for a URL over [`MAX_SESSION_URL_BYTES`].
pub fn launch_xml(rtsp_host: &str, rtsp_port: u16) -> Result<Vec<u8>> {
session_xml(rtsp_host, rtsp_port)
}
/// `resume`: the same body as [`launch_xml`] (the client reads both with one parser).
///
/// # Errors
/// As [`launch_xml`].
pub fn resume_xml(rtsp_host: &str, rtsp_port: u16) -> Result<Vec<u8>> {
session_xml(rtsp_host, rtsp_port)
}
/// A bare `<root status_code="200"/>`: the answer to `cancel` and `unpair`.
#[must_use]
pub fn ok_xml() -> Vec<u8> {
ok_document("")
}
/// One pairing answer: `paired` and the phase's element, hex-encoded (`docs/PROTOCOL.md` 1.5).
///
/// # Errors
/// [`crate::Error::TooLarge`] for a certificate over [`MAX_CERT_PEM_BYTES`] or a binary value over
/// [`MAX_PAIR_VALUE_BYTES`].
pub fn pair_answer_xml(answer: &PairAnswer) -> Result<Vec<u8>> {
let mut s = String::new();
match answer {
PairAnswer::Refused => element(&mut s, "paired", "0"),
PairAnswer::Paired => element(&mut s, "paired", "1"),
PairAnswer::ServerCert { pem } => {
cap("plaincert", MAX_CERT_PEM_BYTES, pem.len())?;
element(&mut s, "paired", "1");
element(&mut s, "plaincert", &hex_encode(pem.as_bytes()));
}
PairAnswer::ChallengeResponse(v) => {
cap("challengeresponse", MAX_PAIR_VALUE_BYTES, v.len())?;
element(&mut s, "paired", "1");
element(&mut s, "challengeresponse", &hex_encode(v));
}
PairAnswer::PairingSecret(v) => {
cap("pairingsecret", MAX_PAIR_VALUE_BYTES, v.len())?;
element(&mut s, "paired", "1");
element(&mut s, "pairingsecret", &hex_encode(v));
}
}
let body = ok_document(&s);
cap("pairing answer", MAX_PAIR_RESPONSE_BYTES, body.len())?;
Ok(body)
}
/// Largest binary value in a pairing answer: a 16-byte secret and an RSA-8192 signature.
pub const MAX_PAIR_VALUE_BYTES: usize = SECRET_LEN + MAX_SIGNATURE_BYTES;
/// The error root: `<root status_code="<code>" status_message="<message>"/>` (`docs/PROTOCOL.md` 1.1).
///
/// # Errors
/// [`crate::Error::Malformed`] for code 200 or a code outside 100..=999, or control characters in `message`;
/// [`crate::Error::TooLarge`] for a message over [`MAX_STATUS_MESSAGE_BYTES`].
pub fn error_xml(status_code: u32, message: &str) -> Result<Vec<u8>> {
if status_code == 200 || !(100..=999).contains(&status_code) {
return Err(malformed("error status_code"));
}
check_text("status_message", message, MAX_STATUS_MESSAGE_BYTES)?;
let mut escaped = String::with_capacity(escaped_len(message));
escape_into(&mut escaped, message);
Ok(format!("{DECLARATION}<root status_code=\"{status_code}\" status_message=\"{escaped}\"/>\n").into_bytes())
}
+486
View File
@@ -0,0 +1,486 @@
//! The host's HTTP side (`docs/PROTOCOL.md` section 1): strict parsing of an incoming `GET` request head and its
//! query into a typed [`Route`], and the XML answers ([`answer`]).
//!
//! Every request is hostile input. Caps are checked before anything is allocated: the head
//! ([`MAX_HEAD_BYTES`]), the target ([`MAX_PATH_BYTES`], [`MAX_QUERY_BYTES`]), the number of parameters
//! ([`MAX_PARAMS`]) and each name and value ([`MAX_PARAM_NAME_BYTES`], [`MAX_PARAM_VALUE_BYTES`]), then each typed
//! field's own limit. A request never carries a body; a `Content-Length` other than 0 or any `Transfer-Encoding` is
//! refused.
//!
//! Callers whose HTTP server already split the head (TLS front end, an HTTP library) pass the request target to
//! [`parse_target`]; callers reading the raw TCP stream cut the head with [`find_head_end`] and pass it to
//! [`parse_request_head`].
use crate::host::pairing::{PairPhase, PairRequest};
use crate::http::check_unique_id;
use crate::keys::RIKEY_LEN;
use crate::pairing::SALT_LEN;
use crate::util::{cap, hex_decode, hex_digit, malformed, parse_dec, parse_u32, percent_encode};
use crate::{Error, Result, SessionKeys};
pub mod answer;
pub use answer::{HostInfo, app_list_xml, error_xml, launch_xml, ok_xml, pair_answer_xml, resume_xml, server_info_xml};
/// Maximum size of a request head (request line, headers and the empty line), in bytes.
pub const MAX_HEAD_BYTES: usize = 64 * 1024;
/// Maximum number of header lines.
pub const MAX_HEADERS: usize = 64;
/// Maximum length of the path (before `?`), in bytes.
pub const MAX_PATH_BYTES: usize = 256;
/// Maximum length of the query (after `?`), in bytes. Room for a phase-1 `clientcert` at its cap.
pub const MAX_QUERY_BYTES: usize = 40 * 1024;
/// Maximum number of query parameters.
pub const MAX_PARAMS: usize = 32;
/// Maximum length of a parameter name, in bytes.
pub const MAX_PARAM_NAME_BYTES: usize = 64;
/// Maximum length of one parameter value as sent (percent-encoded), in bytes: a hex `clientcert` at
/// [`crate::pairing::identity::MAX_CERT_PEM_BYTES`].
pub const MAX_PARAM_VALUE_BYTES: usize = 2 * crate::pairing::identity::MAX_CERT_PEM_BYTES;
/// Maximum length of a hex value other than `clientcert`, in characters (16 bytes of secret plus an RSA-8192
/// signature).
pub const MAX_HEX_VALUE_CHARS: usize = 2 * (crate::pairing::SECRET_LEN + crate::pairing::MAX_SIGNATURE_BYTES);
/// Maximum length of `devicename`, in bytes.
pub const MAX_DEVICE_NAME_BYTES: usize = crate::host::pairing::MAX_PAIR_DEVICE_NAME_BYTES;
/// Largest width or height accepted in `mode`.
pub const MAX_MODE_DIMENSION: u32 = 16_384;
/// Largest frame rate accepted in `mode`.
pub const MAX_MODE_FPS: u32 = 1000;
/// A stream mode, `mode=<width>x<height>x<fps>`.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct DisplayMode {
/// Width in pixels, 1..=[`MAX_MODE_DIMENSION`].
pub width: u32,
/// Height in pixels, 1..=[`MAX_MODE_DIMENSION`].
pub height: u32,
/// Frames per second, 1..=[`MAX_MODE_FPS`].
pub fps: u32,
}
/// `GET /launch` (`docs/PROTOCOL.md` 1.4).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct LaunchRequest {
/// `appid`.
pub app_id: u32,
/// `mode`.
pub mode: DisplayMode,
/// `rikey` and `rikeyid`.
pub keys: SessionKeys,
/// `hdrMode`, if sent.
pub hdr: Option<bool>,
/// `surroundAudioInfo`, if sent: `(channel_mask << 16) | channel_count`.
pub surround_audio_info: Option<u32>,
}
/// `GET /resume` (`docs/PROTOCOL.md` 1.4): fresh keys; the launch parameters only if the client repeats them.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ResumeRequest {
/// `rikey` and `rikeyid`.
pub keys: SessionKeys,
/// `appid`, if sent.
pub app_id: Option<u32>,
/// `mode`, if sent.
pub mode: Option<DisplayMode>,
/// `hdrMode`, if sent.
pub hdr: Option<bool>,
/// `surroundAudioInfo`, if sent.
pub surround_audio_info: Option<u32>,
}
/// What the request asks for.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Route {
/// `/serverinfo` (HTTP or HTTPS).
ServerInfo,
/// `/applist` (HTTPS).
AppList,
/// `/launch` (HTTPS).
Launch(LaunchRequest),
/// `/resume` (HTTPS).
Resume(ResumeRequest),
/// `/cancel` (HTTPS).
Cancel,
/// `/pair` (phases 1-4 over HTTP, phase 5 over HTTPS); feed it to [`crate::host::pairing::HostPairingSession`].
Pair(PairRequest),
/// `/unpair` (HTTPS).
Unpair,
/// `/appasset` (HTTPS): box art of one app.
AppAsset {
/// `appid`.
app_id: u32,
},
/// Any other path (answer 404). The path as sent, never decoded, never used to open anything.
Unknown {
/// The path.
path: String,
},
}
/// One parsed request.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct HostRequest {
/// The route and its typed parameters.
pub route: Route,
/// `uniqueid`, if sent (required for `/pair`).
pub unique_id: Option<String>,
/// Parameters this parser does not know, decoded, in order: kept for logs so black-box clients can be measured
/// (`docs/PROTOCOL.md` UNKNOWN U4). Never used to decide anything.
pub other_params: Vec<(String, String)>,
}
/// The empty line that ends a head.
const HEAD_END: &[u8] = b"\r\n\r\n";
/// Finds the end of a request head in the bytes read so far: `Some(len)` (the head is `buf[..len]`, ending in the
/// empty line) or `None` (read more).
///
/// # Errors
/// [`Error::TooLarge`] when no head end is within the first [`MAX_HEAD_BYTES`] (so a buffer of that size without
/// one is refused: the head could only end past the cap).
pub fn find_head_end(buf: &[u8]) -> Result<Option<usize>> {
let window = buf.get(..MAX_HEAD_BYTES).unwrap_or(buf);
if let Some(at) = window.windows(HEAD_END.len()).position(|w| w == HEAD_END) {
return Ok(Some(at + HEAD_END.len()));
}
if buf.len() >= MAX_HEAD_BYTES {
return Err(Error::TooLarge { what: "http request head", max: MAX_HEAD_BYTES, actual: buf.len() });
}
Ok(None)
}
/// RFC 9110 `tchar`.
fn is_token(b: u8) -> bool {
b.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~".contains(&b)
}
/// Parses one complete request head (`GET <target> HTTP/1.1`, headers, the empty line, nothing after it).
///
/// Only visible ASCII, space and tab are accepted inside lines, every line ends in CRLF, header lines are never
/// folded, and header names are tokens. Headers are otherwise ignored (the host needs none of them), except that a
/// `Content-Length` other than `0` or any `Transfer-Encoding` is refused: a `GET` here never carries a body.
///
/// # Errors
/// [`Error::TooLarge`] over [`MAX_HEAD_BYTES`], [`MAX_HEADERS`] or a target cap, [`Error::Unsupported`] for a
/// method other than `GET`, [`Error::Malformed`] for anything else that is not a strict HTTP/1.x head or a valid
/// target (see [`parse_target`]).
pub fn parse_request_head(head: &[u8]) -> Result<HostRequest> {
cap("http request head", MAX_HEAD_BYTES, head.len())?;
let end = head.windows(HEAD_END.len()).position(|w| w == HEAD_END).ok_or(malformed("http head: no empty line"))?;
if end + HEAD_END.len() != head.len() {
return Err(malformed("http head: bytes after the empty line"));
}
if !head.iter().all(|&b| matches!(b, b' '..=b'~' | b'\t' | b'\r' | b'\n')) {
return Err(malformed("http head: a byte that is not visible ASCII"));
}
let text = core::str::from_utf8(head.get(..end).unwrap_or(&[])).map_err(|_| malformed("http head: not ASCII"))?;
let mut lines = text.split("\r\n");
let request_line = lines.next().unwrap_or("");
if request_line.contains(['\r', '\n']) {
return Err(malformed("http head: bare CR or LF"));
}
let mut parts = request_line.split(' ');
let (Some(method), Some(target), Some(version), None) = (parts.next(), parts.next(), parts.next(), parts.next())
else {
return Err(malformed("http request line"));
};
if method.is_empty() || !method.bytes().all(is_token) || target.is_empty() {
return Err(malformed("http request line"));
}
if version != "HTTP/1.1" && version != "HTTP/1.0" {
return Err(malformed("http version"));
}
if method != "GET" {
return Err(Error::Unsupported { what: "http method other than GET" });
}
let mut count = 0usize;
let mut content_length = false;
for line in lines {
count += 1;
cap("http headers", MAX_HEADERS, count)?;
if line.contains(['\r', '\n']) {
return Err(malformed("http head: bare CR or LF"));
}
if line.starts_with([' ', '\t']) {
return Err(malformed("http head: folded header line"));
}
let (name, value) = line.split_once(':').ok_or(malformed("http header without :"))?;
if name.is_empty() || !name.bytes().all(is_token) {
return Err(malformed("http header name"));
}
let value = value.trim_matches([' ', '\t']);
if name.eq_ignore_ascii_case("content-length") {
if content_length || value != "0" {
return Err(malformed("http head: a body on a GET"));
}
content_length = true;
} else if name.eq_ignore_ascii_case("transfer-encoding") {
return Err(malformed("http head: a body on a GET"));
}
}
parse_target(target)
}
/// The parsed parameters; typed fields are taken out one by one, the rest stays for [`HostRequest::other_params`].
struct Params(Vec<(String, String)>);
impl Params {
fn take(&mut self, name: &str) -> Option<String> {
let at = self.0.iter().position(|(n, _)| n == name)?;
Some(self.0.remove(at).1)
}
fn require(&mut self, name: &str, what: &'static str) -> Result<String> {
self.take(name).ok_or(malformed(what))
}
}
/// `<width>x<height>x<fps>`, each strict decimal and in range.
fn parse_mode(s: &str) -> Result<DisplayMode> {
let mut parts = s.split('x');
let (Some(w), Some(h), Some(f), None) = (parts.next(), parts.next(), parts.next(), parts.next()) else {
return Err(malformed("mode"));
};
let (width, height, fps) = (parse_u32("mode", w)?, parse_u32("mode", h)?, parse_u32("mode", f)?);
let dims = 1..=MAX_MODE_DIMENSION;
if !dims.contains(&width) || !dims.contains(&height) || !(1..=MAX_MODE_FPS).contains(&fps) {
return Err(malformed("mode out of range"));
}
Ok(DisplayMode { width, height, fps })
}
/// `rikeyid`: unsigned decimal, or a negative 32-bit decimal read as its two's complement (tolerated: a client
/// may print the id as a signed integer; the bytes on the wire are the same).
fn parse_rikeyid(s: &str) -> Result<u32> {
match s.strip_prefix('-') {
Some(digits) => {
let v = parse_dec("rikeyid", digits)?;
if v == 0 || v > 1 << 31 {
return Err(malformed("rikeyid"));
}
Ok(0u32.wrapping_sub(u32::try_from(v).map_err(|_| malformed("rikeyid"))?))
}
None => parse_u32("rikeyid", s),
}
}
/// `rikey` (exactly 32 hex digits) and `rikeyid`, both required.
fn parse_keys(p: &mut Params) -> Result<SessionKeys> {
let rikey = p.require("rikey", "no rikey")?;
if rikey.len() != 2 * RIKEY_LEN {
return Err(malformed("rikey"));
}
let bytes = hex_decode("rikey", &rikey)?;
let rikey = crate::util::array::<RIKEY_LEN>("rikey", &bytes, 0)?;
let rikeyid = parse_rikeyid(&p.require("rikeyid", "no rikeyid")?)?;
Ok(SessionKeys { rikey, rikeyid })
}
fn parse_flag(what: &'static str, s: &str) -> Result<bool> {
match s {
"0" => Ok(false),
"1" => Ok(true),
_ => Err(malformed(what)),
}
}
/// `hdrMode` and `surroundAudioInfo`, both optional.
fn parse_stream_options(p: &mut Params) -> Result<(Option<bool>, Option<u32>)> {
let hdr = p.take("hdrMode").map(|v| parse_flag("hdrMode", &v)).transpose()?;
let audio = p.take("surroundAudioInfo").map(|v| parse_u32("surroundAudioInfo", &v)).transpose()?;
Ok((hdr, audio))
}
fn parse_launch(p: &mut Params) -> Result<LaunchRequest> {
let app_id = parse_u32("appid", &p.require("appid", "no appid")?)?;
let mode = parse_mode(&p.require("mode", "no mode")?)?;
let keys = parse_keys(p)?;
let (hdr, surround_audio_info) = parse_stream_options(p)?;
Ok(LaunchRequest { app_id, mode, keys, hdr, surround_audio_info })
}
fn parse_resume(p: &mut Params) -> Result<ResumeRequest> {
let keys = parse_keys(p)?;
let app_id = p.take("appid").map(|v| parse_u32("appid", &v)).transpose()?;
let mode = p.take("mode").map(|v| parse_mode(&v)).transpose()?;
let (hdr, surround_audio_info) = parse_stream_options(p)?;
Ok(ResumeRequest { keys, app_id, mode, hdr, surround_audio_info })
}
/// A non-empty hex value of at most `max` characters.
fn pair_hex(what: &'static str, s: &str, max: usize) -> Result<Vec<u8>> {
cap(what, max, s.len())?;
if s.is_empty() {
return Err(malformed(what));
}
hex_decode(what, s)
}
/// The phase of a `/pair` request (`docs/PROTOCOL.md` 1.5): `phrase=getservercert` (with `salt` and `clientcert`),
/// `phrase=pairchallenge`, or exactly one of `clientchallenge`, `serverchallengeresp`, `clientpairingsecret`.
fn parse_pair(p: &mut Params, unique_id: Option<&str>) -> Result<PairRequest> {
let unique_id = unique_id.ok_or(malformed("pair: no uniqueid"))?.to_owned();
let device_name = match p.take("devicename") {
Some(d) => {
cap("devicename", MAX_DEVICE_NAME_BYTES, d.len())?;
Some(d).filter(|d| !d.is_empty())
}
None => None,
};
let phrase = p.take("phrase");
let salt = p.take("salt");
let cert = p.take("clientcert");
let challenge = p.take("clientchallenge");
let response = p.take("serverchallengeresp");
let secret = p.take("clientpairingsecret");
let phase = match (phrase.as_deref(), challenge, response, secret) {
(Some("getservercert"), None, None, None) => {
let salt = salt.ok_or(malformed("pair: no salt"))?;
if salt.len() != 2 * SALT_LEN {
return Err(malformed("pair: salt"));
}
let salt = crate::util::array::<SALT_LEN>("pair: salt", &hex_decode("pair: salt", &salt)?, 0)?;
let cert = cert.ok_or(malformed("pair: no clientcert"))?;
let client_cert_pem = pair_hex("pair: clientcert", &cert, MAX_PARAM_VALUE_BYTES)?;
return Ok(PairRequest {
unique_id,
device_name,
phase: PairPhase::GetServerCert { salt, client_cert_pem },
});
}
(Some("pairchallenge"), None, None, None) => PairPhase::PairChallenge,
(None, Some(v), None, None) => {
PairPhase::ClientChallenge(pair_hex("clientchallenge", &v, MAX_HEX_VALUE_CHARS)?)
}
(None, None, Some(v), None) => {
PairPhase::ServerChallengeResp(pair_hex("serverchallengeresp", &v, MAX_HEX_VALUE_CHARS)?)
}
(None, None, None, Some(v)) => {
PairPhase::ClientPairingSecret(pair_hex("clientpairingsecret", &v, MAX_HEX_VALUE_CHARS)?)
}
_ => return Err(malformed("pair: not exactly one known phase")),
};
if salt.is_some() || cert.is_some() {
return Err(malformed("pair: salt or clientcert outside getservercert"));
}
Ok(PairRequest { unique_id, device_name, phase })
}
/// Parses a request target (`/path?query`) into a typed request.
///
/// The path is matched exactly (case-sensitive, never decoded); an unknown path is [`Route::Unknown`]. The target
/// must be visible ASCII without a fragment. `uniqueid` is checked wherever it appears (letters, digits, `-`, `_`,
/// at most [`crate::http::MAX_UNIQUE_ID_BYTES`]).
///
/// # Errors
/// [`Error::TooLarge`] over [`MAX_PATH_BYTES`], [`MAX_QUERY_BYTES`] or a parameter cap, [`Error::Malformed`] for a
/// bad character, a bad or repeated parameter, or a missing or bad required parameter of a known route.
pub fn parse_target(target: &str) -> Result<HostRequest> {
let (path, query) = match target.split_once('?') {
Some((path, query)) => (path, query),
None => (target, ""),
};
cap("http path", MAX_PATH_BYTES, path.len())?;
cap("http query", MAX_QUERY_BYTES, query.len())?;
if !path.starts_with('/') {
return Err(malformed("http target: not a path"));
}
if !target.bytes().all(|b| b.is_ascii_graphic() && b != b'#') {
return Err(malformed("http target: a character outside visible ASCII, or a fragment"));
}
let mut p = Params(parse_query(query)?);
let unique_id = p.take("uniqueid");
if let Some(u) = &unique_id {
check_unique_id(u)?;
}
let route = match path {
"/serverinfo" => Route::ServerInfo,
"/applist" => Route::AppList,
"/launch" => Route::Launch(parse_launch(&mut p)?),
"/resume" => Route::Resume(parse_resume(&mut p)?),
"/cancel" => Route::Cancel,
"/pair" => Route::Pair(parse_pair(&mut p, unique_id.as_deref())?),
"/unpair" => Route::Unpair,
"/appasset" => Route::AppAsset { app_id: parse_u32("appid", &p.require("appid", "no appid")?)? },
_ => Route::Unknown { path: path.to_owned() },
};
Ok(HostRequest { route, unique_id, other_params: p.0 })
}
/// One percent-decoded value: `%XX` (either case), `+` as a space, other visible ASCII as itself; UTF-8 without
/// control characters.
fn percent_decode(value: &str) -> Result<String> {
let b = value.as_bytes();
let mut out = Vec::with_capacity(b.len());
let mut i = 0;
while let Some(&c) = b.get(i) {
match c {
b'%' => {
let hi = b.get(i + 1).copied().and_then(hex_digit);
let lo = b.get(i + 2).copied().and_then(hex_digit);
let (Some(hi), Some(lo)) = (hi, lo) else { return Err(malformed("query: bad % escape")) };
out.push((hi << 4) | lo);
i += 3;
}
b'+' => {
out.push(b' ');
i += 1;
}
b'!'..=b'~' => {
out.push(c);
i += 1;
}
_ => return Err(malformed("query: a raw character outside visible ASCII")),
}
}
let s = String::from_utf8(out).map_err(|_| malformed("query: value is not UTF-8"))?;
if s.chars().any(char::is_control) {
return Err(malformed("query: control character in a value"));
}
Ok(s)
}
/// Parses a query string (without `?`) into decoded `(name, value)` pairs, in order. Names are taken as sent
/// (letters, digits, `_`, `-`, `.`); values are percent-decoded (`+` is a space) and must be UTF-8 without control
/// characters. Empty segments (`a=1&&b=2`) are skipped; a repeated name is refused.
///
/// # Errors
/// [`Error::TooLarge`] over [`MAX_QUERY_BYTES`], [`MAX_PARAMS`], [`MAX_PARAM_NAME_BYTES`] or
/// [`MAX_PARAM_VALUE_BYTES`]; [`Error::Malformed`] otherwise.
pub fn parse_query(query: &str) -> Result<Vec<(String, String)>> {
cap("http query", MAX_QUERY_BYTES, query.len())?;
let segments = || query.split('&').filter(|s| !s.is_empty());
let count = segments().count();
cap("http query parameters", MAX_PARAMS, count)?;
let mut out: Vec<(String, String)> = Vec::with_capacity(count);
for segment in segments() {
let (name, value) = segment.split_once('=').unwrap_or((segment, ""));
cap("http parameter name", MAX_PARAM_NAME_BYTES, name.len())?;
if name.is_empty() || !name.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'-' | b'.')) {
return Err(malformed("query: parameter name"));
}
cap("http parameter value", MAX_PARAM_VALUE_BYTES, value.len())?;
if out.iter().any(|(n, _)| n == name) {
return Err(malformed("query: repeated parameter"));
}
let value = percent_decode(value)?;
out.push((name.to_owned(), value));
}
Ok(out)
}
/// Encodes `(name, value)` pairs as a query string (without `?`): values percent-encoded except RFC 3986 unreserved
/// characters, names as given. The inverse of [`parse_query`] for valid names and values.
#[must_use]
pub fn encode_query(params: &[(&str, &str)]) -> String {
let mut out = String::new();
for (i, (name, value)) in params.iter().enumerate() {
if i > 0 {
out.push('&');
}
out.push_str(name);
out.push('=');
out.push_str(&percent_encode(value));
}
out
}
+16
View File
@@ -0,0 +1,16 @@
//! The host side of GameStream, for Lumen (Arena Domi's own streaming host). Sans-I/O like the rest of the crate:
//! lumen-host owns the sockets, TLS, the clock, randomness and storage; this module only turns bytes into typed
//! requests, runs the pairing state machine and writes the XML answers.
//!
//! | Module | What (see `docs/PROTOCOL.md`) |
//! | :-- | :-- |
//! | [`http`] | strict parsing of an incoming `GET` request head and query into a typed [`http::Route`], and the XML answers (section 1) |
//! | [`pairing`] | the host's half of the PIN handshake, with a pending-PIN slot fed by the caller (section 1.5) |
//!
//! The client half of this crate ([`crate::pairing`], [`crate::http`]) is tested against this half in memory.
pub mod http;
pub mod pairing;
pub use http::{HostRequest, Route, parse_request_head, parse_target};
pub use pairing::{HostIdentity, HostPairingFailure, HostPairingSession, HostPairingState, PairAnswer, PairedClient};
+585
View File
@@ -0,0 +1,585 @@
//! The host's half of the PIN pairing handshake (`docs/PROTOCOL.md` 1.5), as a sans-I/O state machine: the
//! mirror of the client's [`crate::pairing::PairingSession`].
//!
//! ```text
//! new ─▶ AwaitGetServerCert ─(getservercert)─▶ AwaitPin ─(supply_pin)─▶ AwaitClientChallenge
//! │ (clientchallenge)
//! AwaitClientPairingSecret ◀─(serverchallengeresp)─ AwaitServerChallengeResp ◀┘
//! │ (clientpairingsecret: signature and proof checked)
//! ▼
//! AwaitPairChallenge ─(pairchallenge over HTTPS, same client certificate)─▶ Paired
//! any step: wrong phase / bad input / bad signature / wrong PIN / deadline passed / cancel ─▶ Failed
//! ```
//!
//! The PIN is not known when the first phase arrives: the machine answers it with [`HostPairingStep::HoldForPin`]
//! and the caller keeps that HTTP request open until the owner types the code from the phone into Arena Domi's
//! "Enter the code from your phone" box; [`HostPairingSession::supply_pin`] then returns the held answer.
//!
//! **Trusted clients (Tessera grants).** The handshake's AES key is `SHA-256(salt ‖ PIN)`, so the wire handshake
//! cannot complete unless both sides know the same PIN. A client the owner already trusts (a Tessera grant) does
//! not run it at all: [`PairedClient::trusted`] records its certificate directly, with no PIN anywhere
//! (`docs/LUMEN-HOST-PLAN.md` 1.9).
//!
//! When a call fails, the state becomes [`HostPairingState::Failed`] and the caller answers the request (and a
//! held phase-1 request, if any) with [`PairAnswer::Refused`]. Failed and Paired are terminal.
use core::fmt;
use core::time::Duration;
use crate::http::{Scheme, check_unique_id};
use crate::pairing::identity::MAX_CERT_DER_BYTES;
use crate::pairing::{CHALLENGE_LEN, ClientIdentity, HASH_LEN, Pin, SALT_LEN, SECRET_LEN, ServerCert, crypto};
use crate::util::{array, cap, ct_eq, malformed};
use crate::{Error, Instant, RandomSource, Result};
/// A failed step: why, and the error to return.
type StepError = (HostPairingFailure, Error);
/// Default time the owner has to type the PIN after the first phase arrives (the client waits as long, see
/// [`crate::pairing::STEP1_TIMEOUT`]).
pub const DEFAULT_PIN_TIMEOUT: Duration = Duration::from_secs(120);
/// Default time the client has for each later phase after the host's previous answer.
pub const DEFAULT_PHASE_TIMEOUT: Duration = Duration::from_secs(30);
/// Maximum length of the device name kept from the first phase, in bytes.
pub const MAX_PAIR_DEVICE_NAME_BYTES: usize = 256;
/// Length of the encrypted client challenge (phase 2), in bytes.
pub const CLIENT_CHALLENGE_LEN: usize = CHALLENGE_LEN;
/// Length of the encrypted client proof (phase 3), in bytes.
pub const SERVER_CHALLENGE_RESP_LEN: usize = HASH_LEN;
/// Length of the host secret (phase 3 answer), in bytes.
pub const HOST_SECRET_LEN: usize = SECRET_LEN;
/// The host's long-lived GameStream identity: a self-signed RSA-2048 / SHA-256 certificate and its key. The same
/// certificate is sent as `plaincert` while pairing and presented by the HTTPS server. `Debug` never prints the key.
#[derive(Clone)]
pub struct HostIdentity {
inner: ClientIdentity,
}
impl HostIdentity {
/// Generates a new key and self-signed certificate (same rules as
/// [`crate::pairing::ClientIdentity::generate`]); `not_before_unix` is passed in, never read from a clock.
///
/// # Errors
/// [`Error::Malformed`] for a bad `common_name` or time, [`Error::Crypto`] if key generation fails.
pub fn generate(rng: &mut dyn RandomSource, common_name: &str, not_before_unix: i64) -> Result<Self> {
ClientIdentity::generate(rng, common_name, not_before_unix).map(|inner| Self { inner })
}
/// Loads a stored identity and checks that the key matches the certificate.
///
/// # Errors
/// As [`crate::pairing::ClientIdentity::from_der`].
pub fn from_der(cert_der: &[u8], key_pkcs8_der: &[u8]) -> Result<Self> {
ClientIdentity::from_der(cert_der, key_pkcs8_der).map(|inner| Self { inner })
}
/// The certificate, DER (what the HTTPS server presents).
#[must_use]
pub fn cert_der(&self) -> &[u8] {
self.inner.cert_der()
}
/// The private key, PKCS#8 DER, for the secret store and the TLS stack.
#[must_use]
pub fn key_pkcs8_der(&self) -> &[u8] {
self.inner.key_pkcs8_der()
}
/// The certificate as PEM text (what `plaincert` carries, hex-encoded).
///
/// # Errors
/// None today.
pub fn cert_pem(&self) -> Result<String> {
self.inner.cert_pem()
}
}
impl fmt::Debug for HostIdentity {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("HostIdentity")
.field("cert_der_len", &self.inner.cert_der().len())
.field("key", &"<redacted>")
.finish()
}
}
/// One pairing phase as the client sent it (`docs/PROTOCOL.md` 1.5), hex already decoded by
/// [`crate::host::http`]. Lengths are checked by the state machine, not here.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum PairPhase {
/// Phase 1 (`phrase=getservercert`): the 16-byte salt and the client certificate as PEM text.
GetServerCert {
/// `salt`.
salt: [u8; SALT_LEN],
/// `clientcert`, hex-decoded: the client certificate PEM.
client_cert_pem: Vec<u8>,
},
/// Phase 2 (`clientchallenge`): `E_K(C)`.
ClientChallenge(Vec<u8>),
/// Phase 3 (`serverchallengeresp`): `E_K(H_c)`.
ServerChallengeResp(Vec<u8>),
/// Phase 4 (`clientpairingsecret`): `secret_c ‖ Sign_client(secret_c)`.
ClientPairingSecret(Vec<u8>),
/// Phase 5 (`phrase=pairchallenge`), over HTTPS with the client certificate.
PairChallenge,
}
impl PairPhase {
/// The phase number, 1..=5 (for logs).
#[must_use]
pub const fn number(&self) -> u8 {
match self {
Self::GetServerCert { .. } => 1,
Self::ClientChallenge(_) => 2,
Self::ServerChallengeResp(_) => 3,
Self::ClientPairingSecret(_) => 4,
Self::PairChallenge => 5,
}
}
}
/// A `/pair` request: who sends it and which phase.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PairRequest {
/// `uniqueid`: the client's id; every phase of one pairing must carry the same one.
pub unique_id: String,
/// `devicename`, if sent (kept from phase 1, shown to the owner).
pub device_name: Option<String>,
/// The phase.
pub phase: PairPhase,
}
/// How a request reached the host.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Transport<'a> {
/// Plain HTTP.
Http,
/// HTTPS; `client_cert_der` is the certificate the client presented in the TLS handshake.
Https {
/// The client's TLS certificate, DER.
client_cert_der: &'a [u8],
},
}
impl Transport<'_> {
/// [`Scheme::Http`] or [`Scheme::Https`].
#[must_use]
pub const fn scheme(&self) -> Scheme {
match self {
Self::Http => Scheme::Http,
Self::Https { .. } => Scheme::Https,
}
}
}
/// What the host answers to one phase (`<root status_code="200"><paired>…</paired>…</root>`); serialize it with
/// [`crate::host::http::pair_answer_xml`].
#[derive(Clone, PartialEq, Eq)]
pub enum PairAnswer {
/// `paired=0`: pairing refused or failed.
Refused,
/// Phase 1: `paired=1`, `plaincert` = the host certificate PEM.
ServerCert {
/// The host certificate PEM text.
pem: String,
},
/// Phase 2: `paired=1`, `challengeresponse` = `E_K(H_s ‖ S_c)`, 48 bytes.
ChallengeResponse(Vec<u8>),
/// Phase 3: `paired=1`, `pairingsecret` = `secret_s ‖ Sign_host(secret_s)`.
PairingSecret(Vec<u8>),
/// Phases 4 and 5: `paired=1` alone.
Paired,
}
impl fmt::Debug for PairAnswer {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Refused => f.write_str("Refused"),
Self::ServerCert { pem } => f.debug_struct("ServerCert").field("pem_len", &pem.len()).finish(),
Self::ChallengeResponse(v) => f.debug_tuple("ChallengeResponse").field(&v.len()).finish(),
Self::PairingSecret(v) => f.debug_tuple("PairingSecret").field(&v.len()).finish(),
Self::Paired => f.write_str("Paired"),
}
}
}
/// A client whose certificate the host accepts on HTTPS from now on. Store it (signed by the host key, per
/// `docs/LUMEN-HOST-PLAN.md` 1.9).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PairedClient {
/// The client certificate, DER: exactly what its TLS handshake must present.
pub cert_der: Vec<u8>,
/// `uniqueid` from the pairing, `None` for a trusted client recorded without a handshake.
pub unique_id: Option<String>,
/// `devicename` from the pairing, if sent.
pub device_name: Option<String>,
}
impl PairedClient {
/// The Tessera grant path: records a client certificate the owner already trusts, with no PIN and no wire
/// handshake. Checks that it is one well-formed X.509 certificate with an RSA key.
///
/// # Errors
/// [`Error::TooLarge`] over [`crate::pairing::identity::MAX_CERT_DER_BYTES`], [`Error::Malformed`] otherwise.
pub fn trusted(cert_der: &[u8]) -> Result<Self> {
ServerCert::from_der(cert_der)?;
Ok(Self { cert_der: cert_der.to_vec(), unique_id: None, device_name: None })
}
/// TLS authorization: whether the certificate a client presents over HTTPS (DER) is exactly this one, compared
/// in constant time.
///
/// # Errors
/// [`Error::TooLarge`] over [`crate::pairing::identity::MAX_CERT_DER_BYTES`].
pub fn matches(&self, presented_der: &[u8]) -> Result<bool> {
cap("presented certificate", MAX_CERT_DER_BYTES, presented_der.len())?;
Ok(ct_eq(&self.cert_der, presented_der))
}
}
/// The client that started a pairing, as phase 1 described it: what the owner's prompt shows.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PendingClient {
/// `uniqueid`.
pub unique_id: String,
/// `devicename`, if sent.
pub device_name: Option<String>,
/// The client certificate, DER.
pub cert_der: Vec<u8>,
}
/// Where the host's handshake is.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum HostPairingState {
/// Nothing received yet; waiting for phase 1 (`getservercert`).
AwaitGetServerCert,
/// Phase 1 received; its answer is held until [`HostPairingSession::supply_pin`].
AwaitPin,
/// Phase 1 answered (`plaincert`); waiting for phase 2 (`clientchallenge`).
AwaitClientChallenge,
/// Phase 2 answered (`challengeresponse`); waiting for phase 3 (`serverchallengeresp`).
AwaitServerChallengeResp,
/// Phase 3 answered (`pairingsecret`); waiting for phase 4 (`clientpairingsecret`).
AwaitClientPairingSecret,
/// Phase 4 checked and answered; waiting for phase 5 (`pairchallenge` over HTTPS).
AwaitPairChallenge,
/// Done; see [`HostPairingSession::paired_client`].
Paired,
/// Stopped; see [`HostPairingFailure`]. No further calls are accepted.
Failed(HostPairingFailure),
}
/// Why the host stopped a pairing.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum HostPairingFailure {
/// The client's proof `H_c` did not match: the PIN typed on the host differs from the client's (or someone is in
/// the middle).
WrongPin,
/// The client's signature over its secret did not verify against the certificate from phase 1.
BadSignature,
/// A phase arrived that is not the one expected now (replayed, reordered or skipped).
WrongOrder,
/// A phase came from another client than phase 1 (other `uniqueid`, or phase 5 without the phase-1 certificate
/// over HTTPS).
WrongClient,
/// A phase's value had the wrong length or the client certificate did not parse.
Malformed,
/// The caller's time passed the deadline (PIN not typed in time, or the client stopped answering).
TimedOut,
/// The caller cancelled (the owner closed the code box).
Cancelled,
}
/// Timeouts of one pairing.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct HostPairingConfig {
/// How long the owner has to type the PIN after phase 1 arrives.
pub pin_timeout: Duration,
/// How long the client has for each phase after the host's previous answer (and for phase 1 after `new`).
pub phase_timeout: Duration,
}
impl Default for HostPairingConfig {
fn default() -> Self {
Self { pin_timeout: DEFAULT_PIN_TIMEOUT, phase_timeout: DEFAULT_PHASE_TIMEOUT }
}
}
/// What to do with the request just handled.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum HostPairingStep {
/// Answer it now with this.
Answer(PairAnswer),
/// Hold it open: the answer comes from [`HostPairingSession::supply_pin`] (or is [`PairAnswer::Refused`] when the
/// session fails or times out first). Show the owner the code box for [`HostPairingSession::pending_client`].
HoldForPin,
/// Pairing finished: answer with [`PairAnswer::Paired`] and store the client.
Paired(PairedClient),
}
/// One pairing attempt by one client.
pub struct HostPairingSession {
state: HostPairingState,
config: HostPairingConfig,
deadline: Instant,
host_cert_der: Vec<u8>,
pending: Option<PendingClient>,
client_cert: Option<ServerCert>,
salt: [u8; SALT_LEN],
key: zeroize::Zeroizing<[u8; 16]>,
server_challenge: [u8; CHALLENGE_LEN],
host_secret: zeroize::Zeroizing<[u8; SECRET_LEN]>,
client_proof: [u8; HASH_LEN],
paired: Option<PairedClient>,
}
impl HostPairingSession {
/// A new pairing, waiting for phase 1 until `now + config.phase_timeout`. `identity` must be passed to every
/// later call (it is borrowed per call, so the session never holds a copy of the private key).
#[must_use]
pub fn new(identity: &HostIdentity, config: HostPairingConfig, now: Instant) -> Self {
Self {
state: HostPairingState::AwaitGetServerCert,
config,
deadline: now.saturating_add(config.phase_timeout),
host_cert_der: identity.cert_der().to_vec(),
pending: None,
client_cert: None,
salt: [0; SALT_LEN],
key: zeroize::Zeroizing::new([0; 16]),
server_challenge: [0; CHALLENGE_LEN],
host_secret: zeroize::Zeroizing::new([0; SECRET_LEN]),
client_proof: [0; HASH_LEN],
paired: None,
}
}
const fn is_over(&self) -> bool {
matches!(self.state, HostPairingState::Paired | HostPairingState::Failed(_))
}
fn fail<T>(&mut self, why: HostPairingFailure, error: Error) -> Result<T> {
self.state = HostPairingState::Failed(why);
Err(error)
}
/// Handles one `/pair` request. Draws randomness in phase 2 (host challenge and host secret, 16 bytes each).
///
/// Phases 1-4 are accepted over either transport; phase 5 only over HTTPS with exactly the certificate of
/// phase 1. Every phase must carry the `uniqueid` of phase 1.
///
/// # Errors
/// [`Error::PairingRefused`] for a wrong phase, client, signature or PIN; [`Error::Malformed`] /
/// [`Error::TooLarge`] for bad values; [`Error::TimedOut`] past the deadline; in each case the state becomes
/// [`HostPairingState::Failed`]. [`Error::State`] after `Paired` or `Failed`; [`Error::Malformed`] for a
/// different identity than at `new` (state unchanged).
pub fn handle(
&mut self,
identity: &HostIdentity,
request: &PairRequest,
transport: Transport<'_>,
now: Instant,
rng: &mut dyn RandomSource,
) -> Result<HostPairingStep> {
if self.is_over() {
return Err(Error::State { expected: "a pairing in progress" });
}
if identity.cert_der() != self.host_cert_der.as_slice() {
return Err(malformed("host pairing: a different identity than at the start"));
}
if now > self.deadline {
return self.fail(HostPairingFailure::TimedOut, Error::TimedOut);
}
match self.step(identity, request, transport, now, rng) {
Ok(step) => Ok(step),
Err((why, e)) => self.fail(why, e),
}
}
/// Every phase after the first must come from the client of phase 1.
fn same_client(&self, request: &PairRequest) -> core::result::Result<(), StepError> {
match &self.pending {
Some(p) if p.unique_id == request.unique_id => Ok(()),
_ => Err((HostPairingFailure::WrongClient, Error::PairingRefused)),
}
}
fn next_phase(&mut self, state: HostPairingState, now: Instant, timeout: Duration) {
self.state = state;
self.deadline = now.saturating_add(timeout);
}
fn step(
&mut self,
identity: &HostIdentity,
request: &PairRequest,
transport: Transport<'_>,
now: Instant,
rng: &mut dyn RandomSource,
) -> core::result::Result<HostPairingStep, StepError> {
let bad = |e: Error| (HostPairingFailure::Malformed, e);
match (self.state, &request.phase) {
(HostPairingState::AwaitGetServerCert, PairPhase::GetServerCert { salt, client_cert_pem }) => {
check_unique_id(&request.unique_id).map_err(bad)?;
if let Some(name) = &request.device_name {
cap("devicename", MAX_PAIR_DEVICE_NAME_BYTES, name.len()).map_err(bad)?;
if name.chars().any(char::is_control) {
return Err(bad(malformed("devicename")));
}
}
let cert = ServerCert::from_pem(client_cert_pem).map_err(bad)?;
self.salt = *salt;
self.pending = Some(PendingClient {
unique_id: request.unique_id.clone(),
device_name: request.device_name.clone(),
cert_der: cert.der().to_vec(),
});
self.client_cert = Some(cert);
self.next_phase(HostPairingState::AwaitPin, now, self.config.pin_timeout);
Ok(HostPairingStep::HoldForPin)
}
(HostPairingState::AwaitClientChallenge, PairPhase::ClientChallenge(encrypted)) => {
self.same_client(request)?;
if encrypted.len() != CLIENT_CHALLENGE_LEN {
return Err(bad(malformed("clientchallenge is not 16 bytes")));
}
let challenge = array::<CHALLENGE_LEN>(
"clientchallenge",
&crypto::ecb_decrypt(&self.key, encrypted).map_err(bad)?,
0,
)
.map_err(bad)?;
rng.fill(&mut self.server_challenge);
rng.fill(&mut *self.host_secret);
let host_sig = identity.inner.cert_signature().map_err(bad)?;
let host_proof = crypto::proof_hash(&challenge, &host_sig, &self.host_secret).map_err(bad)?;
let plain = [&host_proof[..], &self.server_challenge[..]].concat();
let answer = crypto::ecb_encrypt(&self.key, &plain).map_err(bad)?;
self.next_phase(HostPairingState::AwaitServerChallengeResp, now, self.config.phase_timeout);
Ok(HostPairingStep::Answer(PairAnswer::ChallengeResponse(answer)))
}
(HostPairingState::AwaitServerChallengeResp, PairPhase::ServerChallengeResp(encrypted)) => {
self.same_client(request)?;
if encrypted.len() != SERVER_CHALLENGE_RESP_LEN {
return Err(bad(malformed("serverchallengeresp is not 32 bytes")));
}
let proof = crypto::ecb_decrypt(&self.key, encrypted).map_err(bad)?;
self.client_proof = array::<HASH_LEN>("serverchallengeresp", &proof, 0).map_err(bad)?;
let signature = identity.inner.sign(&*self.host_secret).map_err(bad)?;
let answer = [&self.host_secret[..], &signature].concat();
self.next_phase(HostPairingState::AwaitClientPairingSecret, now, self.config.phase_timeout);
Ok(HostPairingStep::Answer(PairAnswer::PairingSecret(answer)))
}
(HostPairingState::AwaitClientPairingSecret, PairPhase::ClientPairingSecret(value)) => {
self.same_client(request)?;
let (secret, signature) = crypto::split_pairing_secret(value).map_err(bad)?;
let cert = self.client_cert.as_ref().ok_or_else(|| bad(malformed("host pairing: no client cert")))?;
cert.verify(&secret, signature)
.map_err(|_| (HostPairingFailure::BadSignature, Error::PairingRefused))?;
let client_sig = cert.signature().map_err(bad)?;
let expected = crypto::proof_hash(&self.server_challenge, &client_sig, &secret).map_err(bad)?;
if !ct_eq(&expected, &self.client_proof) {
return Err((HostPairingFailure::WrongPin, Error::PairingRefused));
}
self.next_phase(HostPairingState::AwaitPairChallenge, now, self.config.phase_timeout);
Ok(HostPairingStep::Answer(PairAnswer::Paired))
}
(HostPairingState::AwaitPairChallenge, PairPhase::PairChallenge) => {
self.same_client(request)?;
let pending = self.pending.as_ref().ok_or((HostPairingFailure::WrongClient, Error::PairingRefused))?;
let Transport::Https { client_cert_der } = transport else {
return Err((HostPairingFailure::WrongClient, Error::PairingRefused));
};
if !ct_eq(client_cert_der, &pending.cert_der) {
return Err((HostPairingFailure::WrongClient, Error::PairingRefused));
}
let client = PairedClient {
cert_der: pending.cert_der.clone(),
unique_id: Some(pending.unique_id.clone()),
device_name: pending.device_name.clone(),
};
self.paired = Some(client.clone());
self.state = HostPairingState::Paired;
Ok(HostPairingStep::Paired(client))
}
_ => Err((HostPairingFailure::WrongOrder, Error::PairingRefused)),
}
}
/// The owner typed the PIN: derives the key `SHA-256(salt ‖ PIN)[0..16]` and returns the held answer to phase 1
/// (the host certificate). Whether the PIN matches the client's shows only in phase 4.
///
/// # Errors
/// [`Error::State`] unless the state is [`HostPairingState::AwaitPin`] (state unchanged); [`Error::Malformed`]
/// for a different identity (state unchanged); [`Error::TimedOut`] past the PIN deadline (state becomes Failed).
pub fn supply_pin(&mut self, identity: &HostIdentity, pin: Pin, now: Instant) -> Result<PairAnswer> {
if self.state != HostPairingState::AwaitPin {
return Err(Error::State { expected: "a phase-1 request held for the PIN" });
}
if identity.cert_der() != self.host_cert_der.as_slice() {
return Err(malformed("host pairing: a different identity than at the start"));
}
if now > self.deadline {
return self.fail(HostPairingFailure::TimedOut, Error::TimedOut);
}
let pem = match identity.cert_pem() {
Ok(pem) => pem,
Err(e) => return self.fail(HostPairingFailure::Malformed, e),
};
*self.key = crypto::derive_key(&self.salt, &pin)?;
self.next_phase(HostPairingState::AwaitClientChallenge, now, self.config.phase_timeout);
Ok(PairAnswer::ServerCert { pem })
}
/// The owner closed the code box (or the caller gives up): the state becomes `Failed(Cancelled)` unless it is
/// already terminal. Answer a held request with [`PairAnswer::Refused`].
pub fn cancel(&mut self) {
if !self.is_over() {
self.state = HostPairingState::Failed(HostPairingFailure::Cancelled);
}
}
/// When the session times out, if it is still in progress. The session is late only after this instant.
#[must_use]
pub const fn poll_timeout(&self) -> Option<Instant> {
if self.is_over() { None } else { Some(self.deadline) }
}
/// Wakes the session at its deadline: returns `true` when this call moved it to `Failed(TimedOut)` (answer a
/// held request with [`PairAnswer::Refused`]).
pub fn handle_timeout(&mut self, now: Instant) -> bool {
if self.is_over() || now <= self.deadline {
return false;
}
self.state = HostPairingState::Failed(HostPairingFailure::TimedOut);
true
}
/// Where the handshake is.
#[must_use]
pub const fn state(&self) -> HostPairingState {
self.state
}
/// The client of phase 1 (for the owner's prompt and the grant check), once phase 1 has arrived.
#[must_use]
pub const fn pending_client(&self) -> Option<&PendingClient> {
self.pending.as_ref()
}
/// The paired client, once [`HostPairingState::Paired`].
#[must_use]
pub const fn paired_client(&self) -> Option<&PairedClient> {
self.paired.as_ref()
}
}
impl fmt::Debug for HostPairingSession {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("HostPairingSession")
.field("state", &self.state)
.field("deadline", &self.deadline)
.finish_non_exhaustive()
}
}
+2
View File
@@ -28,6 +28,7 @@
//! | [`fec`] | Reed-Solomon erasure coding over GF(2^8) | //! | [`fec`] | Reed-Solomon erasure coding over GF(2^8) |
//! | [`video`] | video depacketizer with FEC recovery and decryption (section 5) | //! | [`video`] | video depacketizer with FEC recovery and decryption (section 5) |
//! | [`audio`] | audio depacketizer with FEC recovery and decryption (section 6) | //! | [`audio`] | audio depacketizer with FEC recovery and decryption (section 6) |
//! | [`host`] | the host side, for Lumen: request parsing, XML answers and the host's pairing machine (sections 1, 1.5) |
//! //!
//! Opus and video decoding are not here: they belong to the platform layer (ArenaTV). //! Opus and video decoding are not here: they belong to the platform layer (ArenaTV).
@@ -40,6 +41,7 @@ pub mod enet;
pub mod entropy; pub mod entropy;
pub mod error; pub mod error;
pub mod fec; pub mod fec;
pub mod host;
pub mod http; pub mod http;
pub mod input; pub mod input;
pub mod keys; pub mod keys;
+1 -1
View File
@@ -95,7 +95,7 @@ pub(crate) fn hex_encode(bytes: &[u8]) -> String {
s s
} }
fn hex_digit(c: u8) -> Option<u8> { pub(crate) fn hex_digit(c: u8) -> Option<u8> {
match c { match c {
b'0'..=b'9' => Some(c - b'0'), b'0'..=b'9' => Some(c - b'0'),
b'a'..=b'f' => Some(c - b'a' + 10), b'a'..=b'f' => Some(c - b'a' + 10),
+18
View File
@@ -126,6 +126,20 @@ fn lying_inputs() -> Vec<Case> {
v.push(("pairing secret", vec![0; 17], |b| { v.push(("pairing secret", vec![0; 17], |b| {
common::implemented(&domistream::pairing::crypto::split_pairing_secret(b)) common::implemented(&domistream::pairing::crypto::split_pairing_secret(b))
})); }));
// Host HTTP: a request head claiming a 4 GiB body, and a query of empty segments and many short parameters.
v.push((
"host request head",
b"GET /launch?appid=1 HTTP/1.1\r\nContent-Length: 4294967295\r\n\r\n".to_vec(),
|b| common::implemented(&domistream::host::http::parse_request_head(b)),
));
let mut q = b"/serverinfo?".to_vec();
q.extend_from_slice(&b"&".repeat(4000));
q.extend_from_slice(&b"a=%41&".repeat(32));
v.push(("host target", q, |b| {
common::implemented(&domistream::host::http::parse_target(&String::from_utf8_lossy(b)))
}));
v.push(("host head end", vec![b'a'; 70_000], |b| common::implemented(&domistream::host::http::find_head_end(b))));
v v
} }
@@ -233,6 +247,10 @@ fn parsers_never_allocate_past_their_caps() {
("video", |b| common::implemented(&domistream::video::parse_video_packet(b))), ("video", |b| common::implemented(&domistream::video::parse_video_packet(b))),
("audio", |b| common::implemented(&domistream::audio::parse_audio_packet(b))), ("audio", |b| common::implemented(&domistream::audio::parse_audio_packet(b))),
("video decrypt", |b| common::implemented(&domistream::video::VideoCipher::new([2; 16]).decrypt(b))), ("video decrypt", |b| common::implemented(&domistream::video::VideoCipher::new([2; 16]).decrypt(b))),
("host request head", |b| common::implemented(&domistream::host::http::parse_request_head(b))),
("host target", |b| common::implemented(&domistream::host::http::parse_target(&String::from_utf8_lossy(b)))),
("host query", |b| common::implemented(&domistream::host::http::parse_query(&String::from_utf8_lossy(b)))),
("host head end", |b| common::implemented(&domistream::host::http::find_head_end(b))),
("audio decrypt", |b| { ("audio decrypt", |b| {
common::implemented( common::implemented(
&domistream::audio::AudioCipher::new(&SessionKeys { rikey: [2; 16], rikeyid: 0 }).decrypt(0, b), &domistream::audio::AudioCipher::new(&SessionKeys { rikey: [2; 16], rikeyid: 0 }).decrypt(0, b),
+1
View File
@@ -212,6 +212,7 @@ pub const CLIENT_CERT_PEM: &str = include_str!("../fixtures/test-only-client-cer
pub const ROGUE_CERT_PEM: &str = include_str!("../fixtures/test-only-rogue-cert.pem"); pub const ROGUE_CERT_PEM: &str = include_str!("../fixtures/test-only-rogue-cert.pem");
pub const EC_CERT_PEM: &str = include_str!("../fixtures/test-only-ec-cert.pem"); pub const EC_CERT_PEM: &str = include_str!("../fixtures/test-only-ec-cert.pem");
pub const CLIENT_KEY_PEM: &str = include_str!("../fixtures/test-only-client-key.pem"); pub const CLIENT_KEY_PEM: &str = include_str!("../fixtures/test-only-client-key.pem");
pub const HOST_KEY_PEM: &str = include_str!("../fixtures/test-only-host-key.pem");
/// Base64 (RFC 4648, standard alphabet, padding allowed) to bytes; panics on anything else. /// Base64 (RFC 4648, standard alphabet, padding allowed) to bytes; panics on anything else.
pub fn base64_decode(s: &str) -> Vec<u8> { pub fn base64_decode(s: &str) -> Vec<u8> {
+795
View File
@@ -0,0 +1,795 @@
//! The host's HTTP side (`docs/PROTOCOL.md` 1.1-1.5): hostile request heads and queries, the caps, and the XML
//! answers read back with this crate's own client parsers. Every case asserts a specific result.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::indexing_slicing, missing_docs)]
mod common;
use common::{CLIENT_CERT_PEM, to_hex};
use domistream::host::http::answer::{MAX_STATUS_MESSAGE_BYTES, MAX_WRITTEN_APPS};
use domistream::host::http::{
self as host_http, DisplayMode, HostInfo, HostRequest, LaunchRequest, MAX_DEVICE_NAME_BYTES, MAX_HEAD_BYTES,
MAX_HEADERS, MAX_MODE_DIMENSION, MAX_MODE_FPS, MAX_PARAM_NAME_BYTES, MAX_PARAM_VALUE_BYTES, MAX_PARAMS,
MAX_PATH_BYTES, MAX_QUERY_BYTES, ResumeRequest, Route, encode_query, find_head_end, parse_query,
parse_request_head, parse_target,
};
use domistream::host::pairing::{PairAnswer, PairPhase};
use domistream::http::applist::{MAX_APP_TITLE_BYTES, MAX_APPS};
use domistream::http::serverinfo::MAX_SERVERINFO_FIELD_BYTES;
use domistream::http::xml::MAX_XML_ELEMENTS;
use domistream::http::{self, App, Scheme, xml};
use domistream::pairing::identity::MAX_CERT_PEM_BYTES;
use domistream::{Error, SessionKeys};
use proptest::prelude::*;
const UID: &str = "0123456789ABCDEF";
fn head(target: &str) -> Vec<u8> {
format!("GET {target} HTTP/1.1\r\nHost: lumen.test:47989\r\nUser-Agent: test\r\n\r\n").into_bytes()
}
fn route(target: &str) -> Route {
parse_request_head(&head(target)).unwrap_or_else(|e| panic!("{target}: {e:?}")).route
}
fn keys() -> SessionKeys {
SessionKeys { rikey: *b"\x00\x11\x22\x33\x44\x55\x66\x77\x88\x99\xaa\xbb\xcc\xdd\xee\xff", rikeyid: 1_234_567 }
}
// ================================================================================================ the client's own requests
#[test]
fn every_client_request_parses_on_the_host() {
for scheme in [Scheme::Http, Scheme::Https] {
let r = http::server_info_request(scheme, UID).unwrap();
let req = parse_request_head(&head(&r.path_and_query)).unwrap();
assert_eq!(req, HostRequest { route: Route::ServerInfo, unique_id: Some(UID.into()), other_params: vec![] });
}
for (r, want) in [
(http::app_list_request(UID).unwrap(), Route::AppList),
(http::cancel_request(UID).unwrap(), Route::Cancel),
(http::unpair_request(UID).unwrap(), Route::Unpair),
] {
let req = parse_request_head(&head(&r.path_and_query)).unwrap();
assert_eq!(req.route, want);
assert_eq!(req.unique_id.as_deref(), Some(UID));
}
for (hdr, audio) in [(false, http::launch::AudioLayout::Stereo), (true, http::launch::AudioLayout::Surround71)] {
let params =
http::LaunchParams { app_id: 881_448_767, width: 3840, height: 2160, fps: 120, keys: keys(), hdr, audio };
let r = http::launch::launch_request(&params, UID).unwrap();
let want = LaunchRequest {
app_id: 881_448_767,
mode: DisplayMode { width: 3840, height: 2160, fps: 120 },
keys: keys(),
hdr: Some(hdr),
surround_audio_info: Some(audio.surround_audio_info()),
};
assert_eq!(route(&r.path_and_query), Route::Launch(want));
}
let r = http::launch::resume_request(&keys(), UID).unwrap();
assert_eq!(
route(&r.path_and_query),
Route::Resume(ResumeRequest { keys: keys(), app_id: None, mode: None, hdr: None, surround_audio_info: None })
);
}
#[test]
fn the_client_pairing_requests_parse_on_the_host() {
let v = common::pairing_vectors();
let id =
domistream::pairing::ClientIdentity::from_der(&v.bytes("client_cert_der"), &v.bytes("client_key_pkcs8_der"))
.unwrap();
let mut rng = common::SeqRng::new(3);
let pin = domistream::pairing::Pin::from_digits("4071").unwrap();
let (_, r) = domistream::pairing::PairingSession::start(&id, UID, "Living Room TV", pin, &mut rng).unwrap();
match route(&r.path_and_query) {
Route::Pair(p) => {
assert_eq!(p.unique_id, UID);
assert_eq!(p.device_name.as_deref(), Some("Living Room TV"));
match p.phase {
PairPhase::GetServerCert { client_cert_pem, .. } => {
assert_eq!(client_cert_pem, id.cert_pem().unwrap().into_bytes());
}
other => panic!("{other:?}"),
}
}
other => panic!("{other:?}"),
}
}
#[test]
fn pair_phases_from_the_query() {
let salt = "00112233445566778899aabbccddeeff";
let cert = to_hex(CLIENT_CERT_PEM.as_bytes());
let pair = |q: &str| match route(&format!("/pair?uniqueid={UID}&devicename=tv&updateState=1&{q}")) {
Route::Pair(p) => p.phase,
other => panic!("{other:?}"),
};
assert_eq!(
pair(&format!("phrase=getservercert&salt={salt}&clientcert={cert}")),
PairPhase::GetServerCert {
salt: *b"\x00\x11\x22\x33\x44\x55\x66\x77\x88\x99\xaa\xbb\xcc\xdd\xee\xff",
client_cert_pem: CLIENT_CERT_PEM.as_bytes().to_vec()
}
);
assert_eq!(pair("clientchallenge=0A0b"), PairPhase::ClientChallenge(vec![0x0A, 0x0B]));
assert_eq!(pair("serverchallengeresp=ff"), PairPhase::ServerChallengeResp(vec![0xFF]));
assert_eq!(pair("clientpairingsecret=0001"), PairPhase::ClientPairingSecret(vec![0, 1]));
assert_eq!(pair("phrase=pairchallenge"), PairPhase::PairChallenge);
// updateState is known to the client side but not used by the host: it is kept as an unknown parameter.
let req = parse_target(&format!("/pair?uniqueid={UID}&updateState=1&phrase=pairchallenge")).unwrap();
assert_eq!(req.other_params, vec![("updateState".to_string(), "1".to_string())]);
}
#[test]
fn pair_requests_refused() {
let salt = "00112233445566778899aabbccddeeff";
let cert = to_hex(CLIENT_CERT_PEM.as_bytes());
for (q, why) in [
(format!("phrase=getservercert&salt={salt}&clientcert={cert}"), "no uniqueid"),
(format!("uniqueid={UID}"), "no phase"),
(format!("uniqueid={UID}&phrase=getservercert&clientcert={cert}"), "no salt"),
(format!("uniqueid={UID}&phrase=getservercert&salt={salt}"), "no clientcert"),
(format!("uniqueid={UID}&phrase=getservercert&salt=0011&clientcert={cert}"), "short salt"),
(format!("uniqueid={UID}&phrase=getservercert&salt={salt}00&clientcert={cert}"), "long salt"),
(format!("uniqueid={UID}&phrase=getservercert&salt={salt}&clientcert=abc"), "odd hex"),
(format!("uniqueid={UID}&phrase=getservercert&salt={salt}&clientcert=zz"), "not hex"),
(format!("uniqueid={UID}&phrase=other"), "unknown phrase"),
(format!("uniqueid={UID}&phrase=pairchallenge&clientchallenge=00"), "two phases"),
(format!("uniqueid={UID}&clientchallenge=00&serverchallengeresp=00"), "two phases"),
(format!("uniqueid={UID}&clientchallenge="), "empty hex"),
(format!("uniqueid={UID}&clientchallenge=0x00"), "0x prefix"),
("uniqueid=a%26b&phrase=pairchallenge".to_string(), "bad uniqueid"),
(format!("uniqueid={}&phrase=pairchallenge", "a".repeat(65)), "long uniqueid"),
(format!("uniqueid={UID}&uniqueid={UID}&phrase=pairchallenge"), "repeated uniqueid"),
(format!("uniqueid={UID}&phrase=pairchallenge&phrase=getservercert"), "repeated phrase"),
] {
assert!(
matches!(parse_target(&format!("/pair?{q}")), Err(Error::Malformed { .. })),
"{why}: {:?}",
parse_target(&format!("/pair?{q}"))
);
}
let long_name = "d".repeat(MAX_DEVICE_NAME_BYTES);
assert!(parse_target(&format!("/pair?uniqueid={UID}&devicename={long_name}&phrase=pairchallenge")).is_ok());
assert!(matches!(
parse_target(&format!("/pair?uniqueid={UID}&devicename={long_name}d&phrase=pairchallenge")),
Err(Error::TooLarge { max: MAX_DEVICE_NAME_BYTES, .. })
));
// Hex values other than the certificate have their own cap.
let big = "00".repeat(domistream::host::http::MAX_HEX_VALUE_CHARS / 2);
assert!(parse_target(&format!("/pair?uniqueid={UID}&clientpairingsecret={big}")).is_ok());
assert!(matches!(
parse_target(&format!("/pair?uniqueid={UID}&clientpairingsecret={big}00")),
Err(Error::TooLarge { .. })
));
// The certificate's cap is the PEM cap, in hex.
let at_cap = "41".repeat(MAX_CERT_PEM_BYTES);
assert!(
parse_target(&format!("/pair?uniqueid={UID}&phrase=getservercert&salt={salt}&clientcert={at_cap}")).is_ok()
);
assert!(matches!(
parse_target(&format!("/pair?uniqueid={UID}&phrase=getservercert&salt={salt}&clientcert={at_cap}41")),
Err(Error::TooLarge { .. })
));
}
// ================================================================================================ routes
#[test]
fn routes_and_unknown_parameters() {
let req = parse_request_head(&head(&format!("/serverinfo?uniqueid={UID}&uuid=5d1a-77"))).unwrap();
assert_eq!(req.route, Route::ServerInfo);
assert_eq!(req.other_params, vec![("uuid".to_string(), "5d1a-77".to_string())]);
assert_eq!(parse_target("/serverinfo").unwrap().unique_id, None, "uniqueid is optional outside /pair");
let req = parse_target(&format!("/appasset?uniqueid={UID}&appid=5&AssetType=2&AssetIdx=0")).unwrap();
assert_eq!(req.route, Route::AppAsset { app_id: 5 });
assert_eq!(req.other_params.len(), 2);
assert!(matches!(parse_target("/appasset"), Err(Error::Malformed { .. })), "appid is required");
assert_eq!(route("/foo/../bar?x=1"), Route::Unknown { path: "/foo/../bar".into() });
assert_eq!(route("/"), Route::Unknown { path: "/".into() });
assert_eq!(route("/ServerInfo"), Route::Unknown { path: "/ServerInfo".into() }, "paths are case-sensitive");
assert_eq!(route("/serverinfo/"), Route::Unknown { path: "/serverinfo/".into() });
assert_eq!(route("/%73erverinfo"), Route::Unknown { path: "/%73erverinfo".into() }, "paths are never decoded");
assert_eq!(route("/applist?"), Route::AppList, "an empty query is no query");
}
fn launch_q(extra: &str) -> String {
format!(
"/launch?uniqueid={UID}&appid=7&mode=1920x1080x60&rikey=00112233445566778899AABBCCDDEEFF&rikeyid=1234567{extra}"
)
}
#[test]
fn launch_values() {
let Route::Launch(l) = route(&launch_q("")) else { panic!() };
assert_eq!(l.app_id, 7);
assert_eq!(l.mode, DisplayMode { width: 1920, height: 1080, fps: 60 });
assert_eq!(l.keys, keys());
assert_eq!((l.hdr, l.surround_audio_info), (None, None));
let Route::Launch(l) = route(&launch_q("&hdrMode=1&surroundAudioInfo=196610&localAudioPlayMode=0")) else {
panic!()
};
assert_eq!((l.hdr, l.surround_audio_info), (Some(true), Some(196_610)));
// rikeyid: unsigned decimal; a negative 32-bit value is read as its two's complement (UNKNOWN: some clients
// may print the id signed).
let id = |v: &str| match parse_target(&launch_q("").replace("rikeyid=1234567", &format!("rikeyid={v}"))) {
Ok(HostRequest { route: Route::Launch(l), .. }) => Ok(l.keys.rikeyid),
Ok(other) => panic!("{other:?}"),
Err(e) => Err(e),
};
assert_eq!(id("0"), Ok(0));
assert_eq!(id("4294967295"), Ok(u32::MAX));
assert_eq!(id("-1"), Ok(u32::MAX));
assert_eq!(id("-2147483648"), Ok(0x8000_0000));
for bad in ["4294967296", "-2147483649", "-0", "-", "+1", "1.0", "0x10", "", " 1"] {
assert!(matches!(id(bad), Err(Error::Malformed { .. })), "rikeyid {bad:?}: {:?}", id(bad));
}
let max = format!("{MAX_MODE_DIMENSION}x{MAX_MODE_DIMENSION}x{MAX_MODE_FPS}");
let Route::Launch(l) = route(&launch_q("").replace("1920x1080x60", &max)) else { panic!() };
assert_eq!(l.mode.fps, MAX_MODE_FPS);
}
#[test]
fn launch_refused() {
let base = launch_q("");
for (bad, why) in [
(base.replace("&appid=7", ""), "no appid"),
(base.replace("&mode=1920x1080x60", ""), "no mode"),
(base.replace("&rikey=00112233445566778899AABBCCDDEEFF", ""), "no rikey"),
(base.replace("&rikeyid=1234567", ""), "no rikeyid"),
(base.replace("appid=7", "appid=-7"), "negative appid"),
(base.replace("appid=7", "appid=4294967296"), "appid over u32"),
(base.replace("1920x1080x60", "1920x1080"), "mode without fps"),
(base.replace("1920x1080x60", "1920x1080x60x1"), "mode with four parts"),
(base.replace("1920x1080x60", "0x1080x60"), "zero width"),
(base.replace("1920x1080x60", "1920x0x60"), "zero height"),
(base.replace("1920x1080x60", "1920x1080x0"), "zero fps"),
(base.replace("1920x1080x60", &format!("{}x1080x60", MAX_MODE_DIMENSION + 1)), "too wide"),
(base.replace("1920x1080x60", &format!("1920x1080x{}", MAX_MODE_FPS + 1)), "too fast"),
(base.replace("1920x1080x60", "1920X1080X60"), "upper-case X"),
(base.replace("1920x1080x60", "1920x1080x59.94"), "fractional fps"),
(base.replace("1920x1080x60", "+1920x1080x60"), "sign"),
(base.replace("00112233445566778899AABBCCDDEEFF", "00112233445566778899AABBCCDDEEF"), "short rikey"),
(base.replace("00112233445566778899AABBCCDDEEFF", "00112233445566778899AABBCCDDEEFF00"), "long rikey"),
(base.replace("00112233445566778899AABBCCDDEEFF", "00112233445566778899AABBCCDDEEFG"), "rikey not hex"),
(launch_q("&hdrMode=2"), "hdrMode 2"),
(launch_q("&hdrMode=true"), "hdrMode true"),
(launch_q("&surroundAudioInfo=x"), "surroundAudioInfo not decimal"),
(launch_q("&appid=8"), "repeated appid"),
(launch_q("&rikey=00112233445566778899AABBCCDDEEFF"), "repeated rikey"),
] {
let r = parse_target(&bad);
assert!(matches!(r, Err(Error::Malformed { .. })), "{why}: {r:?}");
}
}
#[test]
fn resume_values() {
let q = format!("/resume?uniqueid={UID}&rikey=00112233445566778899aabbccddeeff&rikeyid=1234567");
let Route::Resume(r) = route(&q) else { panic!() };
assert_eq!(r.keys, keys());
let Route::Resume(r) = route(&format!("{q}&appid=3&mode=1280x720x30&hdrMode=0&surroundAudioInfo=1")) else {
panic!()
};
assert_eq!(r.app_id, Some(3));
assert_eq!(r.mode, Some(DisplayMode { width: 1280, height: 720, fps: 30 }));
assert_eq!((r.hdr, r.surround_audio_info), (Some(false), Some(1)));
assert!(matches!(parse_target(&format!("/resume?uniqueid={UID}&rikeyid=1")), Err(Error::Malformed { .. })));
assert!(matches!(parse_target(&format!("{q}&mode=1x1")), Err(Error::Malformed { .. })));
}
// ================================================================================================ the head
#[test]
fn heads_that_are_fine() {
for h in [
"GET /serverinfo HTTP/1.1\r\n\r\n".to_string(),
"GET /serverinfo HTTP/1.0\r\n\r\n".to_string(),
"GET /serverinfo HTTP/1.1\r\nHost: x\r\nContent-Length: 0\r\n\r\n".to_string(),
"GET /serverinfo HTTP/1.1\r\nX-Odd:\tvalue with spaces \t\r\n\r\n".to_string(),
"GET /serverinfo HTTP/1.1\r\nEmpty:\r\n\r\n".to_string(),
"GET /serverinfo HTTP/1.1\r\ncontent-length: 0\r\n\r\n".to_string(),
] {
assert_eq!(parse_request_head(h.as_bytes()).map(|r| r.route), Ok(Route::ServerInfo), "{h:?}");
}
}
#[test]
fn heads_that_are_refused() {
for (h, why) in [
(&b""[..], "empty"),
(b"GET /serverinfo HTTP/1.1\r\n", "no empty line"),
(b"GET /serverinfo HTTP/1.1\r\nHost: x\r\n", "no empty line after headers"),
(b"GET /serverinfo HTTP/1.1\n\n", "bare LF"),
(b"GET /serverinfo HTTP/1.1\r\nHost: x\n\r\n", "bare LF in a header"),
(b"GET /serverinfo HTTP/1.1\r\n\r\nbody", "bytes after the head"),
(b"GET /serverinfo HTTP/1.1\r\n\r\n\r\n", "two empty lines"),
(b"GET /serverinfo HTTP/1.1\r\n\r\n", "two spaces"),
(b"GET /serverinfo HTTP/1.1\r\n\r\n", "two spaces before the version"),
(b"GET /serverinfo\r\n\r\n", "no version"),
(b"GET /serverinfo HTTP/2\r\n\r\n", "HTTP/2"),
(b"GET /serverinfo http/1.1\r\n\r\n", "lower-case version"),
(b"GET /serverinfo HTTP/1.1 x\r\n\r\n", "four parts"),
(b" GET /serverinfo HTTP/1.1\r\n\r\n", "leading space"),
(b"\r\nGET /serverinfo HTTP/1.1\r\n\r\n", "leading empty line"),
(b"GET http://x/serverinfo HTTP/1.1\r\n\r\n", "absolute form"),
(b"GET * HTTP/1.1\r\n\r\n", "asterisk form"),
(b"GET serverinfo HTTP/1.1\r\n\r\n", "no leading slash"),
(b"GET /serverinfo#x HTTP/1.1\r\n\r\n", "fragment"),
(b"GET /server\x00info HTTP/1.1\r\n\r\n", "NUL"),
(b"GET /server\xc3\xa9 HTTP/1.1\r\n\r\n", "non-ASCII target"),
(b"GET /serverinfo HTTP/1.1\r\nHost: \xff\r\n\r\n", "non-ASCII header"),
(b"GET /serverinfo HTTP/1.1\r\nHost: a\x01b\r\n\r\n", "control in a header"),
(b"GET /serverinfo HTTP/1.1\r\nHost: x\r\n folded\r\n\r\n", "folded header"),
(b"GET /serverinfo HTTP/1.1\r\nHost x\r\n\r\n", "no colon"),
(b"GET /serverinfo HTTP/1.1\r\n: x\r\n\r\n", "empty name"),
(b"GET /serverinfo HTTP/1.1\r\nHost : x\r\n\r\n", "space before the colon"),
(b"GET /serverinfo HTTP/1.1\r\nHo(st: x\r\n\r\n", "not a token"),
(b"GET /serverinfo HTTP/1.1\r\nContent-Length: 5\r\n\r\n", "a body"),
(b"GET /serverinfo HTTP/1.1\r\nContent-Length: 0\r\nContent-Length: 0\r\n\r\n", "two lengths"),
(b"GET /serverinfo HTTP/1.1\r\nContent-Length: +0\r\n\r\n", "signed length"),
(b"GET /serverinfo HTTP/1.1\r\nTransfer-Encoding: chunked\r\n\r\n", "chunked"),
(b"GET /serverinfo HTTP/1.1\r\nHost: x\rY: z\r\n\r\n", "bare CR"),
] {
let r = parse_request_head(h);
assert!(matches!(r, Err(Error::Malformed { .. })), "{why}: {r:?}");
}
for m in ["POST", "HEAD", "PUT", "get", "OPTIONS", "CONNECT"] {
let h = format!("{m} /serverinfo HTTP/1.1\r\n\r\n");
assert!(matches!(parse_request_head(h.as_bytes()), Err(Error::Unsupported { .. })), "{m}");
}
}
#[test]
fn head_caps() {
// A head of exactly the cap, padded with one long header line.
let at = |total: usize| {
let start = "GET /serverinfo HTTP/1.1\r\nX: ";
let end = "\r\n\r\n";
format!("{start}{}{end}", "a".repeat(total - start.len() - end.len())).into_bytes()
};
assert_eq!(parse_request_head(&at(MAX_HEAD_BYTES)).map(|r| r.route), Ok(Route::ServerInfo));
assert_too_large!(parse_request_head(&at(MAX_HEAD_BYTES + 1)), MAX_HEAD_BYTES, MAX_HEAD_BYTES + 1);
assert_too_large!(parse_request_head(&vec![b'G'; 1 << 22]), MAX_HEAD_BYTES, 1 << 22);
let headers = |n: usize| {
let mut s = String::from("GET /serverinfo HTTP/1.1\r\n");
for i in 0..n {
s.push_str(&format!("X-{i}: v\r\n"));
}
s.push_str("\r\n");
s.into_bytes()
};
assert!(parse_request_head(&headers(MAX_HEADERS)).is_ok());
assert!(matches!(parse_request_head(&headers(MAX_HEADERS + 1)), Err(Error::TooLarge { max: MAX_HEADERS, .. })));
let path = |n: usize| format!("/{}", "p".repeat(n - 1));
assert_eq!(route(&path(MAX_PATH_BYTES)), Route::Unknown { path: path(MAX_PATH_BYTES) });
assert!(matches!(parse_target(&path(MAX_PATH_BYTES + 1)), Err(Error::TooLarge { max: MAX_PATH_BYTES, .. })));
}
#[test]
fn find_head_end_cuts_the_stream() {
let h = head("/serverinfo");
for cut in 0..h.len() {
assert_eq!(find_head_end(&h[..cut]), Ok(None), "{cut} bytes");
}
assert_eq!(find_head_end(&h), Ok(Some(h.len())));
let mut two = h.clone();
two.extend_from_slice(&h);
assert_eq!(find_head_end(&two), Ok(Some(h.len())), "pipelined: the first head");
assert_eq!(find_head_end(b"\r\n\r\n"), Ok(Some(4)));
let mut at_cap = vec![b'a'; MAX_HEAD_BYTES - 4];
at_cap.extend_from_slice(b"\r\n\r\n");
assert_eq!(find_head_end(&at_cap), Ok(Some(MAX_HEAD_BYTES)));
assert_eq!(find_head_end(&vec![b'a'; MAX_HEAD_BYTES - 1]), Ok(None), "could still end within the cap");
let mut almost = vec![b'a'; MAX_HEAD_BYTES - 4];
almost.extend_from_slice(b"\r\n\r");
assert_eq!(find_head_end(&almost), Ok(None), "one more LF ends it exactly at the cap");
for len in [MAX_HEAD_BYTES, MAX_HEAD_BYTES + 1, 1 << 22] {
assert!(matches!(find_head_end(&vec![b'a'; len]), Err(Error::TooLarge { max: MAX_HEAD_BYTES, .. })), "{len}");
}
let mut late = vec![b'a'; MAX_HEAD_BYTES - 3];
late.extend_from_slice(b"\r\n\r\n");
assert!(matches!(find_head_end(&late), Err(Error::TooLarge { .. })), "ends one byte past the cap");
}
// ================================================================================================ the query
#[test]
fn query_decoding() {
let q = |s: &str| parse_query(s);
assert_eq!(q(""), Ok(vec![]));
assert_eq!(q("a=1&b=2"), Ok(vec![("a".into(), "1".into()), ("b".into(), "2".into())]));
assert_eq!(q("a=%41%62%2b%2B"), Ok(vec![("a".into(), "Ab++".into())]));
assert_eq!(q("a=x+y"), Ok(vec![("a".into(), "x y".into())]));
assert_eq!(q("a=%C3%A9"), Ok(vec![("a".into(), "é".into())]));
assert_eq!(q("a=%26b%3Dc"), Ok(vec![("a".into(), "&b=c".into())]), "encoded & and = stay in the value");
assert_eq!(q("a"), Ok(vec![("a".into(), String::new())]));
assert_eq!(q("a="), Ok(vec![("a".into(), String::new())]));
assert_eq!(q("a=1&&b=2&"), Ok(vec![("a".into(), "1".into()), ("b".into(), "2".into())]));
assert_eq!(q("a=b=c"), Ok(vec![("a".into(), "b=c".into())]));
assert_eq!(q("x.y-z_1=0"), Ok(vec![("x.y-z_1".into(), "0".into())]));
for (bad, why) in [
("=1", "empty name"),
("a=%", "cut escape"),
("a=%4", "cut escape"),
("a=%zz", "bad escape"),
("a=%00", "NUL"),
("a=%0A", "LF"),
("a=%7F", "DEL"),
("a=%FF", "not UTF-8"),
("a=%C3", "cut UTF-8"),
("a%41=1", "escape in a name"),
("a b=1", "space in a name"),
("a=1&a=2", "repeated name"),
("a=1&a", "repeated name"),
("a=\u{e9}", "raw non-ASCII"),
] {
assert!(matches!(q(bad), Err(Error::Malformed { .. })), "{why}: {:?}", q(bad));
}
}
#[test]
fn query_caps() {
let params = |n: usize| (0..n).map(|i| format!("p{i}=1")).collect::<Vec<_>>().join("&");
assert_eq!(parse_query(&params(MAX_PARAMS)).unwrap().len(), MAX_PARAMS);
assert!(matches!(parse_query(&params(MAX_PARAMS + 1)), Err(Error::TooLarge { max: MAX_PARAMS, .. })));
// Empty segments do not count, but are still bounded by the query cap.
assert_eq!(parse_query(&"&".repeat(10_000)), Ok(vec![]));
let name = |n: usize| "n".repeat(n);
assert!(parse_query(&format!("{}=1", name(MAX_PARAM_NAME_BYTES))).is_ok());
assert!(matches!(
parse_query(&format!("{}=1", name(MAX_PARAM_NAME_BYTES + 1))),
Err(Error::TooLarge { max: MAX_PARAM_NAME_BYTES, .. })
));
let value = |n: usize| format!("v={}", "x".repeat(n));
assert!(parse_query(&value(MAX_PARAM_VALUE_BYTES)).is_ok());
assert!(matches!(
parse_query(&value(MAX_PARAM_VALUE_BYTES + 1)),
Err(Error::TooLarge { max: MAX_PARAM_VALUE_BYTES, .. })
));
// The value cap counts the bytes as sent: three per escape.
assert!(matches!(
parse_query(&format!("v={}", "%41".repeat(MAX_PARAM_VALUE_BYTES / 3 + 1))),
Err(Error::TooLarge { max: MAX_PARAM_VALUE_BYTES, .. })
));
let filler =
|n: usize| format!("a={}&b={}", "x".repeat(MAX_PARAM_VALUE_BYTES), "y".repeat(n - MAX_PARAM_VALUE_BYTES - 5));
assert_eq!(filler(MAX_QUERY_BYTES).len(), MAX_QUERY_BYTES);
assert!(parse_query(&filler(MAX_QUERY_BYTES)).is_ok());
assert_too_large!(parse_query(&filler(MAX_QUERY_BYTES + 1)), MAX_QUERY_BYTES, MAX_QUERY_BYTES + 1);
assert!(matches!(
parse_target(&format!("/serverinfo?{}", filler(MAX_QUERY_BYTES + 1))),
Err(Error::TooLarge { max: MAX_QUERY_BYTES, .. })
));
}
#[test]
fn encode_query_is_strict() {
assert_eq!(encode_query(&[]), "");
assert_eq!(encode_query(&[("a", "1"), ("b", "x y&z=é~")]), "a=1&b=x%20y%26z%3D%C3%A9~");
}
// ================================================================================================ properties
fn name_strategy() -> impl Strategy<Value = String> {
"[a-zA-Z_][a-zA-Z0-9_.-]{0,12}"
}
fn value_strategy() -> impl Strategy<Value = String> {
// Any characters but controls (refused on purpose).
proptest::collection::vec(any::<char>().prop_filter("no controls", |c| !c.is_control()), 0..40)
.prop_map(|v| v.into_iter().collect())
}
proptest! {
#![proptest_config(ProptestConfig { cases: 256, ..ProptestConfig::default() })]
#[test]
fn query_round_trips(pairs in proptest::collection::btree_map(name_strategy(), value_strategy(), 0..MAX_PARAMS)) {
let list: Vec<(&str, &str)> = pairs.iter().map(|(k, v)| (k.as_str(), v.as_str())).collect();
let q = encode_query(&list);
let parsed = parse_query(&q).unwrap();
let want: Vec<(String, String)> = pairs.into_iter().collect();
prop_assert_eq!(parsed, want);
}
#[test]
fn launch_round_trips(app in any::<u32>(), w in 1..=MAX_MODE_DIMENSION, h in 1..=MAX_MODE_DIMENSION,
fps in 1..=MAX_MODE_FPS, rikey in any::<[u8; 16]>(), rikeyid in any::<u32>(),
hdr in proptest::option::of(any::<bool>()), audio in proptest::option::of(any::<u32>())) {
let (app_s, mode_s, key_s, id_s) = (app.to_string(), format!("{w}x{h}x{fps}"), to_hex(&rikey), rikeyid.to_string());
let hdr_s = hdr.map(|b| if b { "1" } else { "0" });
let audio_s = audio.map(|a| a.to_string());
let mut list: Vec<(&str, &str)> = vec![
("uniqueid", UID), ("appid", app_s.as_str()), ("mode", mode_s.as_str()), ("rikey", key_s.as_str()),
("rikeyid", id_s.as_str()),
];
if let Some(h) = hdr_s { list.push(("hdrMode", h)); }
if let Some(a) = &audio_s { list.push(("surroundAudioInfo", a.as_str())); }
let req = parse_target(&format!("/launch?{}", encode_query(&list))).unwrap();
let want = LaunchRequest {
app_id: app,
mode: DisplayMode { width: w, height: h, fps },
keys: SessionKeys { rikey, rikeyid },
hdr,
surround_audio_info: audio,
};
prop_assert_eq!(req.route, Route::Launch(want));
}
#[test]
fn heads_never_panic(data in proptest::collection::vec(any::<u8>(), 0..512)) {
let r = parse_request_head(&data);
prop_assert!(common::implemented(&r));
prop_assert!(common::implemented(&find_head_end(&data)));
let text = String::from_utf8_lossy(&data);
prop_assert!(common::implemented(&parse_target(&text)));
prop_assert!(common::implemented(&parse_query(&text)));
}
#[test]
fn targets_never_panic(target in "/[ -~]{0,200}") {
let r = parse_target(&target);
prop_assert!(common::implemented(&r));
let h = parse_request_head(&head(&target));
prop_assert!(common::implemented(&h));
}
/// A valid head with one byte changed or cut short: never a panic; a cut head is always an error.
#[test]
fn mutated_heads(at in 0usize..200, byte in any::<u8>(), cut in 0usize..200) {
let good = head(&launch_q("&hdrMode=1"));
let mut m = good.clone();
let at = at % m.len();
m[at] = byte;
prop_assert!(common::implemented(&parse_request_head(&m)));
let cut = cut % good.len();
prop_assert!(parse_request_head(&good[..cut]).is_err());
}
}
// ================================================================================================ XML answers
fn host_info() -> HostInfo {
HostInfo {
hostname: "LAB-PC".into(),
app_version: "7.1.431.-1".into(),
gfe_version: "3.23.0.74".into(),
unique_id: "0123456789ABCDEF0123456789ABCDEF".into(),
https_port: 47984,
http_port: 47989,
mac: Some([0x00, 0x11, 0x22, 0xAA, 0xBB, 0xFF]),
local_ip: "192.0.2.10".into(),
max_luma_pixels_hevc: 1_869_449_984,
codec_mode_support: 259,
current_game: 0,
state_prefix: "LUMEN".into(),
}
}
#[test]
fn serverinfo_reads_back() {
let body = host_http::server_info_xml(&host_info(), Scheme::Https, true).unwrap();
let s = http::parse_server_info(&body).unwrap();
assert_eq!(s.hostname, "LAB-PC");
assert_eq!(s.app_version, "7.1.431.-1");
assert_eq!(s.gfe_version.as_deref(), Some("3.23.0.74"));
assert_eq!(s.unique_id, "0123456789ABCDEF0123456789ABCDEF");
assert_eq!(s.https_port, 47984);
assert_eq!(s.http_port, Some(47989));
assert_eq!(s.mac, Some([0x00, 0x11, 0x22, 0xAA, 0xBB, 0xFF]));
assert_eq!(s.local_ip.as_deref(), Some("192.0.2.10"));
assert_eq!(s.max_luma_pixels_hevc, Some(1_869_449_984));
assert_eq!(s.codec_mode_support, Some(259));
assert!(s.paired);
assert_eq!(s.current_game, 0);
assert_eq!(s.state, "LUMEN_SERVER_FREE");
assert_eq!(s.is_busy(), Ok(false));
// Every element of PROTOCOL.md 1.2 is there, SupportedDisplayMode included.
let doc = xml::parse(&body).unwrap();
for name in [
"hostname",
"appversion",
"GfeVersion",
"uniqueid",
"HttpsPort",
"ExternalPort",
"mac",
"LocalIP",
"MaxLumaPixelsHEVC",
"ServerCodecModeSupport",
"SupportedDisplayMode",
"PairStatus",
"currentgame",
"state",
] {
assert!(doc.root.child(name).is_some(), "{name}");
}
}
#[test]
fn serverinfo_pair_status_per_scheme() {
for (scheme, paired, want) in [
(Scheme::Http, false, false),
(Scheme::Http, true, false),
(Scheme::Https, false, false),
(Scheme::Https, true, true),
] {
let s = http::parse_server_info(&host_http::server_info_xml(&host_info(), scheme, paired).unwrap()).unwrap();
assert_eq!(s.paired, want, "{scheme:?} paired={paired}");
}
}
#[test]
fn serverinfo_busy_and_optional_fields() {
let info = HostInfo { current_game: 42, mac: None, local_ip: String::new(), ..host_info() };
let s = http::parse_server_info(&host_http::server_info_xml(&info, Scheme::Http, false).unwrap()).unwrap();
assert_eq!(s.current_game, 42);
assert_eq!(s.state, "LUMEN_SERVER_BUSY");
assert_eq!(s.is_busy(), Ok(true));
assert_eq!((s.mac, s.local_ip), (None, None));
}
#[test]
fn serverinfo_escapes_and_refuses() {
let info = HostInfo { hostname: "Mark's <PC> & \"TV\"".into(), ..host_info() };
let s = http::parse_server_info(&host_http::server_info_xml(&info, Scheme::Http, false).unwrap()).unwrap();
assert_eq!(s.hostname, "Mark's <PC> & \"TV\"");
let long = "h".repeat(MAX_SERVERINFO_FIELD_BYTES);
let info = HostInfo { hostname: long.clone(), ..host_info() };
assert_eq!(
http::parse_server_info(&host_http::server_info_xml(&info, Scheme::Http, false).unwrap()).unwrap().hostname,
long
);
for (info, why) in [
(HostInfo { hostname: String::new(), ..host_info() }, "empty hostname"),
(HostInfo { unique_id: String::new(), ..host_info() }, "empty uniqueid"),
(HostInfo { hostname: "a\u{1}b".into(), ..host_info() }, "control character"),
(HostInfo { hostname: "a\nb".into(), ..host_info() }, "line feed"),
(HostInfo { state_prefix: "LU MEN".into(), ..host_info() }, "state prefix with a space"),
(HostInfo { state_prefix: String::new(), ..host_info() }, "empty state prefix"),
] {
assert!(
matches!(host_http::server_info_xml(&info, Scheme::Http, false), Err(Error::Malformed { .. })),
"{why}"
);
}
let info = HostInfo { hostname: "h".repeat(MAX_SERVERINFO_FIELD_BYTES + 1), ..host_info() };
assert!(matches!(host_http::server_info_xml(&info, Scheme::Http, false), Err(Error::TooLarge { .. })));
// Escaping can push a short name over the client's cap: refused here, not by the client.
let info = HostInfo { hostname: "&".repeat(MAX_SERVERINFO_FIELD_BYTES), ..host_info() };
let r = host_http::server_info_xml(&info, Scheme::Http, false);
match r {
Ok(body) => assert_eq!(http::parse_server_info(&body).unwrap().hostname, info.hostname),
Err(e) => assert!(matches!(e, Error::TooLarge { .. }), "{e:?}"),
}
}
#[test]
fn applist_reads_back() {
let apps = vec![
App { id: 1, title: "Desktop".into(), hdr_supported: false },
App { id: 881_448_767, title: "Tom & Jerry's <Big> \"Day\"".into(), hdr_supported: true },
App { id: u32::MAX, title: "Žluťoučký kůň".into(), hdr_supported: false },
App { id: 0, title: "t".repeat(MAX_APP_TITLE_BYTES), hdr_supported: true },
];
let body = host_http::app_list_xml(&apps).unwrap();
assert_eq!(http::parse_app_list(&body).unwrap(), apps);
assert_eq!(http::parse_app_list(&host_http::app_list_xml(&[]).unwrap()).unwrap(), vec![]);
let dup = vec![apps[0].clone(), App { title: "Other".into(), ..apps[0].clone() }];
assert!(matches!(host_http::app_list_xml(&dup), Err(Error::Malformed { .. })));
let long = vec![App { id: 1, title: "t".repeat(MAX_APP_TITLE_BYTES + 1), hdr_supported: false }];
assert!(matches!(host_http::app_list_xml(&long), Err(Error::TooLarge { .. })));
let ctrl = vec![App { id: 1, title: "a\u{7}".into(), hdr_supported: false }];
assert!(matches!(host_http::app_list_xml(&ctrl), Err(Error::Malformed { .. })));
// The writer's cap is what the client can read: MAX_APPS, and the XML element cap (root + 4 per app).
assert_eq!(MAX_WRITTEN_APPS, MAX_APPS.min((MAX_XML_ELEMENTS - 1) / 4));
let many: Vec<App> =
(0..=MAX_WRITTEN_APPS as u32).map(|i| App { id: i, title: "a".into(), hdr_supported: false }).collect();
assert!(matches!(host_http::app_list_xml(&many), Err(Error::TooLarge { .. })));
let body = host_http::app_list_xml(&many[..MAX_WRITTEN_APPS]).unwrap();
assert_eq!(http::parse_app_list(&body).unwrap().len(), MAX_WRITTEN_APPS);
// Long, heavily escaped titles: refused when the body would pass the client's size cap.
let heavy: Vec<App> = (0..MAX_WRITTEN_APPS as u32)
.map(|i| App { id: i, title: "&".repeat(MAX_APP_TITLE_BYTES), hdr_supported: false })
.collect();
assert!(matches!(host_http::app_list_xml(&heavy), Err(Error::TooLarge { .. })));
}
proptest! {
#![proptest_config(ProptestConfig { cases: 128, ..ProptestConfig::default() })]
#[test]
fn app_titles_round_trip(titles in proptest::collection::vec(value_strategy(), 0..8)) {
let apps: Vec<App> = titles.into_iter().enumerate()
.map(|(i, t)| App { id: i as u32, title: t, hdr_supported: i % 2 == 0 })
.collect();
let body = host_http::app_list_xml(&apps).unwrap();
prop_assert_eq!(http::parse_app_list(&body).unwrap(), apps);
}
}
#[test]
fn launch_and_resume_read_back() {
for (host, port, url) in [
("192.0.2.10", 48010, "rtsp://192.0.2.10:48010"),
("lumen-host.local", 1, "rtsp://lumen-host.local:1"),
("[2001:db8::1]", 65535, "rtsp://[2001:db8::1]:65535"),
] {
for body in [host_http::launch_xml(host, port).unwrap(), host_http::resume_xml(host, port).unwrap()] {
let r = http::parse_launch_response(&body).unwrap();
assert!(r.game_session);
assert_eq!(r.session_url.as_deref(), Some(url));
}
}
for (host, port) in [("", 48010), ("a b", 48010), ("a&b", 48010), ("[]", 48010), ("x", 0), ("a/b", 1), ("[::1", 1)]
{
assert!(matches!(host_http::launch_xml(host, port), Err(Error::Malformed { .. })), "{host:?}:{port}");
assert!(matches!(host_http::resume_xml(host, port), Err(Error::Malformed { .. })), "{host:?}:{port}");
}
let long = "h".repeat(300);
assert!(matches!(host_http::launch_xml(&long, 1), Err(Error::TooLarge { .. })));
}
#[test]
fn ok_and_error_roots() {
assert_eq!(http::parse_status_response(&host_http::ok_xml()), Ok(()));
let body = host_http::error_xml(401, "The client is not authorized & <paired>").unwrap();
let d = xml::parse(&body).unwrap();
assert_eq!(d.status_code, 401);
assert_eq!(d.status_message.as_deref(), Some("The client is not authorized & <paired>"));
assert_eq!(http::parse_status_response(&body), Err(Error::HostStatus { code: 401 }));
assert_eq!(xml::parse(&host_http::error_xml(404, "").unwrap()).unwrap().status_message.as_deref(), Some(""));
for (code, msg, why) in [
(200, "x", "200 is not an error"),
(99, "x", "code below 100"),
(1000, "x", "code over 999"),
(400, "a\nb", "line feed"),
(400, "a\u{0}", "NUL"),
] {
assert!(matches!(host_http::error_xml(code, msg), Err(Error::Malformed { .. })), "{why}");
}
let at = "m".repeat(MAX_STATUS_MESSAGE_BYTES);
assert!(host_http::error_xml(500, &at).is_ok());
assert!(matches!(host_http::error_xml(500, &format!("{at}m")), Err(Error::TooLarge { .. })));
}
#[test]
fn pair_answers_read_back() {
use domistream::pairing::parse_pair_response;
let r = parse_pair_response(&host_http::pair_answer_xml(&PairAnswer::Refused).unwrap()).unwrap();
assert!(!r.paired);
let r = parse_pair_response(&host_http::pair_answer_xml(&PairAnswer::Paired).unwrap()).unwrap();
assert!(r.paired && r.plain_cert.is_none() && r.challenge_response.is_none() && r.pairing_secret.is_none());
let r = parse_pair_response(
&host_http::pair_answer_xml(&PairAnswer::ServerCert { pem: CLIENT_CERT_PEM.into() }).unwrap(),
)
.unwrap();
assert!(r.paired);
assert_eq!(r.plain_cert.as_deref(), Some(CLIENT_CERT_PEM.as_bytes()));
let r =
parse_pair_response(&host_http::pair_answer_xml(&PairAnswer::ChallengeResponse(vec![7; 48])).unwrap()).unwrap();
assert_eq!(r.challenge_response, Some(vec![7; 48]));
let r =
parse_pair_response(&host_http::pair_answer_xml(&PairAnswer::PairingSecret(vec![9; 272])).unwrap()).unwrap();
assert_eq!(r.pairing_secret, Some(vec![9; 272]));
let big = PairAnswer::ServerCert { pem: "A".repeat(MAX_CERT_PEM_BYTES + 1) };
assert!(matches!(host_http::pair_answer_xml(&big), Err(Error::TooLarge { .. })));
}
+661
View File
@@ -0,0 +1,661 @@
//! The host's pairing machine (`docs/PROTOCOL.md` 1.5) driven by this crate's own client, entirely in memory: every
//! client request goes through the host's HTTP parser, every host answer through the host's XML writer and the
//! client's parser. The keys are the test-only fixtures (`tests/fixtures`).
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::indexing_slicing, missing_docs)]
mod common;
use core::time::Duration;
use common::{CLIENT_CERT_PEM, EC_CERT_PEM, HOST_KEY_PEM, SeqRng, Vectors, pem_blocks};
use domistream::host::http::{Route, pair_answer_xml, parse_request_head};
use domistream::host::pairing::{
DEFAULT_PHASE_TIMEOUT, DEFAULT_PIN_TIMEOUT, HostIdentity, HostPairingConfig, HostPairingFailure,
HostPairingSession, HostPairingState, HostPairingStep, PairAnswer, PairPhase, PairRequest, PairedClient, Transport,
};
use domistream::http::{HttpRequest, Scheme};
use domistream::pairing::identity::MAX_CERT_DER_BYTES;
use domistream::pairing::{
ClientIdentity, MAX_SIGNATURE_BYTES, PairedHost, PairingFailure, PairingSession, PairingState, PairingStep, Pin,
};
use domistream::{Error, Instant, RandomSource};
const UID: &str = "0123456789ABCDEF";
const DEVICE: &str = "Pixel Test Phone";
fn v() -> Vectors {
common::pairing_vectors()
}
fn host_id() -> HostIdentity {
let key = pem_blocks(HOST_KEY_PEM, "PRIVATE KEY").pop().expect("host key PEM");
HostIdentity::from_der(&v().bytes("host_cert_der"), &key).expect("HostIdentity::from_der(test-only host)")
}
fn client_id() -> ClientIdentity {
let v = v();
ClientIdentity::from_der(&v.bytes("client_cert_der"), &v.bytes("client_key_pkcs8_der")).expect("client identity")
}
fn rogue_id() -> ClientIdentity {
let v = v();
ClientIdentity::from_der(&v.bytes("rogue_cert_der"), &v.bytes("rogue_key_pkcs8_der")).expect("rogue identity")
}
fn pin(d: &str) -> Pin {
Pin::from_digits(d).unwrap()
}
fn secs(s: u64) -> Instant {
Instant::ZERO.saturating_add(Duration::from_secs(s))
}
/// The client's request as the host's HTTP layer sees it.
fn to_host(req: &HttpRequest) -> PairRequest {
let head = format!("GET {} HTTP/1.1\r\nHost: lumen.test\r\n\r\n", req.path_and_query);
let parsed = parse_request_head(head.as_bytes()).expect("the host parses the client's pair request");
assert_eq!(parsed.unique_id.as_deref(), Some(UID));
match parsed.route {
Route::Pair(p) => p,
other => panic!("expected a /pair route, got {other:?}"),
}
}
/// A random source that counts what it hands out.
struct Counting(SeqRng, usize);
impl RandomSource for Counting {
fn fill(&mut self, dest: &mut [u8]) {
self.1 += dest.len();
self.0.fill(dest);
}
}
/// One client and one host, wired together in memory.
struct Duo {
cid: ClientIdentity,
hid: HostIdentity,
client: PairingSession,
host: HostPairingSession,
next: Option<HttpRequest>,
crng: SeqRng,
hrng: Counting,
host_pin: Pin,
now: Instant,
paired_client: Option<PairedClient>,
}
impl Duo {
fn new(client_pin: &str, host_pin: &str, seed: u64) -> Self {
let cid = client_id();
let hid = host_id();
let mut crng = SeqRng::new(seed);
let (client, req) = PairingSession::start(&cid, UID, DEVICE, pin(client_pin), &mut crng).unwrap();
let host = HostPairingSession::new(&hid, HostPairingConfig::default(), Instant::ZERO);
Self {
cid,
hid,
client,
host,
next: Some(req),
crng,
hrng: Counting(SeqRng::new(seed ^ 0xA5A5), 0),
host_pin: pin(host_pin),
now: Instant::ZERO,
paired_client: None,
}
}
/// The host handles `req` (supplying the PIN when it holds the request); its answer, or `Refused` on failure.
fn host_answers(&mut self, req: &PairRequest, scheme: Scheme) -> PairAnswer {
self.now = self.now.saturating_add(Duration::from_millis(250));
let transport = match scheme {
Scheme::Http => Transport::Http,
Scheme::Https => Transport::Https { client_cert_der: self.cid.cert_der() },
};
match self.host.handle(&self.hid, req, transport, self.now, &mut self.hrng) {
Ok(HostPairingStep::Answer(a)) => a,
Ok(HostPairingStep::HoldForPin) => {
assert_eq!(self.host.state(), HostPairingState::AwaitPin);
self.now = self.now.saturating_add(Duration::from_secs(5));
self.host.supply_pin(&self.hid, self.host_pin, self.now).unwrap_or(PairAnswer::Refused)
}
Ok(HostPairingStep::Paired(c)) => {
self.paired_client = Some(c);
PairAnswer::Paired
}
Err(_) => PairAnswer::Refused,
}
}
/// One round trip of the client's next request. `Ok(Some)` when the client is paired, `Err` when it failed.
fn round(&mut self) -> Result<Option<PairedHost>, Error> {
let req = self.next.take().expect("a request to send");
let answer = self.host_answers(&to_host(&req), req.scheme);
let body = pair_answer_xml(&answer).expect("pair_answer_xml");
match self.client.handle_response(&self.cid, 200, &body, &mut self.crng)? {
PairingStep::Send(r) => {
self.next = Some(r);
Ok(None)
}
PairingStep::Paired(h) => Ok(Some(h)),
}
}
/// Runs until the client is paired or fails.
fn run(&mut self) -> Result<PairedHost, Error> {
for _ in 0..5 {
if let Some(h) = self.round()? {
return Ok(h);
}
}
panic!("pairing did not finish in five round trips")
}
/// The host after `rounds` full round trips (0..=4).
fn after(rounds: usize) -> Self {
let mut d = Self::new("4071", "4071", 7);
for _ in 0..rounds {
assert!(d.round().unwrap().is_none());
}
d
}
fn handle(&mut self, phase: PairPhase, transport_scheme: Scheme) -> Result<HostPairingStep, Error> {
let req = PairRequest { unique_id: UID.into(), device_name: None, phase };
self.now = self.now.saturating_add(Duration::from_millis(250));
let now = self.now;
let cert = self.cid.cert_der().to_vec();
let transport = match transport_scheme {
Scheme::Http => Transport::Http,
Scheme::Https => Transport::Https { client_cert_der: &cert },
};
self.host.handle(&self.hid, &req, transport, now, &mut self.hrng)
}
}
// ================================================================================================ both sides agree
#[test]
fn client_and_host_pair_in_memory() {
let mut d = Duo::new("4071", "4071", 1);
let paired_host = d.run().expect("the client pairs with the host");
assert_eq!(d.client.state(), PairingState::Paired);
assert_eq!(d.host.state(), HostPairingState::Paired);
// The client pins exactly the host's certificate; the host authorizes exactly the client's.
assert_eq!(paired_host.server_cert.der(), d.hid.cert_der());
assert_eq!(paired_host.server_cert.matches(d.hid.cert_der()), Ok(true));
let pc = d.paired_client.clone().expect("the host returned the paired client");
assert_eq!(d.host.paired_client(), Some(&pc));
assert_eq!(pc.cert_der, d.cid.cert_der());
assert_eq!(pc.unique_id.as_deref(), Some(UID));
assert_eq!(pc.device_name.as_deref(), Some(DEVICE));
assert_eq!(pc.matches(d.cid.cert_der()), Ok(true));
assert_eq!(pc.matches(rogue_id().cert_der()), Ok(false));
let pending = d.host.pending_client().expect("phase 1 described the client");
assert_eq!(pending.cert_der, d.cid.cert_der());
assert_eq!(pending.unique_id, UID);
assert_eq!(pending.device_name.as_deref(), Some(DEVICE));
// The host draws exactly S_c and secret_s (16 bytes each), nothing else.
assert_eq!(d.hrng.1, 32);
assert_eq!(d.host.poll_timeout(), None, "Paired is terminal");
}
#[test]
fn several_pins_and_seeds_pair() {
for (p, seed) in [("0000", 2u64), ("9999", 3), ("1234", 4)] {
let mut d = Duo::new(p, p, seed);
d.run().unwrap_or_else(|e| panic!("PIN {p}: {e:?}"));
assert_eq!(d.host.state(), HostPairingState::Paired, "PIN {p}");
}
}
#[test]
fn a_generated_host_identity_pairs() {
let hid = HostIdentity::generate(&mut SeqRng::new(0x1u64), "Lumen Test Host", 1_764_000_000).unwrap();
let parsed = domistream::pairing::ServerCert::from_der(hid.cert_der()).expect("an RSA X.509 certificate");
assert!(hid.cert_der().windows(15).any(|w| w == b"Lumen Test Host"));
assert!(hid.cert_pem().unwrap().starts_with("-----BEGIN CERTIFICATE-----\n"));
let again = HostIdentity::from_der(hid.cert_der(), hid.key_pkcs8_der()).unwrap();
assert_eq!(again.cert_der(), hid.cert_der());
let mut d = Duo::new("2468", "2468", 5);
d.host = HostPairingSession::new(&hid, HostPairingConfig::default(), Instant::ZERO);
d.hid = hid;
let paired = d.run().unwrap();
assert_eq!(paired.server_cert, parsed);
assert_err!(HostIdentity::generate(&mut SeqRng::new(1), "", 0), Error::Malformed { .. });
}
#[test]
fn host_answers_are_fresh_per_session() {
// Same client randomness, different host randomness: the phase-2 answers differ (fresh S_c and secret_s).
let answer2 = |host_seed: u64| {
let mut d = Duo::new("4071", "4071", 9);
d.hrng = Counting(SeqRng::new(host_seed), 0);
d.round().unwrap();
let req = d.next.clone().unwrap();
d.host_answers(&to_host(&req), req.scheme)
};
let (a, b, a2) = (answer2(1), answer2(2), answer2(1));
assert!(matches!(a, PairAnswer::ChallengeResponse(ref v) if v.len() == 48), "{a:?}");
assert_ne!(a, b);
assert_eq!(a, a2, "the host's randomness comes only from the caller");
}
// ================================================================================================ wrong PIN
#[test]
fn wrong_pin_fails_on_both_sides() {
let mut d = Duo::new("1234", "4321", 11);
let r = d.run();
assert_err!(r, Error::PairingRefused);
assert_eq!(d.client.state(), PairingState::Failed(PairingFailure::ProofMismatch), "the client sees it first");
// The client stops; the host waits for phase 4 until its deadline, then fails.
assert_eq!(d.host.state(), HostPairingState::AwaitClientPairingSecret);
let deadline = d.host.poll_timeout().expect("a deadline while in progress");
assert!(!d.host.handle_timeout(deadline), "the deadline itself is still in time");
assert!(d.host.handle_timeout(deadline.saturating_add(Duration::from_micros(1))));
assert_eq!(d.host.state(), HostPairingState::Failed(HostPairingFailure::TimedOut));
assert!(!d.host.handle_timeout(deadline.saturating_add(Duration::from_secs(1))), "only once");
assert_eq!(d.host.paired_client(), None);
}
#[test]
fn wrong_pin_is_caught_by_the_host_when_the_client_carries_on() {
// A client that ignores its own failed check and sends phase 4 anyway (signed correctly): the host's proof
// check catches the PIN mismatch.
let mut d = Duo::new("1234", "4321", 12);
for _ in 0..2 {
d.round().unwrap();
}
assert!(d.round().is_err());
assert_eq!(d.host.state(), HostPairingState::AwaitClientPairingSecret);
let secret = [0x5Au8; 16];
let sig = d.cid.sign(&secret).unwrap();
let r = d.handle(PairPhase::ClientPairingSecret([&secret[..], &sig].concat()), Scheme::Http);
assert_err!(r, Error::PairingRefused);
assert_eq!(d.host.state(), HostPairingState::Failed(HostPairingFailure::WrongPin));
assert_eq!(d.host.paired_client(), None);
}
#[test]
fn the_right_pin_but_a_forged_proof_is_a_wrong_pin() {
// Correct PIN on both sides, but the client's secret is not the one behind H_c.
let mut d = Duo::after(3);
assert_eq!(d.host.state(), HostPairingState::AwaitClientPairingSecret);
let secret = [0x11u8; 16];
let sig = d.cid.sign(&secret).unwrap();
assert_err!(
d.handle(PairPhase::ClientPairingSecret([&secret[..], &sig].concat()), Scheme::Http),
Error::PairingRefused
);
assert_eq!(d.host.state(), HostPairingState::Failed(HostPairingFailure::WrongPin));
}
// ================================================================================================ signatures
/// The genuine phase-4 value the client would send now, split into secret and signature.
fn genuine_phase4(d: &mut Duo) -> (Vec<u8>, Vec<u8>) {
let req = d.next.clone().expect("phase 4 pending");
match to_host(&req).phase {
PairPhase::ClientPairingSecret(v) => (v[..16].to_vec(), v[16..].to_vec()),
other => panic!("expected phase 4, got {other:?}"),
}
}
/// Builds a phase-4 value from the genuine secret and signature.
type Forge = dyn Fn(&[u8], &[u8]) -> Vec<u8>;
#[test]
fn bad_client_signatures() {
let rogue = rogue_id();
let cases: Vec<(&str, Box<Forge>)> = vec![
("signed by another key", Box::new(move |s, _| [s.to_vec(), rogue.sign(s).unwrap()].concat())),
(
"one bit flipped",
Box::new(|s, sig| {
let mut sig = sig.to_vec();
sig[100] ^= 0x08;
[s.to_vec(), sig].concat()
}),
),
("cut short", Box::new(|s, sig| [s, &sig[..sig.len() - 1]].concat())),
("zeroed", Box::new(|s, sig| [s.to_vec(), vec![0; sig.len()]].concat())),
("one byte", Box::new(|s, _| [s, &[1u8][..]].concat())),
];
for (why, make) in cases {
let mut d = Duo::after(3);
let (secret, sig) = genuine_phase4(&mut d);
let r = d.handle(PairPhase::ClientPairingSecret(make(&secret, &sig)), Scheme::Http);
assert_err!(r, Error::PairingRefused, "{why}");
assert_eq!(d.host.state(), HostPairingState::Failed(HostPairingFailure::BadSignature), "{why}");
}
// The genuine value passes.
let mut d = Duo::after(3);
let (secret, sig) = genuine_phase4(&mut d);
let step = d.handle(PairPhase::ClientPairingSecret([secret, sig].concat()), Scheme::Http).unwrap();
assert_eq!(step, HostPairingStep::Answer(PairAnswer::Paired));
assert_eq!(d.host.state(), HostPairingState::AwaitPairChallenge);
}
// ================================================================================================ order
fn phase(n: u8) -> PairPhase {
match n {
1 => PairPhase::GetServerCert { salt: [7; 16], client_cert_pem: CLIENT_CERT_PEM.as_bytes().to_vec() },
2 => PairPhase::ClientChallenge(vec![0; 16]),
3 => PairPhase::ServerChallengeResp(vec![0; 32]),
4 => PairPhase::ClientPairingSecret(vec![0; 16 + 256]),
_ => PairPhase::PairChallenge,
}
}
/// A host in in-progress state `i` (0..6), with the phase it expects (0 = it expects the PIN, no phase).
fn host_in_state(i: usize) -> (Duo, u8) {
match i {
0 => (Duo::after(0), 1),
1 => {
// AwaitPin: phase 1 delivered, PIN not supplied.
let mut d = Duo::after(0);
let req = to_host(d.next.as_ref().unwrap());
let now = d.now;
let step = d.host.handle(&d.hid, &req, Transport::Http, now, &mut d.hrng).unwrap();
assert_eq!(step, HostPairingStep::HoldForPin);
(d, 0)
}
_ => (Duo::after(i - 1), i as u8),
}
}
#[test]
fn out_of_order_phases_are_refused() {
let states = [
HostPairingState::AwaitGetServerCert,
HostPairingState::AwaitPin,
HostPairingState::AwaitClientChallenge,
HostPairingState::AwaitServerChallengeResp,
HostPairingState::AwaitClientPairingSecret,
HostPairingState::AwaitPairChallenge,
];
for (i, want) in states.iter().enumerate() {
for wrong in 1..=5u8 {
let (mut d, expected) = host_in_state(i);
assert_eq!(d.host.state(), *want);
if wrong == expected {
continue;
}
let r = d.handle(phase(wrong), if wrong == 5 { Scheme::Https } else { Scheme::Http });
assert_err!(r, Error::PairingRefused, "phase {wrong} in {want:?}");
assert_eq!(
d.host.state(),
HostPairingState::Failed(HostPairingFailure::WrongOrder),
"phase {wrong} in {want:?}"
);
// Failed is terminal, also for the phase that would have been right.
let right = if expected == 0 { 2 } else { expected };
assert_err!(d.handle(phase(right), Scheme::Http), Error::State { .. });
assert_err!(d.host.supply_pin(&d.hid, pin("4071"), d.now), Error::State { .. });
assert_eq!(d.host.state(), HostPairingState::Failed(HostPairingFailure::WrongOrder));
assert_eq!(d.host.poll_timeout(), None);
}
}
}
#[test]
fn a_replayed_phase_is_refused() {
// Phase 2 accepted, then the same request again.
let mut d = Duo::after(1);
let req = to_host(d.next.as_ref().unwrap());
let now = d.now;
assert!(matches!(
d.host.handle(&d.hid, &req, Transport::Http, now, &mut d.hrng).unwrap(),
HostPairingStep::Answer(PairAnswer::ChallengeResponse(_))
));
assert_err!(d.host.handle(&d.hid, &req, Transport::Http, now, &mut d.hrng), Error::PairingRefused);
assert_eq!(d.host.state(), HostPairingState::Failed(HostPairingFailure::WrongOrder));
}
#[test]
fn paired_is_terminal() {
let mut d = Duo::new("4071", "4071", 21);
d.run().unwrap();
for n in 1..=5 {
assert_err!(d.handle(phase(n), Scheme::Https), Error::State { .. }, "phase {n}");
}
d.host.cancel();
assert!(!d.host.handle_timeout(secs(1_000_000)));
assert_eq!(d.host.state(), HostPairingState::Paired);
}
// ================================================================================================ who is asking
#[test]
fn every_phase_must_come_from_the_phase_1_client() {
let mut d = Duo::after(1);
let mut req = to_host(d.next.as_ref().unwrap());
req.unique_id = "FEDCBA9876543210".into();
let now = d.now;
assert_err!(d.host.handle(&d.hid, &req, Transport::Http, now, &mut d.hrng), Error::PairingRefused);
assert_eq!(d.host.state(), HostPairingState::Failed(HostPairingFailure::WrongClient));
}
#[test]
fn phase_5_needs_https_with_the_phase_1_certificate() {
let rogue = rogue_id();
for (why, cert) in
[("plain HTTP", None), ("another certificate", Some(rogue.cert_der().to_vec())), ("empty", Some(vec![]))]
{
let mut d = Duo::after(4);
assert_eq!(d.host.state(), HostPairingState::AwaitPairChallenge);
let req = PairRequest { unique_id: UID.into(), device_name: None, phase: PairPhase::PairChallenge };
let transport = match &cert {
None => Transport::Http,
Some(c) => Transport::Https { client_cert_der: c },
};
let now = d.now;
assert_err!(d.host.handle(&d.hid, &req, transport, now, &mut d.hrng), Error::PairingRefused, "{why}");
assert_eq!(d.host.state(), HostPairingState::Failed(HostPairingFailure::WrongClient), "{why}");
assert_eq!(d.host.paired_client(), None);
}
let mut d = Duo::after(4);
match d.handle(PairPhase::PairChallenge, Scheme::Https).unwrap() {
HostPairingStep::Paired(c) => assert_eq!(c.cert_der, d.cid.cert_der()),
other => panic!("{other:?}"),
}
}
#[test]
fn identity_must_stay_the_same() {
let mut d = Duo::after(1);
let other = HostIdentity::from_der(d.cid.cert_der(), d.cid.key_pkcs8_der()).unwrap();
let req = to_host(d.next.as_ref().unwrap());
let now = d.now;
assert_err!(d.host.handle(&other, &req, Transport::Http, now, &mut d.hrng), Error::Malformed { .. });
assert_eq!(d.host.state(), HostPairingState::AwaitClientChallenge, "misuse does not end the session");
let mut d = Duo::after(0);
let req = to_host(d.next.as_ref().unwrap());
let hid = host_id();
let now = d.now;
d.host.handle(&hid, &req, Transport::Http, now, &mut d.hrng).unwrap();
assert_err!(d.host.supply_pin(&other, pin("4071"), now), Error::Malformed { .. });
assert_eq!(d.host.state(), HostPairingState::AwaitPin);
}
// ================================================================================================ bad values
fn expect_malformed(mut d: Duo, ph: PairPhase, why: &str) {
let r = d.handle(ph, Scheme::Http);
assert!(matches!(r, Err(Error::Malformed { .. } | Error::TooLarge { .. })), "{why}: {r:?}");
assert_eq!(d.host.state(), HostPairingState::Failed(HostPairingFailure::Malformed), "{why}");
}
#[test]
fn bad_phase_values() {
let pem = |s: &str| PairPhase::GetServerCert { salt: [1; 16], client_cert_pem: s.as_bytes().to_vec() };
expect_malformed(Duo::after(0), pem(""), "empty certificate");
expect_malformed(Duo::after(0), pem("hello"), "not PEM");
expect_malformed(Duo::after(0), pem(EC_CERT_PEM), "not an RSA certificate");
expect_malformed(Duo::after(0), pem(&format!("{CLIENT_CERT_PEM}{CLIENT_CERT_PEM}")), "two certificates");
expect_malformed(Duo::after(0), pem(&"A".repeat(1 << 20)), "huge");
for len in [0usize, 15, 17, 32] {
expect_malformed(Duo::after(1), PairPhase::ClientChallenge(vec![0; len]), &format!("challenge {len}"));
}
for len in [0usize, 16, 31, 33, 48] {
expect_malformed(Duo::after(2), PairPhase::ServerChallengeResp(vec![0; len]), &format!("resp {len}"));
}
for len in [0usize, 15, 16, 16 + MAX_SIGNATURE_BYTES + 1] {
expect_malformed(Duo::after(3), PairPhase::ClientPairingSecret(vec![0; len]), &format!("secret {len}"));
}
}
#[test]
fn bad_unique_ids_and_device_names_in_phase_1() {
for (uid, dev) in [
("", None),
("a&b", None),
("a b", None),
(&*"a".repeat(65), None),
(UID, Some("x".repeat(257))),
(UID, Some("tv\u{1}".to_string())),
] {
let mut d = Duo::after(0);
let req = PairRequest { unique_id: uid.to_string(), device_name: dev.clone(), phase: phase(1) };
let now = d.now;
let r = d.host.handle(&d.hid, &req, Transport::Http, now, &mut d.hrng);
assert!(matches!(r, Err(Error::Malformed { .. } | Error::TooLarge { .. })), "{uid:?} {dev:?}: {r:?}");
assert_eq!(d.host.state(), HostPairingState::Failed(HostPairingFailure::Malformed));
}
}
// ================================================================================================ the PIN slot
#[test]
fn supply_pin_only_while_a_request_is_held() {
let hid = host_id();
let mut s = HostPairingSession::new(&hid, HostPairingConfig::default(), Instant::ZERO);
assert_err!(s.supply_pin(&hid, pin("4071"), Instant::ZERO), Error::State { .. });
assert_eq!(s.state(), HostPairingState::AwaitGetServerCert, "an early PIN does not end the session");
assert_eq!(s.pending_client(), None);
let mut d = Duo::after(1);
assert_err!(d.host.supply_pin(&d.hid, pin("4071"), d.now), Error::State { .. });
assert_eq!(d.host.state(), HostPairingState::AwaitClientChallenge, "a second PIN is refused, nothing else");
}
#[test]
fn deadlines_follow_the_caller_clock() {
let hid = host_id();
let cfg = HostPairingConfig { pin_timeout: Duration::from_secs(60), phase_timeout: Duration::from_secs(10) };
assert_eq!(HostPairingConfig::default().pin_timeout, DEFAULT_PIN_TIMEOUT);
assert_eq!(HostPairingConfig::default().phase_timeout, DEFAULT_PHASE_TIMEOUT);
let mut s = HostPairingSession::new(&hid, cfg, secs(100));
assert_eq!(s.poll_timeout(), Some(secs(110)), "phase 1 within the phase timeout");
let req = PairRequest { unique_id: UID.into(), device_name: Some(DEVICE.into()), phase: phase(1) };
let mut rng = SeqRng::new(1);
assert_eq!(s.handle(&hid, &req, Transport::Http, secs(105), &mut rng).unwrap(), HostPairingStep::HoldForPin);
assert_eq!(s.poll_timeout(), Some(secs(165)), "the PIN within the PIN timeout");
assert!(!s.handle_timeout(secs(165)));
assert!(matches!(s.supply_pin(&hid, pin("4071"), secs(165)).unwrap(), PairAnswer::ServerCert { .. }));
assert_eq!(s.poll_timeout(), Some(secs(175)), "each phase within the phase timeout of the last answer");
let late = PairRequest { unique_id: UID.into(), device_name: None, phase: phase(2) };
assert_err!(s.handle(&hid, &late, Transport::Http, secs(176), &mut rng), Error::TimedOut);
assert_eq!(s.state(), HostPairingState::Failed(HostPairingFailure::TimedOut));
}
#[test]
fn pin_not_typed_in_time() {
let mut d = Duo::after(0);
let req = to_host(d.next.as_ref().unwrap());
d.host.handle(&d.hid, &req, Transport::Http, secs(1), &mut d.hrng).unwrap();
let deadline = d.host.poll_timeout().unwrap();
assert_eq!(deadline, secs(1).saturating_add(DEFAULT_PIN_TIMEOUT));
// Typed one microsecond late, without a timer wake-up first.
let late = deadline.saturating_add(Duration::from_micros(1));
assert_err!(d.host.supply_pin(&d.hid, pin("4071"), late), Error::TimedOut);
assert_eq!(d.host.state(), HostPairingState::Failed(HostPairingFailure::TimedOut));
// The timer fires first.
let mut d = Duo::after(0);
let req = to_host(d.next.as_ref().unwrap());
d.host.handle(&d.hid, &req, Transport::Http, secs(1), &mut d.hrng).unwrap();
assert!(d.host.handle_timeout(secs(1000)));
assert_err!(d.host.supply_pin(&d.hid, pin("4071"), secs(1000)), Error::State { .. });
}
#[test]
fn the_owner_cancels() {
let mut d = Duo::after(0);
let req = to_host(d.next.as_ref().unwrap());
let now = d.now;
d.host.handle(&d.hid, &req, Transport::Http, now, &mut d.hrng).unwrap();
d.host.cancel();
assert_eq!(d.host.state(), HostPairingState::Failed(HostPairingFailure::Cancelled));
assert_err!(d.host.supply_pin(&d.hid, pin("4071"), now), Error::State { .. });
d.host.cancel();
assert_eq!(d.host.state(), HostPairingState::Failed(HostPairingFailure::Cancelled));
// The client is answered paired=0 and stops.
let body = pair_answer_xml(&PairAnswer::Refused).unwrap();
assert_err!(d.client.handle_response(&d.cid, 200, &body, &mut d.crng), Error::PairingRefused);
assert_eq!(d.client.state(), PairingState::Failed(PairingFailure::HostRefused));
}
// ================================================================================================ trusted clients
#[test]
fn trusted_clients_need_no_pin() {
let cid = client_id();
let c = PairedClient::trusted(cid.cert_der()).unwrap();
assert_eq!(c.cert_der, cid.cert_der());
assert_eq!(c.unique_id, None);
assert_eq!(c.matches(cid.cert_der()), Ok(true));
let mut flipped = cid.cert_der().to_vec();
let mid = flipped.len() / 2;
flipped[mid] ^= 1;
assert_eq!(c.matches(&flipped), Ok(false));
assert_eq!(c.matches(&[]), Ok(false));
assert_too_large!(c.matches(&vec![0; MAX_CERT_DER_BYTES + 1]), MAX_CERT_DER_BYTES, MAX_CERT_DER_BYTES + 1);
let ec = pem_blocks(EC_CERT_PEM, "CERTIFICATE").pop().unwrap();
for (bad, why) in [(vec![], "empty"), (vec![0x30], "one byte"), (ec, "EC key"), (flipped[..100].to_vec(), "cut")] {
assert_err!(PairedClient::trusted(&bad), Error::Malformed { .. }, "{why}");
}
assert_too_large!(
PairedClient::trusted(&vec![0x30; MAX_CERT_DER_BYTES + 1]),
MAX_CERT_DER_BYTES,
MAX_CERT_DER_BYTES + 1
);
}
// ================================================================================================ hygiene
#[test]
fn debug_never_prints_host_secrets() {
let key = pem_blocks(HOST_KEY_PEM, "PRIVATE KEY").pop().unwrap();
let hid = host_id();
let s = format!("{hid:?}");
assert!(s.contains("redacted"), "{s}");
assert!(!s.to_lowercase().contains(&common::to_hex(&key[key.len() - 32..])));
assert!(!s.contains(&format!("{:?}", &key[key.len() - 8..])));
let mut d = Duo::after(2);
let s = format!("{:?}", d.host);
assert!(s.len() < 200, "session Debug stays short: {s}");
let req = d.next.clone().unwrap();
let a = d.host_answers(&to_host(&req), req.scheme);
let s = format!("{a:?}");
assert!(s.starts_with("PairingSecret"), "{s}");
assert!(s.len() < 40, "answers print lengths, not bytes: {s}");
}
#[test]
fn transport_scheme() {
assert_eq!(Transport::Http.scheme(), Scheme::Http);
assert_eq!(Transport::Https { client_cert_der: &[] }.scheme(), Scheme::Https);
assert_eq!(phase(1).number(), 1);
assert_eq!(phase(5).number(), 5);
}
+11
View File
@@ -14,7 +14,9 @@ GPL-licensed implementation. This file says what may be read, what may not, and
| Crate docs (docs.rs, crates.io, crate READMEs) | per crate | Read freely. | | Crate docs (docs.rs, crates.io, crate READMEs) | per crate | Read freely. |
| Our own measurements | ours | Captures through our own relay ([tools/lab-relay](../tools/lab-relay)). Mark allowed **one** capture on his PC (answer 16, 2026-11-25), done exactly as [LAB_CAPTURE.md](LAB_CAPTURE.md) says; never his TV, never 192.168.100.217. Recordings stay local (on E:, approved for Play remotely) under `E:\build\play-remotely\lab\`, out of git; only facts and test vectors derived from them go in, with the date and setup. | | Our own measurements | ours | Captures through our own relay ([tools/lab-relay](../tools/lab-relay)). Mark allowed **one** capture on his PC (answer 16, 2026-11-25), done exactly as [LAB_CAPTURE.md](LAB_CAPTURE.md) says; never his TV, never 192.168.100.217. Recordings stay local (on E:, approved for Play remotely) under `E:\build\play-remotely\lab\`, out of git; only facts and test vectors derived from them go in, with the date and setup. |
| Official Sunshine and Moonlight PC **binaries** in that capture | GPL-3.0 (we only run them) | Black-box peers: run, observe their traffic, their `--help` output, their own logs and the files/registry keys they write. Never open their source, never disassemble or decompile them. | | Official Sunshine and Moonlight PC **binaries** in that capture | GPL-3.0 (we only run them) | Black-box peers: run, observe their traffic, their `--help` output, their own logs and the files/registry keys they write. Never open their source, never disassemble or decompile them. |
| Arena Domi Remote (Android, a GPL app built apart from Domi repos) and the official Moonlight PC app, as **clients of Lumen** | GPL-3.0 (we only run them) | Black-box peers (Mark, 2026-12-04, D2): lumen-host logs what they send to it. Same limits as the row above. Their workspaces and source are never opened; the Remote app's own workers drive it and hand over facts only. |
| READMEs and wikis of forbidden projects | n/a | For facts only (licence, release notes, compatibility statements). Never their source files. | | READMEs and wikis of forbidden projects | n/a | For facts only (licence, release notes, compatibility statements). Never their source files. |
| Public OS and SDK documentation (Microsoft Learn; NVIDIA, AMD and Intel encoder SDK docs and API headers; libopus and ViGEm docs) | per vendor | Read for the host side (Lumen), facts in our own words, each page logged. Allowed in the Lumen host lead's brief of 2026-12-04. Never the source of GPL or LGPL projects that wrap these APIs. |
### Approved by Mark (answer 15, 2026-11-25): "Yes, with attribution" ### Approved by Mark (answer 15, 2026-11-25): "Yes, with attribution"
@@ -33,6 +35,10 @@ Never open, read, paste or port code from: **Sunshine, Moonlight (any client: Qt
moonlight-common-c, Moonlight's ENet fork, Apollo, Vibeshine, Rubylight, chiaki** (and forks of them). That also moonlight-common-c, Moonlight's ENet fork, Apollo, Vibeshine, Rubylight, chiaki** (and forks of them). That also
means their source files on GitHub. Their READMEs and wikis are fine for facts. means their source files on GitHub. Their READMEs and wikis are fine for facts.
**For host work (Lumen), also forbidden** (Mark, 2026-12-04, decision D2 in [LUMEN-HOST-PLAN.md](LUMEN-HOST-PLAN.md)):
the source of **OBS Studio** and **FFmpeg** (including any GPL or LGPL code that wraps NVENC, AMF, Quick Sync,
Desktop Duplication or WASAPI). Their documentation pages are fine for facts, like the READMEs above.
### Second-hand GPL facts ### Second-hand GPL facts
Moonshine credits Sunshine for "groundwork" on the host side, and a few Moonshine comments cite Sunshine or Moonshine credits Sunshine for "groundwork" on the host side, and a few Moonshine comments cite Sunshine or
@@ -80,3 +86,8 @@ All entries by the DomiStream protocol engineer. Pinned commits are the ones rea
| S-18 | 2026-11-25 | [fec-rs](https://github.com/hgaiser/fec-rs) at `402f41f970bb8c3ef7c88639821032e3b6460f63`: `LICENSE`, `README.md`, `build.rs` (field tables), `src/galois.rs` (`exp`), `src/matrix.rs` (`vandermonde`), `src/reed_solomon.rs` (`build_matrix`, `new`) | BSD-2. Field GF(2^8) with polynomial 0x11D, generator 2; systematic code whose parity rows are the Cauchy matrix `P[j][i] = 1 / ((m + i) XOR j)`. Its tests also contain the GPL-provenance audio matrix (not taken). | | S-18 | 2026-11-25 | [fec-rs](https://github.com/hgaiser/fec-rs) at `402f41f970bb8c3ef7c88639821032e3b6460f63`: `LICENSE`, `README.md`, `build.rs` (field tables), `src/galois.rs` (`exp`), `src/matrix.rs` (`vandermonde`), `src/reed_solomon.rs` (`build_matrix`, `new`) | BSD-2. Field GF(2^8) with polynomial 0x11D, generator 2; systematic code whose parity rows are the Cauchy matrix `P[j][i] = 1 / ((m + i) XOR j)`. Its tests also contain the GPL-provenance audio matrix (not taken). |
| S-19 | 2026-11-25 | GitHub release API: [Moonlight PC v6.2.0](https://api.github.com/repos/moonlight-stream/moonlight-qt/releases/latest), [Sunshine v2026.914.233613](https://api.github.com/repos/SunshineStream/Sunshine/releases/tags/v2026.914.233613) | Asset names, sizes and sha256 digests for the lab capture pins. Release metadata only. | | S-19 | 2026-11-25 | GitHub release API: [Moonlight PC v6.2.0](https://api.github.com/repos/moonlight-stream/moonlight-qt/releases/latest), [Sunshine v2026.914.233613](https://api.github.com/repos/SunshineStream/Sunshine/releases/tags/v2026.914.233613) | Asset names, sizes and sha256 digests for the lab capture pins. Release metadata only. |
| S-20 | 2026-11-25 | ArenaTV `docs/research/sunshine-api.md` and `docs/research/this-pc.md` (Domi's own research from LizardByte's docs) | Sunshine's API calls, `--creds`, `bind_address`, port offsets, first-run behaviour, this PC's adapters and old install. | | S-20 | 2026-11-25 | ArenaTV `docs/research/sunshine-api.md` and `docs/research/this-pc.md` (Domi's own research from LizardByte's docs) | Sunshine's API calls, `--creds`, `bind_address`, port offsets, first-run behaviour, this PC's adapters and old install. |
| S-21 | 2026-11-30 | [Moonshine](https://github.com/hgaiser/moonshine) at `f184d5e` (same pin as S-9): `src/session/stream/control/mod.rs` again (client message parsing and the control loop), `src/session/stream/mod.rs` (`StreamConfig`), `src/session/stream/video/mod.rs` (PING handling), `src/config.rs` (nothing relevant); the repository tree listing | BSD-2. U10, as facts only: the host reads **no body** from START_B (0x0307), Ping (0x0200), LOSS_STATS, FRAME_STATS or the IDR request; START_A (0x0305) is not a type it knows; inside the encrypted frame an unknown type or a failed decryption is skipped, outside it an unknown type or a bad length ends the session; INVALIDATE_REF_FRAMES `first`/`last` at message bytes 4..8 and 12..16 (LE), short bodies mean "from 0"; each Ping resets a stop deadline, `StreamConfig.timeout` default 60 s; the client-to-host IV is `seq LE ‖ 6 zero ‖ 'C' 'C'`; host messages go reliable on channel 0; the video receiver waits for START_B and takes exactly the 4 bytes `PING`, each PING updating the client address. No value in these parts cites Sunshine or moonlight-common-c (the HDR payload's Sunshine note is the known S-9 case). Used for the probe's default bodies (all empty) and the PROTOCOL.md 3.3 facts. |
| S-22 | 2026-12-04 | Microsoft Learn: [DXGI 1.5 improvements](https://learn.microsoft.com/windows/win32/direct3ddxgi/dxgi-1-5-improvements), [IDXGIOutput5::DuplicateOutput1](https://learn.microsoft.com/windows/win32/api/dxgi1_5/nf-dxgi1_5-idxgioutput5-duplicateoutput1), [IDXGIOutput1::DuplicateOutput](https://learn.microsoft.com/windows/win32/api/dxgi1_2/nf-dxgi1_2-idxgioutput1-duplicateoutput), [Desktop duplication](https://learn.microsoft.com/windows-hardware/drivers/display/desktop-duplication-api), [HDR and advanced colour](https://learn.microsoft.com/windows/win32/direct3darticles/high-dynamic-range), [GraphicsCaptureSession](https://learn.microsoft.com/uwp/api/windows.graphics.capture.graphicscapturesession) (`IsBorderRequired`, `IsCursorCaptureEnabled`), [SendInput](https://learn.microsoft.com/windows/win32/api/winuser/nf-winuser-sendinput), [MOUSEINPUT](https://learn.microsoft.com/windows/win32/api/winuser/ns-winuser-mouseinput), [Security considerations for assistive technologies](https://learn.microsoft.com/windows/win32/winauto/uiauto-securityoverview), [UAC policy for UIAccess in secure locations](https://learn.microsoft.com/windows/client-management/mdm/policy-csp-localpoliciessecurityoptions), [CreateSyntheticPointerDevice](https://learn.microsoft.com/windows/win32/api/winuser/nf-winuser-createsyntheticpointerdevice), [InjectSyntheticPointerInput](https://learn.microsoft.com/windows/win32/api/winuser/nf-winuser-injectsyntheticpointerinput), [Loopback recording](https://learn.microsoft.com/windows/win32/coreaudio/loopback-recording), [AUDIOCLIENT_PROCESS_LOOPBACK_PARAMS](https://learn.microsoft.com/windows/win32/api/audioclientactivationparams/ns-audioclientactivationparams-audioclient_process_loopback_params) | For [LUMEN-HOST-PLAN.md](LUMEN-HOST-PLAN.md): `DuplicateOutput1` takes a list of formats and can deliver HDR/WCG surfaces unconverted, the list should always hold `B8G8R8A8_UNORM`; E_ACCESSDENIED on the secure desktop unless LocalSystem; four duplicating processes per session by default; re-create after desktop switches and mode changes. WGC draws a border, removable only from build 20348 after user consent; cursor capture from 19041. `SendInput` is subject to UIPI and fails silently; absolute moves are 0..65535, `MOUSEEVENTF_VIRTUALDESK` maps to the whole virtual desktop; relative moves get pointer speed applied. UIAccess needs Authenticode signing, a secure install location and is meant for assistive technology. Synthetic touch/pen injection from Windows 10 1809. WASAPI loopback captures the render mix in shared mode; per-process loopback from build 20348. |
| S-23 | 2026-12-04 | NVIDIA [video-sdk-samples](https://github.com/NVIDIA/video-sdk-samples) at `aa3544d`: `Samples/NvCodec/NvEncoder/nvEncodeAPI.h` (API 8.1, sha256 `4d061c34…6042a`); NVIDIA [VideoProcessingFramework](https://github.com/NVIDIA/VideoProcessingFramework) at `e82364f`: `src/TC/third_party/nvEncodeAPI.h` (API 12.0, sha256 `067c5159…b4ad`); GitHub repository metadata of both | Both headers carry NVIDIA's MIT notice for the header file; the repositories are Apache-2.0 / unlicensed samples and the second is archived. Declarations used for the L0 spike shim (struct versions, preset and tuning enums, `NvEncGetEncodePresetConfigEx`, resource registration). No sample `.cpp` file was opened. |
| S-24 | 2026-12-04 | [NVENC Video Encoder API Programming Guide](https://docs.nvidia.com/video-technologies/video-codec-sdk/13.0/nvenc-video-encoder-api-prog-guide/index.html) (SDK 13.0) | Loading `nvEncodeAPI` at run time and `NvEncodeAPICreateInstance`; `NV_ENC_DEVICE_TYPE_DIRECTX` sessions; registering, mapping and unmapping D3D11 textures; tuning info (low latency, ultra low latency), presets P1-P7, CBR filler, forcing IDR, `NvEncInvalidateRefFrames`, intra refresh, look-ahead latency; lock/unlock of the bitstream; async mode only on Windows 10+ WDDM, recommended there; Main10 settings. |
| S-25 | 2026-12-04 | Licences via the GitHub and crates.io APIs and `COPYING` files: nefarius/ViGEmClient (MIT, archived), nefarius/ViGEmBus (BSD-3-Clause, archived), xiph/opus `COPYING` (BSD-style), crates `opus`, `audiopus_sys`, `vigem-client`, `nvidia-video-codec-sdk`, `nvenc`, `windows` | Licence and status only; no source files of these projects were opened. |
+2
View File
@@ -25,3 +25,5 @@ Open (see `docs/PROTOCOL.md` §UNKNOWN):
against the pinned Sunshine (Mark, 2026-11-25: "COntinue roadmap without the check"). Expect `stream-v0.1.x`. against the pinned Sunshine (Mark, 2026-11-25: "COntinue roadmap without the check"). Expect `stream-v0.1.x`.
- U16 (audio parity matrix: audio plays without it at zero loss) and U19 (video encryption layout). - U16 (audio parity matrix: audio plays without it at zero loss) and U19 (video encryption layout).
- `tools/lab-relay` and its scripts were never run (`docs/LAB_CAPTURE.md`); they're kept for byte logs on Day 1. - `tools/lab-relay` and its scripts were never run (`docs/LAB_CAPTURE.md`); they're kept for byte logs on Day 1.
- The live sitting is prepared: `tools/gs-probe` (a desktop probe client driving these state machines over real
sockets, built and unit-tested, never run against a host) and its run book `docs/LIVE-INTEROP.md`.
+324
View File
@@ -0,0 +1,324 @@
# Live interop: the one sitting with Mark
Status: **prepared 2026-11-30, not run.** The probe (`tools/gs-probe`) is built and unit-tested and has never talked
to a host: no Sunshine existed when it was written.
This sitting settles the open UNKNOWNs of [PROTOCOL.md](PROTOCOL.md) §8 live, in one go, and answers the black-box
checks a GameStream client can answer from Arena `docs/PLAY-REMOTELY.md`. That list lives in its handover ("Next on
RESUME", item 3), §8 (the `pairing_id` call, the clients list) and §15 (the test-PC checks); §17 is the installer
spec and is not part of this sitting. The host is the pinned Sunshine
`v2026.914.233613`, installed by arena-host at Turn on to `E:\Apps\Sunshine` and bound to `192.168.100.140`. The
client is our probe, which runs DomiStream `stream-v0.1.0`'s state machines over real sockets from this PC. No
Moonlight, no TV and no other machine take part.
## 0. Hard limits
- **One address.** Every probe socket goes to `192.168.100.140`. If `sessionUrl0` names another host, the probe
records it and still connects only to .140.
- **No listening port on this PC.** During `launch` the probe has only three ephemeral UDP client sockets. Nothing
binds a fixed port.
- **Out folder:** `F:\build\play-remotely\live\<date>\` (E: is full). It is outside git and holds:
- `identity\`: the probe's test-only key and certificate, made on the first run;
- `runs\<utc>-<command>\`: one folder per command, with `log.jsonl` and the dumps.
It is deleted at the end (section 7).
- **Secrets:**
- The probe never prints its key and never logs the stream key (`rikey`), pairing salts, challenges or secrets.
- The PIN goes to the operator's terminal only, never to the log. Every log line is also scanned for the session
key's hex before it is written.
- Sunshine's API credentials stay in Custos: never typed, never on a command line, never in a log.
- **Nothing changes on Mark's PC** during the sitting: no Sunshine config, firewall, arena-host setting or install.
The only exceptions are the steps below that the run book names (pairing the probe, launching one game) and their
undo in section 7.
- **The stop-and-report rule** (section 6) wins over everything in this file.
## 1. What Mark sees
- **Nothing on his screen except:**
- Sunshine's own notifications, if any (for example when a client asks to pair, or a stream starts or ends);
- at `launch`, the game starting on his PC;
- at `quit`, the game closing.
- The probe runs in our terminal. No UAC prompt, no Custos card (Arena Domi was approved at Turn on), and no PIN is
shown to Mark.
- **Two things we cannot rule out before the sitting.** If either appears, Mark answers as below and we stop and
report:
- A **Windows Security Alert** for `probe.exe` when its UDP sockets first receive. Mark clicks **Cancel**.
- **Arena Domi's own first-stream toast** (PLAY-REMOTELY §7.4). It can appear if the Arena window is running when
Sunshine's prep-cmd hook reports the probe's stream. Mark dismisses it.
- **Mark's part:** be present, agree on the game for `launch` beforehand (a light one from the `apps` list), and keep
hands off mouse and keyboard while the stream runs (90 s for the first launch, about 30 s for any variant).
## 2. Before the sitting (without Mark)
| # | What | How |
| :-- | :-- | :-- |
| P1 | Probe built | `cd tools\gs-probe`, `CARGO_BUILD_BUILD_DIR=F:\build\play-remotely\cargo-build-probe`, `TEMP`/`TMP=F:\build\play-remotely\tmp\protocol`, load gate (CPU and RAM < 90 %, D: and F: < 95 %), then `cargo test --offline -j 2` and `cargo build --offline --release -j 2`. Binary: `tools\gs-probe\target\release\probe.exe`. |
| P2 | Sunshine as arena-host left it (read-only) | `Get-NetTCPConnection -State Listen \| ? LocalPort -in 47984,47989,47990,48010` shows each on `192.168.100.140` only: nothing on `0.0.0.0` or loopback on Day 1 (PLAY-REMOTELY §4). `Get-NetUDPEndpoint \| ? LocalPort -in 47998,47999,48000` is empty while idle (PLAY-REMOTELY §9). |
| P3 | Sunshine's API without seeing the credentials (**decided: a**, build lead 2026-11-30) | Needed for the PIN (step S2) and checks B1–B3. The host engineer writes a dev-only `sunshine-api <GET\|POST> <path> [json]` command in arena-host (Play remotely's own crate), behind a cargo feature that never ships. It takes the credentials from Custos (never typed, printed or logged), calls `https://192.168.100.140:47990` with arena-host's pinned client (§3, §4) and prints the answer with secrets redacted. Its first call also answers §15's "does `pc` cover a self-connection to .140". It must be built and checked before the sitting; this file writes the calls as `sunshine-api …`. |
| P4 | U10 bodies (**done** 2026-11-30, CLEAN_ROOM S-21) | Moonshine (BSD-2) reads **no body** from START_B, PERIODIC_PING or the IDR request, ignores LOSS_STATS and FRAME_STATS, and does not know START_A. Inside the encrypted frame, an unknown type is skipped, not fatal. Each PERIODIC_PING pushes its stop deadline out (60 s by default). Nothing taken has GPL provenance. The probe's defaults follow: START_A and START_B empty, PERIODIC_PING empty every 500 ms, an empty IDR request on frame loss. Table V holds what to try if Sunshine differs. |
| P5 | Game | Agree the `launch` game with Mark (a light one) and note its app id after S4. |
Shell variables used below (PowerShell):
```powershell
$P = "F:\Akce\DomiStream-wt-probe\tools\gs-probe\target\release\probe.exe"
$O = "F:\build\play-remotely\live\2026-12-XX" # the sitting's date
$H = "192.168.100.140"
```
Exit codes: 0 done, 1 error, 2 bad command line, 3 **stop and report** (a `stop` record is in the log).
## 3. The sequence
Each step names the command, the UNKNOWNs it settles and what to look for. "Log" means that run's
`$O\runs\<utc>-<command>\log.jsonl` (format in section 4).
### S0. Preflight (read-only, 1 min)
- Run the P2 checks again.
- Sunshine's own traffic baseline (B4): `Get-NetTCPConnection -OwningProcess (Get-Process sunshine).Id` and
`Get-NetUDPEndpoint -OwningProcess …`. Note every remote address.
### S1. `& $P serverinfo --host $H --out $O`
- **Settles:** U25 (codec bits, from a host whose GPU we know: RTX 3090).
- **Look for:**
- `serverinfo.http` recv: status 200, the XML in full;
- the note with `parsed` and `codec_mode_support_bits`;
- `HttpsPort` (if it is not 47984, add `--https-port` to every later command);
- `appversion`, `state` (…`_FREE`), `PairStatus 0`.
- On the first run the probe generates its identity: log record `identity` (`generated a new …`).
### S2. `& $P pair --host $H --out $O`
- **Settles:**
- U1: the parameter names we send are accepted, and the order of steps 4 and 5;
- U2: our RSA-2048 self-signed certificate is accepted;
- U24: the TLS version and suite at step 5;
- with B1 and B2, PLAY-REMOTELY §8.
- **Procedure.** The probe prints `PIN for the operator: NNNN` and waits up to 120 s at step 1. Within that time:
1. **B1, the pending pairing.**
- Call each documented read-only GET of the pinned API docs (at least `sunshine-api GET /api/clients/list`).
- Look for an entry naming the probe's `uniqueid` (log record `identity`) or the device name
`DomiStream probe`.
- Read `E:\Apps\Sunshine\config\sunshine.log` (black-box: Sunshine's own log, read-only) for a line about the
incoming pairing and any id it names.
- Record which call or line shows the pending pairing and its `pairing_id`.
2. **Submit:** `sunshine-api POST /api/pin '{"pairing_id":"<id>","pin":"NNNN","name":"DomiStream probe"}'`. If no
`pairing_id` was found, try `{"pin":"NNNN","name":"DomiStream probe"}` once and record the answer. If that is
refused too: stop and report (B1 open, and pairing cannot go on).
3. The probe goes on by itself through steps 2–5 and ends with an HTTPS `serverinfo` (`PairStatus 1`).
- **Look for:**
- `pair.1` … `pair.5`: send and recv of each step (values redacted, names and order kept);
- `pair.1`'s `elapsed_ms` (the time until the PIN went in);
- the `host certificate sha256` note;
- `pair.5`'s `tls` (version, suite);
- `pair.done`;
- on failure, the `stop` record, with the step and the state it failed in.
- **B2:** `sunshine-api GET /api/clients/list` must show exactly one new client, named `DomiStream probe`. Record the
entry's fields: this is also B3's input.
### S3. `& $P apps --host $H --out $O`
- **Settles:** nothing new. It confirms HTTPS with the pinned certificate (U24 again).
- **Look for:** the agreed game's id (P5); `Desktop`, if listed, is the fallback.
### S4. `& $P launch <id> --host $H --out $O --seconds 90 --nudge-mouse`
90 s outlasts Moonshine's 60 s no-ping deadline. A stream that lives to the end shows Sunshine accepts the default
empty PERIODIC_PING, or does not need one within 90 s; `sunshine.log` tells which (U10). Variants use `--seconds 30`.
- **Mark sees** the game start.
- **Settles:**
| Area | UNKNOWNs |
| :-- | :-- |
| Launch | U4 |
| RTSP | U5, U6, U7, U26 |
| UDP setup | U8 |
| Control stream | U9, U10, U11 |
| Video | U13, U14, U15, U29; U19 only if the host offers video encryption |
| Audio | U17; data for U16 |
| Host events | U23, only if any arrive |
- **Look for**, in order:
| Record | Settles | What it shows |
| :-- | :-- | :-- |
| `launch` send/recv | U4 | Our parameter set accepted (`uniqueid, appid, mode, rikey=<redacted>, rikeyid, hdrMode, surroundAudioInfo`); `gamesession`, `sessionUrl0` |
| `rtsp.*` send/recv | U5 | Every request and answer in full; `end` (`Length` / `Closed` / `Idle`), `content_length_header`, and notes about new TCP connections |
| `rtsp.describe` recv | U26 | The SDP: every `surround-params` line, `encryptionSupported`, `featureFlags` |
| `rtsp.setup_*` recv | U5, U7 | Every header of the three answers (`Session`, `Transport`, anything extra) |
| `rtsp.announce` | U6 | 200 means our 19 attributes are accepted as they are |
| `ping` + `video.first` / `audio.first` | U8 | Payload `PING`; `pings_before` and the source port of the first packet |
| `control.datagram` (first 64 each way) | U9 | Decoded ENet: our connect, the host's verify connect (channel count, MTU, window, flags), anything stock 1.3 lacks (`unparsed: …` or `parse_error`) |
| `control.start_a`, `control.start_b` | U10 | What we sent (empty bodies by default). Video then flowing means the host accepted it |
| `control.periodic_ping` (first 3), `launch.summary` `control.ended` | U10 | The empty ping every 500 ms; `ended` null after 90 s means the pings kept the session alive |
| `control.host` | U10, U11, U23 | Every decrypted host message: type, sequence, body |
| `video.frame` (first 16) | U13 | `header_raw`: Wolf's constant `0137636861727373` or Moonshine's fields |
| `launch.summary` | U14 | `u14_*`: whole-packet parity matches (5.3 confirmed), or payload-only, or neither |
| `launch.summary` | U15 | `multi_fec_flags_u15` histogram |
| `launch.summary` | U29 | `u29_rtp_ticks_per_frame`, `u29_clock_hz_estimate` (90000 expected) |
| `launch.summary` | U17 | `u17_decrypting` vs `u17_plain`: the receiver that accepts the packets says whether audio is encrypted. Compare with bit 0x04 of `negotiated.encryption` |
| `launch.summary` | U19 | `decrypt_failures` is 0 when video encryption was negotiated |
| `audio.u16` | U16 | Matrix solved from `audio-packets.bin` (or later: `& $P solve-audio-fec <run>\audio-packets.bin`); `matrix_is_mds` |
| `launch.summary` counters | — | Video: `frames`, `decode_ready_frames`, `frames_lost`, `fec_recovered_shards`. Audio: data and parity packets, losses |
- **B3, per-device input:**
- The `--nudge-mouse` input is one relative move of +1 then −1 pixel after the first decodable frame:
harmless, and invisible to Mark.
- If the B2 entry has a per-client input field, an extra launch with that input turned off for the probe shows
whether Sunshine drops it (watch `sunshine.log`). That launch needs the build lead's OK: it changes a Sunshine
setting.
- If the entry has no such field, record "per-client: enable/disable only".
- **B4:** during the stream, list Sunshine's sockets again (S0). The three UDP ports appear, and no remote address
besides .140 shows up.
- **B5:** with arena-host running, the prep-cmd hook should report `start <game>` with
`SUNSHINE_CLIENT_NAME = DomiStream probe`, and arena-host should write its audit record "Play remotely started".
Record what happened.
- Then `& $P quit --host $H --out $O`: the game closes. B5 again: `end`.
**Variants (table V), only when S4 stops.** Each variant is one `launch` (with `quit` before the next). There are at
most 6 launches in the sitting, and the same variant is never tried twice.
| Symptom (log) | Variant |
| :-- | :-- |
| ANNOUNCE not 200 (U6) | `--encryption 1`, then `--codec hevc`, then `--packet-size 1392`. Attribute values beyond the CLI need a code change: stop and report |
| No verify connect, ENet `timed_out` (U9) | `--enet-channels 48`. Nothing else is known about the connect fields: stop and report |
| Connected, but the host ends the session right after START_A, or `sunshine.log` names an unknown control message (U10) | `--start-a none` (Moonshine has no START_A) |
| Connected but no video within 5 s of START_B (U10) | Read `sunshine.log` for what it says about START_B. If it names a body or a length, give that body with `--start-b <hex>` (one try). Otherwise stop and report: P4 found no body, and none is guessed |
| Video stops after N s, host disconnects (U10) | `--periodic-ping-ms 100`; if it still stops, `--periodic-ping none` (to see whether the empty ping is what the host refuses), then stop and report |
| Frames lost and never recovered (U10) | `--rfi`, if DESCRIBE has `refPicInvalidation`; else `--idr none`, to compare with the default empty request |
| Surround (U26), only if time allows | `--audio 5.1` |
### S5. U28, a refused pairing (optional, 2 min)
1. `& $P unpair --host $H --out $O`.
2. `& $P pair --host $H --out $O --wrong-pin`. The probe prints one PIN, uses another, and must stop at step 3 with
`ProofMismatch`.
3. Submit the printed PIN as in S2.
4. Look for:
- what `/api/pin` answers;
- whether B1's call still lists a pending pairing afterwards;
- whether the client list stays without the probe;
- whether a fresh `probe pair` works without any clean-up. That last point is U28's answer.
5. Leave it unpaired.
## 4. Reading the log
One JSON object per line, flushed as written:
```json
{"n":12,"t_ms":845.210,"step":"rtsp.setup_video","kind":"recv","u":["U5","U7"],"data":{…}}
```
- **`kind`:**
- `send`: what the probe sent;
- `recv`: what the host sent;
- `note`: an observation;
- `parse_error`: the parser's error plus the bytes that caused it (hex or text, capped at 4 KiB);
- `stop`: the stop-and-report rule fired;
- `summary`: the end-of-step counters.
- **`u`:** the UNKNOWNs the record bears on.
- **Filtering** (PowerShell):
`Get-Content log.jsonl | ConvertFrom-Json | ? { $_.u -contains 'U5' } | ConvertTo-Json -Depth 8`.
- **Run folder contents:**
- `video.h264` (or `.h265`): the first `--dump-frames` frames' Annex-B elementary stream, for `ffprobe` later.
The probe decodes nothing.
- `video-packets.bin`: plaintext video packets, `--dump-packets` of them.
- `audio-packets.bin`: audio datagrams as received.
The `.bin` files use the format in `tools/gs-probe/src/dump.rs`. **The video files hold frames of Mark's game:**
they never go into git and are deleted after analysis.
## 5. From the log to PROTOCOL.md and the code
1. **Facts first.** Each settled UNKNOWN gets its fact in PROTOCOL.md with the tag `[L2]` (live sitting, date,
Sunshine `v2026.914.233613`, probe commit). Add the tag to the tag table and the row to §8. An UNKNOWN that stays
open says why.
2. **Tests before code** (repo rule). Every fact becomes a unit test or vector in `crates/domistream`:
- structure and constants only;
- re-encrypted with keys generated in the test;
- never bytes of Mark's video.
3. **Where each U lands:**
| U | PROTOCOL.md | Code |
| :-- | :-- | :-- |
| U1, U28 | 1.5 | `pairing/mod.rs` (`request`, step order) |
| U2 | 1.5 | `pairing/identity.rs` (`generate`) |
| U4 | 1.4 | `http/launch.rs` (`launch_request`, the `sessionUrl0` default) |
| U5 | 2.1, 2.2 | `rtsp/mod.rs` (`RtspFramer`), `rtsp/client.rs` (`CLIENT_VERSION`, `SETUP_TARGETS`, `TRANSPORT`, `Session` echo, PLAY target) |
| U6 | 2.4 | `rtsp/sdp.rs` (`build_announce`) |
| U7 | 2.2 | `rtsp/client.rs` (`advance`, `NegotiatedStream`) |
| U8 | 5.1, 6.1 | `rtsp/client.rs` (`PING_PAYLOAD`); the ping interval in the platform layer's docs |
| U9 | 3.1 | the `EnetConfig` defaults the callers use (docs in `enet/mod.rs`); `enet/protocol.rs` only if the host sends something stock 1.3 lacks |
| U10 | 3.3 | `control/message.rs` (`encode_client_message`: START_A, START_B, PERIODIC_PING, IDR bodies instead of `Unsupported`), `control/mod.rs` (send PERIODIC_PING on `ping_interval`) |
| U11 | 3.2 | `control/mod.rs` (`next_sequence` start, replay rule) |
| U13, U15 | 5.2 | `video/packet.rs` (docs, `FrameHeader`) |
| U14 | 5.3 | `fec.rs`: confirmed, nothing to change (or stop and report if `u14_no_match`) |
| U16 | 6.4 | a `pub const` parity matrix in `audio/mod.rs`, used as `AudioFec::ParityMatrix` by the callers |
| U17 | 6.3 | `AudioConfig.cipher` policy (docs in `audio/mod.rs`) |
| U19 | 7 | `video/mod.rs` (`VideoCipher::decrypt`) |
| U23 | 3.3 | `control/message.rs` (host event bodies) |
| U25, U27 | 1.2, 1.1 | `http/serverinfo.rs`, `http/xml.rs` docs |
| U26 | 2.3 | `rtsp/sdp.rs` |
| U29 | 5.2 | `rtp.rs` / `video/mod.rs` docs |
4. **Re-run** clippy, fmt, rustdoc, the tests, the mutation script and the fuzz targets of the touched parsers (load
gate first).
5. **Re-run the probe** against Sunshine with the patched crate: `launch` with **no** variant flags must give
`decode_ready_frames > 0`, audio packets, and no `stop`. Then release `stream-v0.1.1` (HANDOVER).
6. **Arena:** B1–B5 answers go to Arena `docs/PLAY-REMOTELY.md` (handover, §8, §15). That file and arena-host are Play
remotely's own, so we write them; the seam files stay the Arena build lead's.
**Not settled by the probe:**
- U20, U21, U22: no keyboard, touch or gamepad input beyond the one mouse nudge.
- U24 beyond what rustls negotiates.
- U26 beyond stereo, unless the 5.1 variant runs.
- U19, if the host does not offer video encryption.
- U23, if no host event arrives.
`tools/lab-relay` cannot be used as it stands: its upstream must be loopback, and Sunshine listens on .140 only.
`--relay` is ready on the probe side if the build lead ever widens that rule. The probe's own log already holds the
plaintext of HTTP, HTTPS and RTSP, and the decrypted control messages.
## 6. Stop and report
**Stop** means: no further probe command, no Sunshine call beyond read-only GETs, no retry outside table V. Report to
the coordinator:
- the step;
- the log path and the record number `n`;
- what was expected;
- what was seen.
Then wait.
**Stop when:**
- a probe command exits with code 3 (a `stop` record), or with 1;
- anything appears on Mark's screen beyond section 1's list, or Mark asks to stop;
- any socket of the probe or of Sunshine talks to an address other than `192.168.100.140` or loopback;
- Sunshine crashes, restarts, or its notifications show an error;
- the game misbehaves, or the PC slows down noticeably;
- an answer fits none of the expectations above, even if the probe accepted it;
- table V is used up (6 launches), or a variant would need a code change, a Sunshine setting or an install;
- a secret shows up anywhere it should not (terminal, log, file name). Stop at once and delete the record.
## 7. Clean-up (same sitting)
1. `& $P quit --host $H --out $O`, if a game is still running.
2. `& $P unpair --host $H --out $O`, then B2 again: the client list no longer shows the probe.
3. Delete `$O\identity\` (the probe's test key).
4. **The run folders stay** until the facts are in PROTOCOL.md and the tests are in. Then they are deleted on the
build lead's word. `video.*` and `video-packets.bin` go first, right after the U13/U14/U15/U29 analysis.
5. Nothing to undo on Sunshine, arena-host or the firewall: nothing was changed.
## 8. Timeline for Mark (about 20 minutes)
| When | What happens | Mark |
| :-- | :-- | :-- |
| 0:00 | S0, S1: read-only checks, `serverinfo` | nothing |
| 0:02 | S2: the probe pairs (we submit the PIN through Sunshine's API). Sunshine may show a notification | nothing |
| 0:05 | S3, S4: the agreed game starts on his PC and streams to the probe for 90 s; then we close it | hands off mouse and keyboard while it runs |
| 0:07-0:15 | Variants, only if needed (up to 6 launches, each about 1 min) | same |
| 0:15 | S5 (optional), clean-up | nothing |
| later | Analysis offline; the game frames are deleted | nothing |
+568
View File
@@ -0,0 +1,568 @@
# Lumen host: the plan
Status: **plan, 2026-12-04; Mark's go for phase one (L0 + L1) on 2026-12-04**, with all six decisions of section 8
accepted as proposed. Later milestones start after phase one is reported.
Goal (Mark, 2026-12-04): "move away from Sunshine". Today Arena Domi's Play remotely wraps Sunshine, a separate
GPL-3.0 program that Arena Domi installs and drives only through its local settings API. Lumen is Arena Domi's own
streaming host. It replaces Sunshine on the PC, so that Arena Domi Remote (Android), the Windows client and Arena
Domi TV stream from Lumen instead. Sunshine stays as a hidden fallback until Mark removes it.
This file is public, like the rest of DomiStream. It holds the architecture, the split between DomiStream and the
private Arena Domi repository, the milestones, the risks and the tests. Network addresses, the owner's devices beyond the
reference PC's hardware, and the private Play remotely design stay in Arena's `docs/ROADMAP-REMOTE.md` (section
"Lumen host").
Words used here:
- **host**: the PC that runs the game and streams it; **client**: the phone, TV or PC that shows it.
- **GameStream**: the protocol that Sunshine and the Moonlight-family clients speak, as described in
[PROTOCOL.md](PROTOCOL.md).
- **lumen-host**: the Windows program that is the Lumen host (section 1.1).
---
## 0. Ground rules this plan keeps
- **Clean room** ([CLEAN_ROOM.md](CLEAN_ROOM.md)). No code of Sunshine, Moonlight (any client, including
moonlight-common-c), Apollo, Vibeshine, Rubylight or chiaki is opened, pasted or ported. That includes the GPL
fork that Arena Domi Remote is built from: its workspace is never opened by anyone working on Lumen, and nothing
of it enters a Domi repository. Host-side facts come from the Wolf docs, Moonshine (a BSD-2 host, see 6.1), stock
ENet, tokio-enet, fec-rs, public OS and SDK documentation, and our own measurements. Every source is logged in the
source log in the same PR that uses it.
- **Sans-I/O protocol code stays here**; sockets, TLS, the GPU, audio devices and input injection live in the
program that uses DomiStream (section 3).
- **Hostile input**: everything a client sends is parsed strictly, every length is capped before it allocates, and
every parser has a fuzz target.
- **No admin rights.** lumen-host runs as the signed-in user, never as a service or as SYSTEM. The only elevation
in the plan is the one Mark already allowed at "Turn on Play remotely", and whether Lumen's firewall rules may use
it is decided: D1, yes, the same single step.
- **Nothing leaves the PC by default.** lumen-host listens only on the addresses Play remotely allows; every
session start and stop is audit-recorded, like today.
- **No injection into a game process, no DirectX/Vulkan hooks, no reading game memory.** Lumen captures the display
the game is shown on and injects input through public Windows input APIs, like a keyboard, mouse or pad would.
- **Measure, don't guess.** Every latency claim comes from the harness (section 7.4).
---
## 1. Host architecture
```
lumen-host (one process, signed-in user, medium integrity)
┌──────────────────────────────────────────────────────────────────────────────────────────┐
│ capture ──► colour convert + scale ──► encode ──► packetize + FEC ──► pace ──► UDP video │
│ (DXGI dup., (GPU shader: FP16 scRGB (NVENC, (DomiStream │ │
│ FP16 or → NV12 BT.709 or P010 zero copy) host side) │ │
│ BGRA8) BT.2020 PQ, limited/full) │ │
│ WASAPI loopback ──► resample ──► Opus ──► packetize + FEC + AES-CBC ─────────► UDP audio │
│ control (ENet host + AES-GCM) ◄──► input mapper ──► SendInput / ViGEmBus / pointer inject │
│ HTTP/HTTPS (pairing, serverinfo, applist, launch) and RTSP (session setup), TLS via rustls │
│ session: launch game from Arena's library, watch it, game mode, audit, end │
└──────────────────────────────────────────────────────────────────────────────────────────┘
▲ arena-host (in Arena Domi): turns Lumen on/off, pairing gate, grants, which engine per device
```
### 1.1 Process model
- **One program, `lumen-host.exe`**, separate from the Arena Domi window and from the tray agent. A crash in it
never takes the window or the agent down, and it can be stopped cleanly.
- **Two states.** *Idle*: only the HTTP/HTTPS and RTSP listeners are open (a few sockets, no GPU, no audio device,
no threads busy), so a phone can see the PC and pair. *Streaming*: capture, encode, audio and input start when a
paired client launches a game, and stop when the session ends. One streaming session at a time in the first
version.
- **Started by Arena Domi**, never by Windows as a service. Who starts it at sign-in (the tray agent is the natural
owner, because it always runs) is decided: D4, the tray agent, once Lumen is the default.
- **Priorities**: the idle listeners run at below-normal priority. While streaming, the capture/encode thread and
the packet pacer register with the Multimedia Class Scheduler Service (no admin needed) and everything else stays
normal or below. The cost to the game is measured (section 7.4), not assumed.
### 1.2 Capture
| | DXGI Desktop Duplication (`IDXGIOutput5::DuplicateOutput1`) | Windows.Graphics.Capture |
| :-- | :-- | :-- |
| What it captures | a whole output (monitor), any game shown on it, fullscreen included | a monitor or one window |
| HDR | yes: pass a list of formats that includes `R16G16B16A16_FLOAT` and the FP16 scRGB desktop arrives without conversion | yes, by choosing the frame pool's pixel format |
| Capture border | none | a yellow border; it can be turned off only from Windows 10 build 20348 (`IsBorderRequired`) and after the user grants borderless access |
| Cursor | given separately (shape + position): we draw it, or not | `IsCursorCaptureEnabled` from Windows 10 2004 |
| Limits | E_ACCESSDENIED on the secure desktop (UAC prompt, lock screen) unless the process runs as LocalSystem; at most four duplicating processes per session by default; must be re-created after a mode change or a fullscreen switch | per-window capture survives window moves; needs the WinRT interop |
**Choice: Desktop Duplication first, Windows.Graphics.Capture as a later option** for single-window streaming on
Windows 11, where the border can be turned off. Reasons: the reference PC runs Windows 10 22H2 (build 19045), where
WGC would draw a yellow border over the game; duplication captures exclusive-fullscreen games; and it hands us FP16
directly. Sources: S-22 (section 9).
- **DPI awareness**: lumen-host is per-monitor DPI aware (v2). Measured in L0: without it `DuplicateOutput1`
fails with `DXGI_ERROR_UNSUPPORTED` and output sizes are DPI-virtualised.
- **Formats asked for**: `R16G16B16A16_FLOAT`, `R10G10B10A2_UNORM`, `B8G8R8A8_UNORM` (the last one always, as
Microsoft asks). The format that arrives decides the colour path (1.3).
- **Frames only on change**: duplication delivers a frame only when something changed. The pacer repeats the last
encoded frame (or sends nothing, if the client tolerates gaps; measured) so that the client sees its frame rate.
- **The secure desktop** (UAC prompt, lock screen, Ctrl+Alt+Del) cannot be captured without SYSTEM rights, and
input cannot reach it either (1.6). lumen-host keeps the stream alive and sends a still frame that says "Finish
this on the PC", then resumes when the desktop comes back (`EVENT_SYSTEM_DESKTOPSWITCH` / re-creating the
duplication). This is an accepted limitation of the no-admin rule, not a bug to fix later.
- **Which monitor** (the reference PC has a 1440p HDR primary display and a 2160p second display):
1. the monitor that shows the launched game's main window (found from the game's process, re-checked when the
window moves);
2. otherwise the client's own choice ("Stream this display", per device, in Settings → Play remotely);
3. otherwise the primary monitor.
A monitor switch during a stream re-creates the duplication and sends an IDR frame; the client keeps its
resolution.
- **Resolution**: the client asks for a size in ANNOUNCE. Lumen never changes the PC's display mode in the first
version (the owner's desktop stays as it is); it scales on the GPU in the colour pass (for example 2160p to 1080p
for a phone) and keeps the aspect ratio with black bars. A virtual display per client is roadmap Day 6.
- **GPU**: the duplication device is created on the adapter that drives the output. If the encoder is on another
adapter (laptops), one cross-adapter copy is made; on the reference PC both are the same GPU, so there is no copy.
### 1.3 Colour: SDR, HDR, limited or full range
The rule: **what the phone shows must look like what the PC shows**, for the same content, so the colour path is
explicit at every step and tested with patterns (7.5).
| Desktop (capture format) | Client asks for | Conversion on the GPU (one compute pass, fused with scaling and the cursor) | Encoder input | Signalled in the bitstream (VUI) |
| :-- | :-- | :-- | :-- | :-- |
| SDR (BGRA8, sRGB) | SDR | RGB → Y'CbCr BT.709, limited or full range | NV12 | BT.709 primaries, transfer and matrix; full-range flag as negotiated |
| HDR (FP16 scRGB, linear) | SDR | scale by the display's **SDR white level** (so SDR apps keep the brightness they have on the PC), tone-map highlights above SDR white with a fixed curve, encode with the sRGB/BT.709 transfer | NV12 | as above |
| HDR (FP16 scRGB) | HDR | linear BT.709 → BT.2020 primaries → PQ (SMPTE ST 2084), 10-bit | P010 | BT.2020, PQ, BT.2020 non-constant matrix; mastering metadata from the output's description (`IDXGIOutput6::GetDesc1`) |
| HDR10 game in `R10G10B10A2` | HDR | pass through when the output is already in BT.2020/PQ | P010 | as above |
- **Range**: the client tells the host its colour space and range in ANNOUNCE (`encoderCscMode`, PROTOCOL.md 2.4).
The bit meanings are **unknown** (U6 territory); they are settled by measurement: what Arena Domi Remote and our
own clients send for each of their settings, and how the decoded test pattern looks (7.5). Until a client's value
is understood, Lumen uses **BT.709 limited range** for SDR, the most common decoder default, and says so in the
stream's VUI, so a correct decoder shows correct colours either way.
- **HDR to the client** needs the host-to-client HDR message (`0x010e`, PROTOCOL.md 3.3). Its layout is
GPL-provenance ([M*]): it is **not** used from Moonshine's note; it is settled by our own measurement (6.2) before
Lumen sends HDR. Until then Lumen streams SDR to every client, tone-mapped as above.
- **Chroma**: 4:2:0 first. 4:4:4 (text mode) is roadmap Day 5.
- The SDR white level is read per display from Windows (`DisplayConfigGetDeviceInfo`, SDR white level), not
assumed.
### 1.4 Encode
- **NVENC first** (the reference PC has an NVIDIA Ampere GPU: H.264 and HEVC 8/10-bit encode; AV1 encode needs a
newer generation). AMD AMF and Intel Quick Sync come later behind the same `Encoder` trait, and Media Foundation's
hardware encoder is the generic fallback.
- **Zero copy**: the colour pass writes into a D3D11 texture that is registered with NVENC as an input resource, so
a frame never leaves the GPU between capture and the bitstream. The bitstream (a few kilobytes) is the only thing
read back to the CPU.
- **Low-latency settings** (named here as the NVENC programming guide names them; the guide is read and logged in
milestone L0 before any of this is written): ultra-low-latency tuning, no B-frames, no look-ahead, CBR with a VBV
of about one frame, an infinite GOP with IDR only on request, reference-frame invalidation when the client reports
a lost range (`INVALIDATE_REF_FRAMES`) and supports it, optional intra refresh instead of IDR frames, and slices
sized to the video packet size where that helps the FEC blocks.
- **Codec choice**: HEVC by default (smaller frames at the same quality, HDR possible), H.264 for clients without
HEVC; the client's ANNOUNCE (`bitStreamFormat`) decides, within what serverinfo advertised.
- **Bitrate**: from the client's request (`configuredBitrateKbps`), capped by what the encoder supports; adaptive
bitrate belongs to Lumen's own transport (roadmap Day 4).
- **Interface to NVENC**: NVIDIA's public API header and the driver's `nvEncodeAPI64.dll`, loaded at run time, so
nothing of NVIDIA ships in Arena Domi. The header is MIT-licensed by its own notice; L0 settled which one (section
10: API 12.0, because current drivers refuse the older API's presets). We do not read
the source of GPL or LGPL projects that wrap NVENC (FFmpeg, OBS Studio and the like); see 6.1.
### 1.5 Audio
- **Capture**: WASAPI loopback on the default render device (shared mode), which is the full mix the PC plays.
Per-process loopback (only the game, without voice chat or notifications) needs Windows 10 build 20348 or newer,
so it is an option for Windows 11 PCs, not the reference PC. Sources: S-22.
- **The PC keeps its own sound** in the first version (Lumen changes no audio setting). Muting the PC's speakers
while streaming is a later, opt-in choice.
- **Encode**: libopus (BSD-3-Clause) through a Rust binding whose licence is checked and logged; 48 kHz, stereo
first, 5.1/7.1 when the surround mapping is measured (U26). Frame duration from ANNOUNCE (`packetDuration`),
constant bitrate, because the audio FEC needs equally long packets (PROTOCOL.md 6.4).
- **Audio FEC** needs the parity matrix (U16), which is GPL-provenance. Lumen first sends audio **without** parity
packets and checks that every client plays it (6.2); the matrix is then measured and solved by us (PROTOCOL.md
U16) before parity is sent.
- **Audio encryption**: AES-128-CBC with the session key, as PROTOCOL.md 6.3 says (DomiStream already holds the
cipher; the host needs the encrypt side).
### 1.6 Input injection
Everything a client sends arrives as INPUT_DATA on the control channel (PROTOCOL.md section 4). DomiStream already
parses it (`input::parse_input`); lumen-host maps each event to a Windows call.
| Event | Windows call | Notes |
| :-- | :-- | :-- |
| Mouse relative move | `SendInput`, `MOUSEEVENTF_MOVE` | what games read (raw input). Windows applies the pointer-speed settings to relative moves on the desktop; games reading raw input get the raw delta |
| Mouse absolute move | `SendInput`, `MOUSEEVENTF_ABSOLUTE \| MOUSEEVENTF_VIRTUALDESK` | the client's position (in the stream's picture) is mapped to the streamed monitor's rectangle inside the virtual desktop, then to 0..65535. The mapping is a pure function with tests (letterboxing, scaling, monitors at negative coordinates) |
| Buttons, wheel, horizontal wheel | `SendInput` | wheel in multiples of 120, high-resolution deltas passed through |
| Keyboard | `SendInput` with **scan codes** (`KEYEVENTF_SCANCODE`) | many games read scan codes, not virtual keys. A pure table maps GameStream key codes (PROTOCOL.md 4, Wolf's key table) to scan codes. Text (UTF8_TEXT) goes as `KEYEVENTF_UNICODE` |
| Gamepad | **ViGEmBus** (Mark: "ViGEmBus for now"), through the MIT-licensed ViGEmClient library or a binding of it (licence logged) | one virtual Xbox 360 or DualShock 4 pad per client pad (CONTROLLER_ARRIVAL decides the type), rumble back to the client as RUMBLE_DATA. If ViGEmBus is not installed, pads are refused with a plain message, nothing else breaks. Our own virtual gamepad driver replaces it later (open point 13 of the roadmap) |
| Touch, pen (later) | `InjectSyntheticPointerInput` (Windows 10 1809+) | only when a client sends real touch (TOUCH/PEN layouts are U21); not needed for touch-to-mouse below |
**Touch-to-mouse, designed deliberately.** The 2026-12-04 evidence: the phone sent only *relative* mouse moves and
left-button press/release, never an absolute position. So a tap could not click where the finger was. The mapping
we want on every touch client:
| Gesture on the phone | What the PC gets |
| :-- | :-- |
| finger down and up without moving (tap) | absolute move to that point, left press, left release |
| long press (finger still for 500 ms; the threshold is tuned by tests) | absolute move to that point, right press, right release; the client vibrates once |
| one-finger drag after the finger moved | absolute moves while the finger moves, left held from the start (drag and drop) |
| two-finger drag | wheel (vertical) and horizontal wheel, in proportion to the distance, no button |
| two-finger tap | right click at the midpoint (desktop habit; optional) |
The gesture recogniser is **client-side** and pure, so it lives in DomiStream (`input::touch`, new) and every Arena
client uses the same code. It turns timed touch points into GameStream events (MOUSE_MOVE_ABS with the stream's
reference size, buttons, scroll); lumen-host only maps absolute positions correctly. For **Arena Domi Remote**,
which is a GPL app no Lumen worker may read, the same behaviour is handed over as a **written specification with
test cases** (gesture in, packets out), never as code, and its own workers implement it there. The input e2e
(7.3) checks the result against the PC, whatever client produced it.
**Integrity levels (UIPI).** `SendInput` reaches only windows of equal or lower integrity, and the failure is
silent. lumen-host runs at medium integrity, so:
- a game or launcher that runs **as administrator** gets no input from Lumen. lumen-host checks the foreground
window's process integrity when input starts failing to land and tells the client "This game runs as
administrator, so Arena Domi can't control it", once per session;
- the **secure desktop** (UAC prompts, lock screen) gets no input (and no capture, 1.2);
- `uiAccess` in the manifest would lift the first limit only for a signed program installed under Program Files,
and Microsoft reserves it for assistive technology. The plan does not use it (D6, accepted).
### 1.7 Sessions and launching games
Sunshine needs an app list written through its API and a hook program (`prep-cmd`) to learn when a game starts.
Lumen does not:
- **App list** = Arena Domi's visible library, read directly (the same mapping Play remotely uses today: Steam and
Epic by their launcher links, GOG and manual games by their `.exe` and folder; web games skipped). The ids clients
see are stable per game. Covers come from Arena Domi's own cover source, as today.
- **Desktop** is not in the list by default. It becomes a per-device choice ("Allow this device to see the whole
desktop"), off for TVs; phones use it with touch-to-mouse.
- **Launch**: lumen-host starts the game through the same launch path the Arena Domi window uses, watches for its
process and window (to pick the monitor, 1.2), turns game mode on, records "Play remotely started: <game> on
<device>" in the audit log, and starts the streams.
- **Quit game**: lumen-host asks the game to close (closes its main window), waits up to 10 seconds, and if it is
still running leaves it running and tells the client "The game is still open on the PC". It never kills a game
(unsaved progress). Ending the session turns game mode off and records "Play remotely ended".
- **Client gone without Quit** (TV switched off): the control channel times out (PROTOCOL.md 3.3: periodic pings),
the stream stops at once, the game keeps running, and the session ends after a grace period so the device can
come back (`resume`).
### 1.8 Network
- **GameStream first**, unchanged on the wire, so that clients that speak GameStream work without changes: our own
`gs-probe`, Arena Domi Remote, and Arena Domi TV (built on DomiStream). lumen-host speaks HTTP and HTTPS
(serverinfo, pairing, applist, launch, resume, cancel), RTSP (OPTIONS, DESCRIBE, SETUP, ANNOUNCE, PLAY), the ENet
control channel with AES-GCM, RTP video with Reed-Solomon FEC, and RTP Opus audio with AES-CBC.
- **Binding**: lumen-host binds every listening socket itself, to exactly the addresses Play remotely allows (the
Via Domi interface, loopback, and the home network only where Mark's decisions say so). Unlike Sunshine, Lumen can
bind several addresses at once, so the loopback/VPN forwarder planned for Sunshine is not needed for Lumen.
- **Beside Sunshine**: while both are installed, Lumen uses its own port base (Sunshine's default ports + 1000:
HTTP 48989, HTTPS 48984, RTSP 49010, video 48998, control 48999, audio 49000), so the two never collide.
A GameStream client learns the HTTPS port from serverinfo, the RTSP address from the launch answer and the stream
ports from RTSP (PROTOCOL.md sections 0, 1.2, 1.4; U4 and U5 say what is still to confirm), so a client only needs
"this PC on port 48989". Whether Arena Domi Remote accepts a host with a port is checked
black-box in L1 (risk R10). When Sunshine is gone, Lumen can take the standard ports.
- **Then Lumen's own transport** (roadmap Day 4, a separate plan): frame-aware packets, adaptive FEC, slice pacing,
an input lane and congestion control inside the Via Domi tunnel, chosen by Arena clients through a capability
flag, with GameStream as the fallback. Nothing in this plan's milestones depends on it.
### 1.9 Pairing: Tessera grants, no PIN for Arena clients
GameStream pairing proves, with a 4-digit PIN, that a client certificate belongs to someone the owner trusts. Arena
Domi already decides trust another way: every device holds its own key, and the PC's owner grants it Play remotely
with one click (no PIN, no code, Mark's decision). With Lumen, the host side of pairing is ours, so:
- **Arena clients (Arena Domi TV, our Windows and Android clients)**: the device's grant decides. The device sends
its signed pair request to Arena Domi as today; when the grant holds, lumen-host completes the GameStream pairing
for that device's client certificate itself, without a PIN anywhere (no PIN generated by the client to forward,
no submission to another program). A device that already holds a grant from the Sunshine days is accepted by
Lumen without asking the owner again.
- **Arena Domi Remote (today)**: it pairs the GameStream way. The owner types the 4 digits the phone shows into
Arena Domi's "Enter the code from your phone" box, exactly as with Sunshine today; lumen-host holds the pending
pairing and the box supplies its PIN. The same box, the same click count. Whether Arena Domi Remote should learn
the grant-based pairing instead was decided against (D5): it keeps the code box.
- **The host's identity**: the GameStream host certificate and its RSA key are made by lumen-host on first run and
the key is kept in Custos, never in a file. The PC's Play remotely signing key (Tessera) stays what it is.
- **Pairing state** (paired client certificates, which device they belong to) is public data on disk, each record
signed by the host key; an edited record fails its signature and is dropped.
- Clients paired with Sunshine are **not** imported into Lumen (that would mean reading Sunshine's state and
copying its identity). Each client pairs with Lumen once; for Arena clients that is invisible (the grant carries
over), for Arena Domi Remote it is one typed code.
---
## 2. Migration: Lumen beside Sunshine, then instead of it
| Stage | What changes | Who sees it |
| :-- | :-- | :-- |
| A. Beside | lumen-host runs on its own ports (1.8) next to Sunshine, turned on by a hidden developer switch. Only test clients use it | nobody |
| B. Per client | Arena Domi keeps an **engine per device** (`sunshine` or `lumen`). Arena Domi TV learns its engine and port from the "Find my PC" answer, so it switches with no action. Arena Domi Remote gets Lumen as a second entry for the same PC (or by its own update) | the owner, in Settings → Play remotely → Devices ("Streams with: Lumen") |
| C. Switch | a client moves to Lumen when Lumen passes **the same end-to-end suite** for that client as Sunshine does (7.6) and the harness shows Lumen's median and p95 at least as good (the roadmap's Day 3 gate). Order: gs-probe and the Windows client, then Arena Domi Remote, then Arena Domi TV | each switch is reported to Mark with its evidence |
| D. Default | Lumen is the default engine for every client. Sunshine is a hidden fallback under "Show expert options" (roadmap J4): still installed, used only for a device set to it | "Sunshine" appears only under expert options |
| E. Removal | when Mark says so, Arena Domi removes the Sunshine **it installed** with the existing single elevated step (it also removes the firewall rules named for Sunshine), and Lumen moves to the standard ports. A Sunshine that was on the PC before Arena Domi is left alone, as today | one UAC prompt, at Mark's request |
- **Fallback while both exist**: if lumen-host fails to start a session, Arena clients may retry on Sunshine
automatically (stages B to D), and the failure is reported, never hidden.
- **Uninstalling Arena Domi** removes lumen-host, its firewall rules (in the same single elevated step that removes
the others), its pairing records and its host key in Custos. Nothing of Lumen survives an uninstall.
- **Turning Play remotely off** stops lumen-host; the firewall rules stay until uninstall (Mark's rule for
Sunshine's rules, applied to Lumen's).
---
## 3. What lives where
### 3.1 DomiStream (this repo, public, sans-I/O)
**Reused as it is** (already written and tested for the client): the pairing crypto (AES, SHA-256, RSA signatures,
certificate parsing and our DER writer), session keys, Reed-Solomon (`fec::ReedSolomon::encode` exists), RTP and
the video/audio packet headers, the control frame cipher and message codec, `input::parse_input` and the gamepad
messages, the RTSP request parser and framer, the SDP parser, the HTTP XML reader, the ENet wire structs, the clock
and randomness seams.
**Added** (each with tests written first, a fuzz target for each parser, and the mutation pass):
| Module (proposed) | What |
| :-- | :-- |
| `host::pairing` | the host's pairing state machine: the phases of PROTOCOL.md 1.5 from the other side (server challenge, checks of the client's hashes and signature, host signature), a pending-PIN slot fed by the caller |
| `host::http` | request-line and query parsing (strict, capped), and the XML answers: serverinfo, applist, launch/resume/cancel, pair, errors |
| `rtsp::server` | the host's RTSP session: request order, CSeq, SETUP ports, the DESCRIBE answer (SDP writer), a strict ANNOUNCE parser into a typed stream configuration |
| `enet::host` | the accepting side of ENet: connect, verify connect, reliable channel, ping and timeouts |
| `control::host` | the host side of the control channel: client-to-host decryption, host-to-client messages (rumble, HDR mode once measured, termination) |
| `video::packetizer` | an encoded frame → RTP + NV-header packets, FEC blocks with parity, optional encryption |
| `audio::packetizer` | Opus packets → RTP, AES-CBC, parity once U16 is settled |
| `input::touch` | the client-side gesture recogniser of 1.6 (pure, timed points in, events out) |
| `input::keymap` | GameStream key codes ↔ scan codes, as a pure table both sides can use |
| `pacing`, `harness` | the frame pacer's maths and the harness statistics (median, p95, clock offset) |
The client and host halves are tested **against each other in memory**: a DomiStream client and a DomiStream host
run a whole session in one test (pairing, RTSP, control, video with loss and FEC recovery, audio), with no socket.
That catches every asymmetric mistake before a real client is involved. The release that adds the host side is
`stream-v0.2.0`.
### 3.2 Arena Domi (private)
- **lumen-host's I/O**: sockets and TLS (rustls, server side, client certificates checked against the paired list),
capture, the colour pass, NVENC, WASAPI and Opus, input injection and ViGEmBus, launching and watching games,
pacing threads. Proposed home: inside `crates/arena-host` (the Play remotely crate), with `lumen-host.exe` as a
new binary of that crate. Each Windows API sits behind a trait (`Capturer`, `Encoder`, `AudioSource`, `Injector`,
`Pads`, `Launcher`) with a fake, so the logic is tested without a GPU or a desktop.
- **arena-host** keeps the pairing gate, grants, devices, the engine per device, the code box, audit records and
turning Lumen on and off.
- **Capture and encode** could instead live in DomiCapture (public, CPAL-1.0), which the roadmap names for the
zero-copy encode path and which Pictor Domi will share. That crate has no code yet and belongs to the Arena build
lead's plan; D3: capture/encode start in arena-host and move to DomiCapture at L4.
- What touches files outside Play remotely's agreed folders (installer, tray agent, shared seams) goes through the
Arena build lead, one small PR each, as agreed on 2026-11-25.
---
## 4. Risks, and how each is retired early
| # | Risk | Retired by | When |
| :-- | :-- | :-- | :-- |
| R1 | **Clean room.** The host side of GameStream is best documented in GPL code, and GPL-provenance values sit in permissive sources (the audio parity matrix, the HDR message layout) | Sources limited to section 0's list; Moonshine read as a host for facts only; GPL-provenance values never used until measured (6.2); every PR adds its source rows; the GPL Remote app's workers and Lumen's workers never share a workspace, code or review; each PR body carries a clean-room checklist (sources read, none forbidden, provenance of every constant) | every PR, from L0 |
| R2 | **Interop with real clients**: a host must accept exactly what clients send (U5, U6, U9, U10 from the host side) | the in-memory client↔host test (L1); Sunshine as a black-box oracle (our gs-probe's byte logs of what Sunshine sends); then the first real client (Arena Domi Remote in the Android emulator, black-box) against lumen-host's listeners at the end of L1, before any video work depends on it | L1 |
| R3 | **Audio FEC matrix (U16)** is GPL-provenance | send audio without parity and verify clients play it; solve the matrix from Sunshine's captured parity (our measurement) | L2, L6 |
| R4 | **Colours differ between phone and PC** (range, transfer, HDR) | SDR BT.709 limited by default with correct VUI; test patterns decoded on the client and compared (7.5); HDR only after the HDR message is measured | L4 |
| R5 | **Input that cannot land**: elevated games, the secure desktop (UIPI) | detect and tell the client; accepted as the price of "no admin rights" (D6) | L3 |
| R6 | **Firewall rules need admin**; inbound connections on a public-profile network are blocked without them | decision D1 before L5; until then the emulator connects over loopback, which needs no rule | L5 |
| R7 | **ViGEmBus** is a third-party driver that its authors no longer develop | used only if Mark installed it; pads are refused cleanly without it; our own driver later (roadmap open point 13) | L3 |
| R8 | **Anti-cheat** may dislike desktop capture, synthetic input or virtual pads | Lumen never touches the game process; a short list of games is tested before the switch (C) and any that refuse are listed in the client ("Streaming isn't allowed by this game") | L6 |
| R9 | **Cost to the game** (GPU time of the colour pass, NVENC sessions, CPU) | the harness reports the game's frame rate with and without streaming; target under 3 % loss, measured | L2, L6 |
| R10 | **A client that cannot use a non-standard port** | checked black-box in L1 (Arena Domi Remote with port 48989); if it fails, the fork's workers get a written requirement, or Lumen waits for stage E for that client | L1 |
| R11 | **Desktop Duplication limits**: at most four duplicating processes; Arena's own overlay capture, Sunshine and Lumen all duplicate | one Lumen session at a time; lumen-host releases its duplication when idle; the error (`DXGI_ERROR_NOT_CURRENTLY_AVAILABLE`) is reported in plain words | L2 |
| R12 | **Licences of the native pieces** (NVENC header, libopus, ViGEmClient, their Rust bindings) | each read and logged before it is added; only MIT, BSD, Apache, ISC, zlib or CPAL; NVIDIA's DLL is the driver's, never shipped | L0 |
| R13 | **Codec patents** if Arena Domi is sold (roadmap open point 9) | the encoder is the user's GPU's hardware; flagged to Mark, not decided here | before sale |
| R14 | **Estimates**: GameStream host work has unknowns we cannot see before real clients connect | milestones end in demos, each small; the plan is re-estimated after L1 with real numbers | L1 |
---
## 5. Milestones
Estimates are working days of one engineer (with QA writing tests first, as DomiStream did), on this PC, gated by
the load rule. Each milestone ends in a demo Mark can see. Total: **about 18 days, 22 to 23 with a 25 % margin**.
| # | Milestone | Content | Days | Demo for Mark |
| :-- | :-- | :-- | :-- | :-- |
| L0 | Spikes | Read and log the NVENC programming guide and header licence, libopus and ViGEmClient licences. A throwaway Rust spike, run only with Mark present: duplicate the HDR desktop in FP16, convert to NV12 and P010 on the GPU, encode 10 s of HEVC with NVENC, write the file; time each step | 1 | a 10 s HEVC file of a test pattern window (SDR and HDR) and a table: capture, convert and encode time per frame |
| L1 | Host protocol + first contact | DomiStream host side of section 3.1 (pairing, HTTP, RTSP server, ANNOUNCE, ENet host, control host, both packetizers), the in-memory client↔host session test, fuzz targets. A lumen-host skeleton (listeners on loopback only, no capture) that Arena Domi Remote in the Android emulator can find, pair with (code box) and list games from | 4 | the emulator on this PC pairs with Lumen and shows Arena Domi's game list; test and fuzz report |
| L2 | First stream | Capture (SDR path, and FP16 → SDR), NVENC HEVC/H.264 low latency, pacing, WASAPI + Opus (no audio parity), keyboard and relative mouse, launch from the library, quit, game mode and audit; beside Sunshine on its own ports | 4 | a game streams from Lumen to the emulator, with sound and keyboard/mouse, while Sunshine is still installed |
| L3 | Input, all of it | absolute mouse mapping, wheel, scan-code keyboard, text, ViGEmBus pads with rumble, the touch-to-mouse spec and `input::touch`, UIPI detection; the input e2e (7.3) running green | 2 | a scripted tap, long press and two-finger scroll land at the right places in the Arena input probe; e2e report |
| L4 | Colour and displays | capture/encode move from arena-host to DomiCapture (D3); range/colour-space negotiation from measurement, HDR → SDR tone mapping checked, monitor choice and switching, GPU scaling; HDR to HDR clients only if the HDR message has been measured | 2 | test pattern on the PC and on the phone side by side, with the measured colour differences |
| L5 | Pairing and per-device engine | Tessera-grant pairing with no PIN for Arena clients, the code box for Arena Domi Remote, the engine per device, Lumen's binding on the allowed addresses, firewall rules (after D1), the installer seam | 2 | gs-probe pairs with Lumen with no PIN; the phone pairs with a code; Settings shows "Streams with: Lumen" |
| L6 | Harness and the Day 3 gate | the same-PC latency harness (7.4), Lumen against Sunshine, tuning (pacing, VBV, slices, priorities), the game's frame-rate cost, a 2-hour soak, audio parity once U16 is solved | 2 | the harness table: median and p95 for Lumen and Sunshine, and the gate answer |
| L7 | Switch-over | stage C for each client that passes, Sunshine as the hidden fallback (stage D), uninstall path checked | 1 | Arena Domi Remote and the Windows client streaming from Lumen by default; Sunshine only under expert options |
Not in these estimates: Arena Domi TV itself (it switches when it exists, because it is built on DomiStream),
Lumen's own transport (roadmap Day 4), AMF/Quick Sync, 4:4:4, a virtual display per client, and the iOS client
(5.2).
### 5.1 The first build phase (accepted: Mark's go, 2026-12-04)
**L0 + L1**: the spikes (to retire the GPU and licence risks while they are cheap) and the DomiStream host side
with the in-memory session test, ending with Arena Domi Remote in the emulator pairing with a Lumen skeleton over
loopback. Nothing touches Sunshine, the owner's desktop, mouse or windows, except the one L0 spike run with Mark
present. About 5 days.
### 5.2 Later client phase: iOS
Every Domi app eventually runs on Windows, Android and iOS (Mark, 2026-12-04). Lumen's host does not change for
iOS: an iOS client speaks GameStream (later Lumen's own transport) to the same lumen-host. The iOS client is its own
phase after the switch-over (L7): DomiStream compiles for `aarch64-apple-ios` (it is pure Rust with no I/O, so the
check is a build and the test suite on that target), VideoToolbox decodes, the same `input::touch` recogniser maps
gestures, and the client pairs through a Tessera grant like Arena's other clients, with no PIN. It is planned and
estimated when phase L7 is done; no Moonlight iOS code is read for it (the clean room covers every client).
---
## 6. Sources and measurements for the host side
### 6.1 What may be read
- Everything already allowed in [CLEAN_ROOM.md](CLEAN_ROOM.md), with one point made explicit: **Moonshine is a
host**, so its host-side code (BSD-2) is the most useful permissive reference for Lumen's state machines; it is
read for facts, logged, and never copied.
- Public OS and SDK documentation: Microsoft Learn (DXGI, Windows.Graphics.Capture, Core Audio, input, display
configuration), NVIDIA's Video Codec SDK documentation and API header, AMD AMF and Intel oneVPL documentation, the
libopus documentation, the ViGEm documentation, the Opus and RTP RFCs, ITU-R BT.709 / BT.2020 / BT.2100 and SMPTE
ST 2084.
- **Forbidden for host work** (D2, Mark 2026-12-04): the source of OBS Studio (GPL-2.0) and of FFmpeg (LGPL/GPL)
is not read either, because both contain encoder and capture code that would be tempting to port.
### 6.2 Measurements we make ourselves
- **Sunshine as a black-box oracle.** Our own `gs-probe` (a GameStream client) connects to the pinned Sunshine and
logs what it sends, as allowed today ([LIVE-INTEROP.md](LIVE-INTEROP.md)): headers, packet layouts, FEC parity
(to solve the audio matrix, U16), the HDR message bytes with HDR on (its layout), timings.
- **Clients as black boxes** (D2, accepted). Arena Domi Remote (in the Android emulator) and the official
Moonlight PC app connect to lumen-host, and lumen-host logs what they send: ANNOUNCE values per client setting
(range, codec, HDR), input packets per gesture, ENet details. We run the binaries and read our own logs; we never
open their source, disassemble or decompile them.
- Every fact found this way goes into PROTOCOL.md with a measurement tag, the date and the setup.
---
## 7. Test strategy
### 7.1 Tests first
- **DomiStream**: tests before code for every new parser and state machine (host pairing, HTTP requests, RTSP
server, ANNOUNCE, ENet host, control host), the packetizers and the gesture recogniser. Vectors come from
independent tools (OpenSSL, Python) and from the client half (round trips); property tests: packetize →
lose up to the parity count → depacketize gives the same frame; any gesture sequence gives balanced button
presses. Mutation pass as in [MUTATION.md](MUTATION.md).
- **Fuzzing**: one libFuzzer target per new parser (HTTP request and query, RTSP request, ANNOUNCE/SDP, ENet host
datagram, control client-to-host frame, INPUT_DATA already exists), 60 s each per release and a long run for the
pairing and ENet host targets, 0 crashes required.
- **arena-host / lumen-host**: the pure parts (coordinate mapping, key map, colour matrices and the tone curve,
engine choice, app list, quit logic) are unit-tested; the I/O sits behind traits with fakes, so a whole session
(control in, injector calls out) runs in a test without a desktop.
### 7.2 GPU tests
Capture → convert → encode → decode on the reference GPU with known patterns (colour bars, grey ramps, a PQ ramp),
compared numerically (PSNR and colour difference thresholds). They need the real GPU and desktop, so they are
`#[ignore]` by default and run only under the load rule, and only with Mark's agreement when they capture his
display.
### 7.3 The input e2e, from L2 on
The **Arena input probe** (our own tool: a window that logs every mouse, key, touch and pointer event with its
coordinates) is shown on the streamed display; a client streams it and sends scripted input; the probe's log is the
assertion.
| Step | Client | Expected in the probe log |
| :-- | :-- | :-- |
| tap at stream point (x, y) | emulator (adb tap) and gs-probe | left down and up at the mapped PC point, within 2 px |
| long press 800 ms | emulator (adb swipe from a point to itself) | right down and up at that point, no left click |
| two-finger drag up | emulator (an instrumentation test APK of our own that injects a two-pointer gesture) | wheel events with the right sign and no buttons |
| one-finger drag | emulator | left down, moves along the path, left up |
| typed text and key combos | gs-probe | the same characters and scan codes, in order |
| pad buttons and sticks | gs-probe | the virtual pad's state (the probe reads XInput) |
- **Two tiers.** The *hermetic* tier replaces `SendInput` with a recording fake and checks the calls; it runs in
every test run. The *live* tier injects for real, so it moves the PC's pointer: it runs only in a sitting agreed
with Mark (or in a Windows Sandbox or virtual machine, where the software encoder stands in for NVENC).
- The emulator connects over loopback, so no firewall rule and no network outside the PC are involved.
- Against Arena Domi Remote the gesture rows will fail until its workers implement the touch spec (1.6); the e2e is
how that is checked, and it is reported as a client gap, not hidden.
### 7.4 Latency harness, from L2 on
- **Same PC, one clock**: the client (gs-probe with hardware decode, later the emulator) sends a click at t0; the
probe flips a large patch from black to white on that click; the client timestamps the first decoded frame that
shows white (t1). t1 − t0 is the input-to-decoded latency, without the client's display. 200 samples per run,
alternating Lumen and Sunshine runs, median and p95 reported.
- **Inside lumen-host**: each frame carries timestamps for capture, convert done, encode done and last packet sent,
logged to a local trace, so a regression points at its stage.
- **Cost to the game**: the game's frame rate with and without a stream (Arena Domi's own frametime statistics).
- **Away from home** (Via Domi) needs two clocks: the harness maths in DomiStream estimates the offset; that is the
roadmap's Day 2/4 harness and is reused when it exists.
### 7.5 Colour tests
A colour-pattern window (bars, ramps, near-black steps, an SDR-white patch) is streamed; the client saves a decoded
frame; the PC saves the captured frame; both are converted to the same space and compared patch by patch. This
settles the range and colour-space values (1.3) per client.
### 7.6 The switch-over suite (one per client)
Pair → list games → launch → 60 s of video and audio → input e2e → quit → reconnect after a dropped connection →
pair removal refuses the client → a 2-hour soak without memory or handle growth. A client moves to Lumen (stage C)
when this suite passes on Lumen as it does on Sunshine, and the harness says Lumen is at least as fast.
---
## 8. Decisions (Mark, 2026-12-04: all six accepted as proposed)
| # | Question | Decision |
| :-- | :-- | :-- |
| D1 | Lumen needs Windows firewall rules for `lumen-host.exe` on its ports, which needs admin | **Yes**: the existing single UAC step at "Turn on Play remotely" also creates Lumen's rules (scoped to `lumen-host.exe`, its ports and the allowed addresses). No new prompt. They stay until uninstall, like Sunshine's |
| D2 | Black-box logging of what clients send to Lumen; OBS Studio and FFmpeg sources | **Yes**: lumen-host may log what Arena Domi Remote and the official Moonlight PC app send to it (run and observe only, never source, disassembly or decompiling). **OBS Studio and FFmpeg source are forbidden for host work** ([CLEAN_ROOM.md](CLEAN_ROOM.md)) |
| D3 | Where capture and encode live | **arena-host first**, behind traits; they **move to DomiCapture at L4** |
| D4 | Who starts lumen-host at sign-in | **The tray agent**, once Lumen is the default engine (stage D). Before that, Arena Domi starts it when Play remotely uses Lumen |
| D5 | Arena Domi Remote: the code box or a no-PIN spec | **Keep the code box.** No grant-based pairing spec is published into the GPL app |
| D6 | Games running as administrator | **Accepted**: they get no input from Lumen, and the client shows a clear message ("This game runs as administrator, so Arena Domi can't control it") |
---
## 9. Sources used for this plan
Logged as S-22 in [CLEAN_ROOM.md](CLEAN_ROOM.md): Microsoft Learn pages on DXGI 1.5 and `DuplicateOutput1`,
Desktop Duplication, HDR and advanced colour, `GraphicsCaptureSession` (`IsBorderRequired`,
`IsCursorCaptureEnabled`), `SendInput` and `MOUSEINPUT`, the UIAccess security considerations and the UAC policy
for UIAccess, `CreateSyntheticPointerDevice` / `InjectSyntheticPointerInput`, and WASAPI loopback recording with
process loopback activation. Everything else here comes from this repository's own documents and the 2026-12-04
live evidence (the phone's input packets).
---
## 10. L0 results (2026-12-04)
**Done:** the licence reading and the GPU spike. The spike is a throwaway Rust program with a small C shim over the
NVENC header, kept outside git. It showed no window, injected nothing and opened no socket. The desktop bitstreams
never left memory (nothing of the screen was written to disk); only two synthetic-pattern encodes were written, and
they stay outside git.
**Licences** (logged as S-23 to S-25 in [CLEAN_ROOM.md](CLEAN_ROOM.md)):
| Piece | Licence | Note |
| :-- | :-- | :-- |
| `nvEncodeAPI.h`, API **12.0**, from NVIDIA's own public repository (VideoProcessingFramework, Apache-2.0 repository, archived) | MIT (the header's own notice) | used. No account and no licence acceptance needed |
| `nvEncodeAPI.h`, API 8.1, NVIDIA's video-sdk-samples | MIT | **not usable**: the driver refuses its presets (below) |
| NVENC API 12.1 or newer headers | NVIDIA's SDK download (account and terms) | not needed for anything planned; if a later feature needs it, that download is Mark's decision |
| libopus | BSD-3-Clause style (Xiph COPYING) | for L2 |
| `opus` crate / `audiopus_sys` | Apache-2.0 or MIT / ISC | candidates for L2, chosen then |
| ViGEmClient | MIT (repository archived) | the client library for ViGEmBus |
| ViGEmBus | BSD-3-Clause (repository archived) | Mark installs it himself; never shipped |
| `vigem-client` crate | MIT | candidate binding for L3 |
| `windows` crate | MIT or Apache-2.0 | used by the spike |
**Measured on the reference PC** (RTX 3090, driver NVENC API maximum 13.1; primary 2560x1440 HDR; one run,
idle desktop):
| What | Result |
| :-- | :-- |
| Display state | both outputs report colour space `RGB_FULL_G2084_NONE_P2020` (HDR on); primary 10 bits per colour; peak 1499 nits, full frame 799; SDR white level 240 nits |
| Desktop Duplication | the HDR desktop arrives as `R16G16B16A16_FLOAT` (FP16 scRGB), as planned. **Needs per-monitor DPI awareness**: without it `DuplicateOutput1` returned `DXGI_ERROR_UNSUPPORTED` and the 4K output showed as 2560x1440 |
| NVENC with the API 8.1 header | `nvEncGetEncodePresetConfig` refuses the legacy low-latency preset (`NV_ENC_ERR_UNSUPPORTED_PARAM`) and initialisation without a preset fails (`NV_ENC_ERR_INVALID_PARAM`) |
| NVENC with the API 12.0 header | preset P1, tuning "ultra low latency", CBR 20 Mbit/s, VBV one frame, infinite GOP: works, 8-bit and 10-bit HEVC; the first access unit is VPS, SPS, PPS, IDR |
| Copy of the captured frame (GPU, waited) | 1.6 ms (one sample: the desktop was idle, so only one new frame arrived) |
| Colour pass FP16 → NV12 / P010, 2560x1440 (one compute dispatch, waited) | median 0.57 / 0.50 ms, p95 1.01 / 0.93 ms |
| NVENC HEVC 2560x1440, synchronous | 8-bit median 2.56 ms, p95 2.70 ms; 10-bit median 2.56 ms, p95 2.80 ms |
| NVENC HEVC 1920x1080 (pattern) | median 1.4 to 1.5 ms, p95 1.7 to 2.5 ms |
| Capture to bitstream, sum of medians, 1440p | about **4.7 ms** on the host |
What L0 did not settle (and where it is settled): capture timing under motion and at a game's frame rate (L2,
with the harness); whether the colour pass matches what a decoder shows (L4, the pattern files are the start);
the asynchronous NVENC mode, which NVIDIA recommends on Windows (L2).
+12 -7
View File
@@ -298,13 +298,13 @@ Every control message is wrapped [W4] (little-endian):
| Type | Name | Direction | Body | | Type | Name | Direction | Body |
| :-- | :-- | :-- | :-- | | :-- | :-- | :-- | :-- |
| 0x0305 | START_A | client → host | UNKNOWN U10 | | 0x0305 | START_A | client → host | UNKNOWN U10. Moonshine has no such type; inside the encrypted frame it skips an unknown type [M] |
| 0x0307 | START_B | client → host | UNKNOWN U10. The host starts video and audio when it arrives [M] | | 0x0307 | START_B | client → host | Moonshine reads no body [M]. The host starts video and audio when it arrives [M]; Moonshine's video receiver (and so its PING handling) only runs from then on [M] |
| 0x0200 | PERIODIC_PING | client → host | UNKNOWN U10. Keeps the session alive; the host stops after a timeout without one [M] | | 0x0200 | PERIODIC_PING | client → host | Moonshine reads no body [M]. Each one pushes the host's stop deadline out; Moonshine stops a stream after 60 s without one (its default) [M] |
| 0x0201 | LOSS_STATS | client → host | UNKNOWN U10 | | 0x0201 | LOSS_STATS | client → host | Moonshine ignores it [M]; body UNKNOWN U10 |
| 0x0204 | FRAME_STATS | client → host | UNKNOWN U10 | | 0x0204 | FRAME_STATS | client → host | Moonshine ignores it [M]; body UNKNOWN U10 |
| 0x0206 | INPUT_DATA | client → host | section 4 | | 0x0206 | INPUT_DATA | client → host | section 4 |
| 0x0302 | IDR_FRAME (request) | client → host | UNKNOWN U10 (Moonshine ignores the body) | | 0x0302 | IDR_FRAME (request) | client → host | Moonshine reads no body [M] |
| 0x0301 | INVALIDATE_REF_FRAMES | client → host | `first u32`, `reserved u32`, `last u32`, `reserved 12 bytes`, LE [M] | | 0x0301 | INVALIDATE_REF_FRAMES | client → host | `first u32`, `reserved u32`, `last u32`, `reserved 12 bytes`, LE [M] |
| 0x0100 | TERMINATION | host → client | UNKNOWN U10 | | 0x0100 | TERMINATION | host → client | UNKNOWN U10 |
| 0x0109 | TERMINATION (extended) | host → client | `error_code u32 BE`; `0x80030023` = graceful [M] | | 0x0109 | TERMINATION (extended) | host → client | `error_code u32 BE`; `0x80030023` = graceful [M] |
@@ -317,6 +317,11 @@ Every control message is wrapped [W4] (little-endian):
UNKNOWN U23: Wolf states "all data is little-endian" for the frame; we assume LE for the host event bodies too. UNKNOWN U23: Wolf states "all data is little-endian" for the frame; we assume LE for the host event bodies too.
How Moonshine treats what a client sends on control [M]: a message whose type it does not know, or whose length field
does not match, **ends the session** when it arrives outside the encrypted frame; inside the encrypted frame the same
message is skipped, and so is a frame that fails decryption. Whether Sunshine reads bodies (and which) is what U10
still settles live: the probe sends empty bodies first ([LIVE-INTEROP.md](LIVE-INTEROP.md), table V).
--- ---
## 4. Input and gamepad packets ## 4. Input and gamepad packets
@@ -569,7 +574,7 @@ client and Sunshine on a lab machine, not Mark's PC, his Sunshine or his TV); th
| U7 | Extra headers in SETUP replies | B | capture | | U7 | Extra headers in SETUP replies | B | capture |
| U8 | UDP ping payload and repeat interval | B | capture | | U8 | UDP ping payload and repeat interval | B | capture |
| U9 | Narrowed (3.1): only what Sunshine's ENet may add when *sending*; the client's channel count, MTU, connect data | B | capture, decode with our parser | | U9 | Narrowed (3.1): only what Sunshine's ENet may add when *sending*; the client's channel count, MTU, connect data | B | capture, decode with our parser |
| U10 | Bodies of START_A, START_B, PERIODIC_PING, LOSS_STATS, FRAME_STATS, IDR request, TERMINATION; ping interval | B | capture, decrypted with the session's `rikey` | | U10 | Narrowed (3.3): Moonshine reads no body from START_B, PERIODIC_PING or the IDR request and ignores START_A, LOSS_STATS and FRAME_STATS; what Sunshine reads, the ping interval it needs, TERMINATION's body | B | live sitting: empty bodies first, then the hex variants |
| U11 | First control sequence number; host's replay rules | | capture | | U11 | First control sequence number; host's replay rules | | capture |
| U13 | Video frame header: Wolf's constant or Moonshine's fields | | capture | | U13 | Video frame header: Wolf's constant or Moonshine's fields | | capture |
| U14 | Video RS matrix: **settled** (5.3, Cauchy from fec-rs) | | capture confirms: our parity = captured parity | | U14 | Video RS matrix: **settled** (5.3, Cauchy from fec-rs) | | capture confirms: our parity = captured parity |
+14
View File
@@ -211,3 +211,17 @@ path = "fuzz_targets/rtsp_client.rs"
test = false test = false
doc = false doc = false
bench = false bench = false
[[bin]]
name = "host_http_request"
path = "fuzz_targets/host_http_request.rs"
test = false
doc = false
bench = false
[[bin]]
name = "host_pairing"
path = "fuzz_targets/host_pairing.rs"
test = false
doc = false
bench = false
+67
View File
@@ -0,0 +1,67 @@
//! Fuzzes the host's HTTP request parsing: the head cutter, the head parser, the target parser and the query parser.
//! Asserts invariants, not only "no panic": a parsed head ends exactly where the cutter says, a parsed query
//! re-encodes to the same parameters, and every typed value of a parsed request is within its documented range.
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
#![no_main]
use libfuzzer_sys::fuzz_target;
use domistream::host::http::{
HostRequest, MAX_HEAD_BYTES, MAX_MODE_DIMENSION, MAX_MODE_FPS, MAX_PARAMS, Route, encode_query, find_head_end,
parse_query, parse_request_head, parse_target,
};
use domistream::host::pairing::PairPhase;
fn check(req: &HostRequest) {
assert!(req.other_params.len() <= MAX_PARAMS);
if let Some(u) = &req.unique_id {
assert!(!u.is_empty() && u.len() <= 64, "uniqueid {u:?}");
}
let mode_ok = |m: &domistream::host::http::DisplayMode| {
(1..=MAX_MODE_DIMENSION).contains(&m.width)
&& (1..=MAX_MODE_DIMENSION).contains(&m.height)
&& (1..=MAX_MODE_FPS).contains(&m.fps)
};
match &req.route {
Route::Launch(l) => assert!(mode_ok(&l.mode), "{:?}", l.mode),
Route::Resume(r) => assert!(r.mode.as_ref().is_none_or(mode_ok)),
Route::Pair(p) => {
assert_eq!(req.unique_id.as_deref(), Some(p.unique_id.as_str()), "/pair needs uniqueid");
match &p.phase {
PairPhase::GetServerCert { client_cert_pem, .. } => assert!(!client_cert_pem.is_empty()),
PairPhase::ClientChallenge(v)
| PairPhase::ServerChallengeResp(v)
| PairPhase::ClientPairingSecret(v) => {
assert!(!v.is_empty())
}
PairPhase::PairChallenge => {}
}
}
Route::Unknown { path } => assert!(path.starts_with('/') && path.len() <= 256),
_ => {}
}
}
fuzz_target!(|data: &[u8]| {
let cut = find_head_end(data);
if let Ok(Some(n)) = cut {
assert!((4..=MAX_HEAD_BYTES).contains(&n) && data[..n].ends_with(b"\r\n\r\n"));
}
if let Ok(req) = parse_request_head(data) {
assert_eq!(cut, Ok(Some(data.len())), "a parsed head ends where the cutter says");
check(&req);
}
let Ok(text) = core::str::from_utf8(data) else { return };
if let Ok(req) = parse_target(text) {
check(&req);
}
if let Ok(params) = parse_query(text) {
let list: Vec<(&str, &str)> = params.iter().map(|(k, v)| (k.as_str(), v.as_str())).collect();
match parse_query(&encode_query(&list)) {
Ok(again) => assert_eq!(again, params, "parse -> encode -> parse"),
// Encoding can triple a value (`+` becomes `%20`), so only a cap may refuse it.
Err(e) => assert!(matches!(e, domistream::Error::TooLarge { .. }), "{e:?}"),
}
}
});
+148
View File
@@ -0,0 +1,148 @@
//! Fuzzes the host's pairing state machine: a session fed arbitrary sequences of phases, PINs, timer wake-ups and
//! cancels, with arbitrary values, transports and client ids.
//! Asserts invariants, not only "no panic": a fuzzer that holds no client key never gets the session to Paired,
//! Failed is terminal, and the session has a deadline exactly while it is in progress.
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
#![no_main]
use core::time::Duration;
use libfuzzer_sys::fuzz_target;
use domistream::host::pairing::{
HostIdentity, HostPairingConfig, HostPairingSession, HostPairingState, HostPairingStep, PairPhase, PairRequest,
Transport,
};
use domistream::pairing::Pin;
use domistream::{Error, Instant, RandomSource};
const VECTORS: &str = include_str!("../../crates/domistream/tests/fixtures/pairing.txt");
/// The certificate phase 1 presents: a test-only certificate whose key the fuzzer does not have.
const CLIENT_CERT_PEM: &str = include_str!("../../crates/domistream/tests/fixtures/test-only-host-cert.pem");
fn value(name: &str) -> Vec<u8> {
let prefix = format!("{name} = ");
let line = VECTORS.lines().find(|l| l.starts_with(&prefix)).expect("fixture value");
let hex = &line[prefix.len()..];
(0..hex.len()).step_by(2).map(|i| u8::from_str_radix(&hex[i..i + 2], 16).expect("hex")).collect()
}
struct Fixed;
impl RandomSource for Fixed {
fn fill(&mut self, dest: &mut [u8]) {
dest.fill(0x5A);
}
}
/// Reads the fuzzer's bytes as a script.
struct Script<'a>(&'a [u8]);
impl Script<'_> {
fn byte(&mut self) -> Option<u8> {
let (&b, rest) = self.0.split_first()?;
self.0 = rest;
Some(b)
}
fn bytes(&mut self, n: usize) -> Vec<u8> {
let n = n.min(self.0.len());
let (head, rest) = self.0.split_at(n);
self.0 = rest;
head.to_vec()
}
}
fuzz_target!(|data: &[u8]| {
// Any RSA identity serves as the host's: the client fixture's.
let Ok(host) = HostIdentity::from_der(&value("client_cert_der"), &value("client_key_pkcs8_der")) else { return };
let host_cert_der = value("host_cert_der");
let mut s = HostPairingSession::new(&host, HostPairingConfig::default(), Instant::ZERO);
let mut now = Instant::ZERO;
let mut script = Script(data);
let mut steps = 0;
while let Some(op) = script.byte() {
steps += 1;
if steps > 24 {
break;
}
let before = s.state();
let flags = script.byte().unwrap_or(0);
now = now.saturating_add(Duration::from_millis(u64::from(flags & 0x0F) * 700));
let unique_id = if flags & 0x10 != 0 {
String::from_utf8_lossy(&script.bytes(usize::from(flags >> 5) * 3)).into_owned()
} else {
"0123456789ABCDEF".to_string()
};
let len = usize::from(script.byte().unwrap_or(0));
let phase = match op % 8 {
0 => {
let mut salt = [0u8; 16];
let raw = script.bytes(16);
salt[..raw.len()].copy_from_slice(&raw);
let client_cert_pem =
if len % 4 == 0 { script.bytes(len * 8) } else { CLIENT_CERT_PEM.as_bytes().to_vec() };
Some(PairPhase::GetServerCert { salt, client_cert_pem })
}
1 => Some(PairPhase::ClientChallenge(script.bytes(len % 40))),
2 => Some(PairPhase::ServerChallengeResp(script.bytes(len % 72))),
3 => Some(PairPhase::ClientPairingSecret(script.bytes(len * 2))),
4 => Some(PairPhase::PairChallenge),
5 => {
let digits = format!("{:04}", u16::from_le_bytes([len as u8, flags]) % 10_000);
if let Ok(pin) = Pin::from_digits(&digits) {
let r = s.supply_pin(&host, pin, now);
if r.is_ok() {
assert_eq!(before, HostPairingState::AwaitPin);
assert_eq!(s.state(), HostPairingState::AwaitClientChallenge);
}
}
None
}
6 => {
let late = now.saturating_add(Duration::from_secs(u64::from(flags)));
let fired = s.handle_timeout(late);
assert_eq!(
fired,
matches!(s.state(), HostPairingState::Failed(_)) && !matches!(before, HostPairingState::Failed(_))
);
None
}
_ => {
s.cancel();
None
}
};
if let Some(phase) = phase {
let device_name = (flags & 0x80 != 0).then(|| "fuzz".to_string());
let request = PairRequest { unique_id, device_name, phase };
let other_cert;
let transport = match len % 3 {
0 => Transport::Http,
1 => Transport::Https { client_cert_der: &host_cert_der },
_ => {
other_cert = script.bytes(len);
Transport::Https { client_cert_der: &other_cert }
}
};
let r = s.handle(&host, &request, transport, now, &mut Fixed);
assert!(!matches!(r, Ok(HostPairingStep::Paired(_))), "paired without the client's key");
if matches!(before, HostPairingState::Failed(_) | HostPairingState::Paired) {
assert!(matches!(r, Err(Error::State { .. })));
}
if r.is_err() {
assert!(matches!(s.state(), HostPairingState::Failed(_)), "an error ends the session: {r:?}");
}
}
assert_ne!(s.state(), HostPairingState::Paired, "paired without the client's key");
assert!(s.paired_client().is_none());
if let HostPairingState::Failed(_) = before {
assert_eq!(s.state(), before, "Failed is terminal");
}
assert_eq!(
s.poll_timeout().is_none(),
matches!(s.state(), HostPairingState::Failed(_)),
"a deadline while in progress"
);
}
});
+692
View File
@@ -0,0 +1,692 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "aead"
version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1973cfbc1a2daf9cf550e74e1f088c28e7f7d8c1e1418fb6c9dc5184b7e84c99"
dependencies = [
"crypto-common",
"inout",
]
[[package]]
name = "aes"
version = "0.9.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fc0fc36d7440d015b45468ba08a21e80e056ebbd014c611c6298bb7503e04bd1"
dependencies = [
"cipher",
"cpubits",
"cpufeatures",
]
[[package]]
name = "aes-gcm"
version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f2b8006a0c83f52b62ba44a97b58bf76fe2f70a329e588f67f89691d93d498f"
dependencies = [
"aead",
"aes",
"cipher",
"ctr",
"ctutils",
"ghash",
]
[[package]]
name = "autocfg"
version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
[[package]]
name = "base16ct"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fd307490d624467aa6f74b0eabb77633d1f758a7b25f12bceb0b22e08d9726f6"
[[package]]
name = "base64ct"
version = "1.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06"
[[package]]
name = "block-buffer"
version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa"
dependencies = [
"hybrid-array",
"zeroize",
]
[[package]]
name = "block-padding"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "710f1dd022ef4e93f8a438b4ba958de7f64308434fa6a87104481645cc30068b"
dependencies = [
"hybrid-array",
]
[[package]]
name = "cbc"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ce2dc9ee5f88d11e0beb842c88b33c8a5cf0d1329c4b19494af42b07dbfe8896"
dependencies = [
"cipher",
]
[[package]]
name = "cc"
version = "1.11.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "02f0e023adb368345ce0ca6cdfc0f24a06554468d0e8503e14a0841de79bfa69"
dependencies = [
"find-msvc-tools",
"shlex",
]
[[package]]
name = "cfg-if"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
[[package]]
name = "cipher"
version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c"
dependencies = [
"block-buffer",
"crypto-common",
"inout",
]
[[package]]
name = "cmov"
version = "0.5.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a"
[[package]]
name = "const-oid"
version = "0.10.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a"
[[package]]
name = "cpubits"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "15b85f9c39137c3a891689859392b1bd49812121d0d61c9caf00d46ed5ce06ae"
[[package]]
name = "cpufeatures"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566"
dependencies = [
"libc",
]
[[package]]
name = "crypto-bigint"
version = "0.7.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "914c195c4d7fbc5ed7f88d14cbf85914d5c664967658d43404b263913a477e82"
dependencies = [
"cpubits",
"ctutils",
"num-traits",
"rand_core",
"serdect",
"zeroize",
]
[[package]]
name = "crypto-common"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453"
dependencies = [
"hybrid-array",
"rand_core",
]
[[package]]
name = "crypto-primes"
version = "0.7.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3633a51a39c69ebbaa4feaa694bd83d241e4093901c84a0963b19d9bb3f0cf8f"
dependencies = [
"crypto-bigint",
"rand_core",
]
[[package]]
name = "ctr"
version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "baaca1c4b237092596f64d571e9db6ce4109c4ef9742e27590f1709594461f21"
dependencies = [
"cipher",
]
[[package]]
name = "ctutils"
version = "0.4.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "261af4dc7a06ea8a527a8717d8cbba3417530d6ea14e1edb3de6b67806be474f"
dependencies = [
"cmov",
]
[[package]]
name = "der"
version = "0.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6a996a108feb8b427a6e12fcf6af4aa83409b79d72c15337d7741368131ee004"
dependencies = [
"const-oid",
"der_derive",
"flagset",
"pem-rfc7468",
"zeroize",
]
[[package]]
name = "der_derive"
version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "59600e2c2d636fde9b65e99cc6445ac770c63d3628195ff39932b8d6d7409903"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "digest"
version = "0.11.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2"
dependencies = [
"block-buffer",
"const-oid",
"crypto-common",
"ctutils",
"zeroize",
]
[[package]]
name = "domistream"
version = "0.1.0"
dependencies = [
"aes",
"aes-gcm",
"cbc",
"rand_core",
"rsa",
"sha2",
"x509-cert",
"zeroize",
]
[[package]]
name = "find-msvc-tools"
version = "0.1.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48"
[[package]]
name = "flagset"
version = "0.4.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b7ac824320a75a52197e8f2d787f6a38b6718bb6897a35142d749af3c0e8f4fe"
[[package]]
name = "getrandom"
version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"
dependencies = [
"cfg-if",
"libc",
"wasi",
]
[[package]]
name = "ghash"
version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2eecf2d5dc9b66b732b97707a0210906b1d30523eb773193ab777c0c84b3e8d5"
dependencies = [
"polyval",
]
[[package]]
name = "gs-probe"
version = "0.1.0"
dependencies = [
"domistream",
"ring",
"rustls",
]
[[package]]
name = "hmac"
version = "0.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f"
dependencies = [
"digest",
]
[[package]]
name = "hybrid-array"
version = "0.4.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17"
dependencies = [
"typenum",
]
[[package]]
name = "inout"
version = "0.2.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3a580c13f0ffc335ef42dd3f6b1a41b726051c5e1656d9a3aa6fddb3c5dfbbf9"
dependencies = [
"block-padding",
"hybrid-array",
]
[[package]]
name = "libc"
version = "0.2.191"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
[[package]]
name = "num-traits"
version = "0.2.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
dependencies = [
"autocfg",
]
[[package]]
name = "once_cell"
version = "1.21.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
[[package]]
name = "pem-rfc7468"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a6305423e0e7738146434843d1694d621cce767262b2a86910beab705e4493d9"
dependencies = [
"base64ct",
]
[[package]]
name = "pkcs1"
version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6250dd7321adbe93d12b750aee0ced159fd13e77f625edcdf1cb6f83cd99f650"
dependencies = [
"der",
"spki",
]
[[package]]
name = "pkcs8"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "451913da69c775a56034ea8d9003d27ee8948e12443eae7c038ba100a4f21cb7"
dependencies = [
"der",
"spki",
]
[[package]]
name = "polyval"
version = "0.7.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0fa31d631f2b2cb2a544d0aa321ce847a94764d701ca2becc411138b93d49cd"
dependencies = [
"cpubits",
"cpufeatures",
"universal-hash",
]
[[package]]
name = "proc-macro2"
version = "1.0.107"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
dependencies = [
"proc-macro2",
]
[[package]]
name = "rand_core"
version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69"
[[package]]
name = "ring"
version = "0.17.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7"
dependencies = [
"cc",
"cfg-if",
"getrandom",
"libc",
"untrusted",
"windows-sys",
]
[[package]]
name = "rsa"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "23e77fd77e0dea28b3011fd62d15445b7de7959333b0276d930e03be0f755699"
dependencies = [
"const-oid",
"crypto-bigint",
"crypto-common",
"crypto-primes",
"digest",
"hmac",
"pkcs1",
"pkcs8",
"rand_core",
"sha2",
"signature",
"spki",
"zeroize",
]
[[package]]
name = "rustls"
version = "0.23.46"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf"
dependencies = [
"once_cell",
"ring",
"rustls-pki-types",
"rustls-webpki",
"subtle",
"zeroize",
]
[[package]]
name = "rustls-pki-types"
version = "1.16.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb"
dependencies = [
"zeroize",
]
[[package]]
name = "rustls-webpki"
version = "0.103.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e3a0760a887c14823fca5a1c970b01d47c328c696c0c64829d1df50e8f853fd5"
dependencies = [
"ring",
"rustls-pki-types",
"untrusted",
]
[[package]]
name = "serde"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
dependencies = [
"serde_core",
]
[[package]]
name = "serde_core"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.10",
]
[[package]]
name = "serdect"
version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "66cf8fedced2fcf12406bcb34223dffb92eaf34908ede12fed414c82b7f00b3e"
dependencies = [
"base16ct",
"serde",
]
[[package]]
name = "sha2"
version = "0.11.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5b0e5c7d67bc53f435386b2130fdc900488c5703770f6d8a4633060e34288a27"
dependencies = [
"cfg-if",
"cpufeatures",
"digest",
]
[[package]]
name = "shlex"
version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
[[package]]
name = "signature"
version = "3.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "28d567dcbaf0049cb8ac2608a76cd95ff9e4412e1899d389ee400918ca7537f5"
dependencies = [
"digest",
"rand_core",
]
[[package]]
name = "spki"
version = "0.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7ef958a98b9d5da290cfc78946e9f3e61e1e62a18db0d92cac0b83cc161491a9"
dependencies = [
"base64ct",
"der",
]
[[package]]
name = "subtle"
version = "2.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
[[package]]
name = "syn"
version = "2.0.119"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "syn"
version = "3.0.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "typenum"
version = "1.20.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
[[package]]
name = "unicode-ident"
version = "1.0.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
[[package]]
name = "universal-hash"
version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f4987bdc12753382e0bec4a65c50738ffaabc998b9cdd1f952fb5f39b0048a96"
dependencies = [
"crypto-common",
"ctutils",
]
[[package]]
name = "untrusted"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"
[[package]]
name = "wasi"
version = "0.11.1+wasi-snapshot-preview1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
[[package]]
name = "windows-sys"
version = "0.52.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"
dependencies = [
"windows-targets",
]
[[package]]
name = "windows-targets"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"
dependencies = [
"windows_aarch64_gnullvm",
"windows_aarch64_msvc",
"windows_i686_gnu",
"windows_i686_gnullvm",
"windows_i686_msvc",
"windows_x86_64_gnu",
"windows_x86_64_gnullvm",
"windows_x86_64_msvc",
]
[[package]]
name = "windows_aarch64_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
[[package]]
name = "windows_aarch64_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
[[package]]
name = "windows_i686_gnu"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"
[[package]]
name = "windows_i686_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"
[[package]]
name = "windows_i686_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
[[package]]
name = "windows_x86_64_gnu"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
[[package]]
name = "windows_x86_64_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
[[package]]
name = "windows_x86_64_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
[[package]]
name = "x509-cert"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e9f58ad685a2945c7c063f5d69b5c27105d75bb85c740380d8fc64e79a098417"
dependencies = [
"const-oid",
"der",
"spki",
]
[[package]]
name = "zeroize"
version = "1.9.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "85ccff8a4805aba1eaa4cd4afcd49f7557dd2cf5fd79ffc37f8959466effc5aa"
+28
View File
@@ -0,0 +1,28 @@
# gs-probe: a desktop GameStream probe client for the one live interop sitting (docs/LIVE-INTEROP.md). A tool, never
# published, never part of the domistream crate: it may use sockets, threads, files and the clock, and drives
# DomiStream's sans-I/O state machines against ONE host address given on the command line. Its own workspace so it
# never joins the main build.
[package]
name = "gs-probe"
version = "0.1.0"
edition = "2024"
rust-version = "1.89"
license = "CPAL-1.0"
publish = false
[workspace]
members = ["."]
[[bin]]
name = "probe"
path = "src/main.rs"
[dependencies]
domistream = { path = "../../crates/domistream" }
# HTTPS with the client certificate and the pinned host certificate. ring backend, as in tools/lab-relay.
rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12"] }
# The OS random generator (salts, keys, PIN) and SHA-256 fingerprints; already under rustls.
ring = "0.17"
[lints.rust]
unsafe_code = "forbid"
+453
View File
@@ -0,0 +1,453 @@
//! The command line. Strict: an unknown option, a missing value or a value out of range is refused, never guessed.
use std::net::IpAddr;
use std::path::PathBuf;
use domistream::http::launch::AudioLayout;
use domistream::rtsp::client::VideoCodec;
pub const USAGE: &str = "\
usage: probe <command> --host <ip> --out <dir> [options]
commands:
serverinfo GET /serverinfo over HTTP (and HTTPS once paired)
pair pair this probe: prints a 4-digit PIN for the operator to submit through Sunshine's API
apps GET /applist (HTTPS)
launch <app-id> launch, RTSP, ENet control, then receive video + audio for --seconds
quit GET /cancel (HTTPS): quits the running app
unpair GET /unpair (HTTPS): the host forgets this probe
solve-audio-fec <file> offline: solve the audio parity matrix (U16) from a launch run's audio-packets.bin
common options:
--host <ip> the ONE host address; every socket goes there (or to --relay)
--out <dir> identity (test-only key and cert), runs/<utc>-<command>/log.jsonl and dumps
--http-port <n> 47989 --https-port <n> 47984
--relay <loopback ip> connect to tools/lab-relay on this loopback address instead (same ports)
--bind <ip> local address for the UDP sockets (default: unspecified)
--name <text> device name sent while pairing and certificate CN (default: DomiStream probe)
pair:
--wrong-pin print one PIN but use another (U28: what the host does after a failed pairing)
launch:
--mode <WxHxFPS> 1920x1080x60 --bitrate <kbps> 20000 --packet-size <n> 1024
--codec h264|hevc|av1 h264 --hdr --audio stereo|5.1|7.1
--audio-ms <n> 5 --min-fec <n> 2 --rfi (ask for reference frame invalidation)
--encryption <0-7> 7 (bits: 1 control V2, 2 video, 4 audio)
--seconds <n> 20 (1-600) --dump-frames <n> 120 --dump-packets <n> 3000
--ping-ms <n> 500 (UDP ping to the video and audio ports)
--enet-channels <n> 1 --enet-mtu <n> 1392 --enet-connect-data <n> 0
--control-channel <n> 0 --first-control-seq <n> 0
Control message bodies (U10; defaults from Moonshine, which reads no body from any of them, PROTOCOL.md 3.3):
--start-a <hex|empty|none> empty --start-b <hex|empty|none> empty
--periodic-ping <hex|empty|none> empty --periodic-ping-ms <n> 500
--idr <hex|empty|none> empty (IDR request on frame loss, unless --rfi and the host offers invalidation)
--nudge-mouse send one relative mouse move +1/-1 after the first decodable frame
";
/// What to do.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Command {
ServerInfo,
Pair,
Apps,
Launch { app_id: u32 },
Quit,
Unpair,
SolveAudioFec { dump: PathBuf },
}
impl Command {
/// The short name used in run folder names and the log.
pub const fn name(&self) -> &'static str {
match self {
Self::ServerInfo => "serverinfo",
Self::Pair => "pair",
Self::Apps => "apps",
Self::Launch { .. } => "launch",
Self::Quit => "quit",
Self::Unpair => "unpair",
Self::SolveAudioFec { .. } => "solve-audio-fec",
}
}
/// Whether the command talks to the host (and so needs `--host` and `--out`).
pub const fn is_network(&self) -> bool {
!matches!(self, Self::SolveAudioFec { .. })
}
}
/// A control message body from the command line: skip the message, send it empty, or send these bytes.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Body {
None,
Bytes(Vec<u8>),
}
/// Every option, with its default.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Options {
pub host: Option<IpAddr>,
pub out: Option<PathBuf>,
pub http_port: u16,
pub https_port: u16,
pub relay: Option<IpAddr>,
pub bind: Option<IpAddr>,
pub name: String,
pub wrong_pin: bool,
pub width: u32,
pub height: u32,
pub fps: u32,
pub bitrate_kbps: u32,
pub packet_size: u16,
pub codec: VideoCodec,
pub hdr: bool,
pub audio: AudioLayout,
pub audio_ms: u8,
pub min_fec: u8,
pub rfi: bool,
pub encryption: u8,
pub seconds: u32,
pub dump_frames: u32,
pub dump_packets: u32,
pub ping_ms: u32,
pub enet_channels: u8,
pub enet_mtu: u16,
pub enet_connect_data: u32,
pub control_channel: u8,
pub first_control_seq: u32,
pub start_a: Body,
pub start_b: Body,
pub periodic_ping: Body,
pub periodic_ping_ms: u32,
pub idr: Body,
pub nudge_mouse: bool,
}
impl Default for Options {
fn default() -> Self {
Self {
host: None,
out: None,
http_port: domistream::http::DEFAULT_HTTP_PORT,
https_port: domistream::http::DEFAULT_HTTPS_PORT,
relay: None,
bind: None,
name: "DomiStream probe".to_owned(),
wrong_pin: false,
width: 1920,
height: 1080,
fps: 60,
bitrate_kbps: 20_000,
packet_size: 1024,
codec: VideoCodec::H264,
hdr: false,
audio: AudioLayout::Stereo,
audio_ms: 5,
min_fec: 2,
rfi: false,
encryption: 7,
seconds: 20,
dump_frames: 120,
dump_packets: 3000,
ping_ms: 500,
enet_channels: 1,
enet_mtu: 1392,
enet_connect_data: 0,
control_channel: 0,
first_control_seq: 0,
start_a: Body::Bytes(Vec::new()),
start_b: Body::Bytes(Vec::new()),
periodic_ping: Body::Bytes(Vec::new()),
periodic_ping_ms: 500,
idr: Body::Bytes(Vec::new()),
nudge_mouse: false,
}
}
}
impl Options {
/// The address every socket connects to: the relay when one is given, else the host.
pub fn connect_ip(&self) -> Option<IpAddr> {
self.relay.or(self.host)
}
}
/// A parsed command line.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Invocation {
pub command: Command,
pub options: Options,
}
/// Largest control message body accepted from the command line.
pub const MAX_BODY_BYTES: usize = 1024;
fn number<T: std::str::FromStr>(name: &str, v: &str) -> Result<T, String> {
v.parse().map_err(|_| format!("{name}: '{v}' is not a valid number"))
}
fn ranged<T: std::str::FromStr + PartialOrd + std::fmt::Display>(
name: &str,
v: &str,
min: T,
max: T,
) -> Result<T, String> {
let n: T = number(name, v)?;
if n < min || n > max {
return Err(format!("{name}: {n} is outside {min}..={max}"));
}
Ok(n)
}
/// `hex`, `empty` or `none` (when `allow_none`).
pub fn parse_body(name: &str, v: &str, allow_none: bool) -> Result<Body, String> {
match v {
"none" if allow_none => Ok(Body::None),
"empty" => Ok(Body::Bytes(Vec::new())),
_ => parse_hex(v).map(Body::Bytes).map_err(|e| format!("{name}: {e}")),
}
}
/// Hex digits, upper or lower case, optionally separated by spaces, colons or dashes; at most [`MAX_BODY_BYTES`].
pub fn parse_hex(v: &str) -> Result<Vec<u8>, String> {
let digits: Vec<u8> = v.bytes().filter(|b| !matches!(b, b' ' | b':' | b'-')).collect();
if digits.is_empty() || !digits.len().is_multiple_of(2) {
return Err(format!("'{v}' is not an even number of hex digits"));
}
if digits.len() / 2 > MAX_BODY_BYTES {
return Err(format!("more than {MAX_BODY_BYTES} bytes"));
}
let nibble = |b: u8| match b {
b'0'..=b'9' => Ok(b - b'0'),
b'a'..=b'f' => Ok(b - b'a' + 10),
b'A'..=b'F' => Ok(b - b'A' + 10),
_ => Err(format!("'{v}' holds a non-hex character")),
};
digits.chunks(2).map(|p| Ok((nibble(p[0])? << 4) | nibble(p[1])?)).collect()
}
/// `WxHxFPS`, each part non-zero.
pub fn parse_mode(v: &str) -> Result<(u32, u32, u32), String> {
let parts: Vec<&str> = v.split('x').collect();
let [w, h, f] = parts.as_slice() else { return Err(format!("--mode: '{v}' is not WxHxFPS")) };
Ok((ranged("--mode width", w, 1, 8192)?, ranged("--mode height", h, 1, 8192)?, ranged("--mode fps", f, 1, 480)?))
}
fn ip(name: &str, v: &str) -> Result<IpAddr, String> {
v.parse().map_err(|_| format!("{name}: '{v}' is not an IP address (names are not resolved)"))
}
/// Parses the arguments after the program name.
pub fn parse(args: &[String]) -> Result<Invocation, String> {
let mut it = args.iter();
let command = match it.next().map(String::as_str) {
Some("serverinfo") => Command::ServerInfo,
Some("pair") => Command::Pair,
Some("apps") => Command::Apps,
Some("launch") => {
let id = it.next().ok_or("launch: needs an app id")?;
Command::Launch { app_id: number("launch <app-id>", id)? }
}
Some("quit") => Command::Quit,
Some("unpair") => Command::Unpair,
Some("solve-audio-fec") => {
let file = it.next().ok_or("solve-audio-fec: needs a file")?;
Command::SolveAudioFec { dump: PathBuf::from(file) }
}
Some(other) => return Err(format!("unknown command '{other}'")),
None => return Err("no command".into()),
};
let mut o = Options::default();
while let Some(flag) = it.next() {
let mut value = || it.next().map(String::as_str).ok_or(format!("{flag}: needs a value"));
match flag.as_str() {
"--host" => o.host = Some(ip(flag, value()?)?),
"--out" => o.out = Some(PathBuf::from(value()?)),
"--http-port" => o.http_port = ranged(flag, value()?, 1, 65535)?,
"--https-port" => o.https_port = ranged(flag, value()?, 1, 65535)?,
"--relay" => {
let r = ip(flag, value()?)?;
if !r.is_loopback() {
return Err(format!(
"--relay: {r} is not a loopback address (tools/lab-relay runs on loopback only)"
));
}
o.relay = Some(r);
}
"--bind" => o.bind = Some(ip(flag, value()?)?),
"--name" => {
let n = value()?;
if n.is_empty() || n.len() > 64 || n.chars().any(char::is_control) {
return Err("--name: 1-64 characters, no control characters".into());
}
o.name = n.to_owned();
}
"--wrong-pin" => o.wrong_pin = true,
"--mode" => (o.width, o.height, o.fps) = parse_mode(value()?)?,
"--bitrate" => o.bitrate_kbps = ranged(flag, value()?, 500, 500_000)?,
"--packet-size" => o.packet_size = ranged(flag, value()?, 64, 4000)?,
"--codec" => {
o.codec = match value()? {
"h264" => VideoCodec::H264,
"hevc" => VideoCodec::Hevc,
"av1" => VideoCodec::Av1,
v => return Err(format!("--codec: '{v}' is not h264, hevc or av1")),
}
}
"--hdr" => o.hdr = true,
"--audio" => {
o.audio = match value()? {
"stereo" => AudioLayout::Stereo,
"5.1" => AudioLayout::Surround51,
"7.1" => AudioLayout::Surround71,
v => return Err(format!("--audio: '{v}' is not stereo, 5.1 or 7.1")),
}
}
"--audio-ms" => o.audio_ms = ranged(flag, value()?, 1, 100)?,
"--min-fec" => o.min_fec = ranged(flag, value()?, 0, 64)?,
"--rfi" => o.rfi = true,
"--encryption" => o.encryption = ranged(flag, value()?, 0, 7)?,
"--seconds" => o.seconds = ranged(flag, value()?, 1, 600)?,
"--dump-frames" => o.dump_frames = ranged(flag, value()?, 0, 100_000)?,
"--dump-packets" => o.dump_packets = ranged(flag, value()?, 0, 1_000_000)?,
"--ping-ms" => o.ping_ms = ranged(flag, value()?, 10, 10_000)?,
"--enet-channels" => o.enet_channels = ranged(flag, value()?, 1, 255)?,
"--enet-mtu" => o.enet_mtu = ranged(flag, value()?, 576, 4096)?,
"--enet-connect-data" => o.enet_connect_data = number(flag, value()?)?,
"--control-channel" => o.control_channel = number(flag, value()?)?,
"--first-control-seq" => o.first_control_seq = number(flag, value()?)?,
"--start-a" => o.start_a = parse_body(flag, value()?, true)?,
"--start-b" => o.start_b = parse_body(flag, value()?, true)?,
"--periodic-ping" => o.periodic_ping = parse_body(flag, value()?, true)?,
"--periodic-ping-ms" => o.periodic_ping_ms = ranged(flag, value()?, 10, 10_000)?,
"--idr" => o.idr = parse_body(flag, value()?, true)?,
"--nudge-mouse" => o.nudge_mouse = true,
other => return Err(format!("unknown option '{other}'")),
}
}
if o.control_channel >= o.enet_channels {
return Err(format!(
"--control-channel {} needs --enet-channels above it (now {})",
o.control_channel, o.enet_channels
));
}
if command.is_network() {
if o.host.is_none() {
return Err(format!("{}: --host is required", command.name()));
}
if o.out.is_none() {
return Err(format!("{}: --out is required", command.name()));
}
}
Ok(Invocation { command, options: o })
}
#[cfg(test)]
mod tests {
use super::*;
fn args(s: &str) -> Vec<String> {
s.split_whitespace().map(str::to_owned).collect()
}
fn ok(s: &str) -> Invocation {
parse(&args(s)).unwrap()
}
fn err(s: &str) -> String {
parse(&args(s)).unwrap_err()
}
#[test]
fn network_commands_need_host_and_out() {
assert!(err("serverinfo --out x").contains("--host"));
assert!(err("serverinfo --host 192.168.100.140").contains("--out"));
let i = ok("serverinfo --host 192.168.100.140 --out F:/x");
assert_eq!(i.command, Command::ServerInfo);
assert_eq!(i.options.host, Some("192.168.100.140".parse().unwrap()));
assert_eq!(i.options.connect_ip(), i.options.host);
}
#[test]
fn defaults_are_the_documented_ones() {
let o = ok("pair --host 127.0.0.1 --out o").options;
assert_eq!((o.http_port, o.https_port), (47989, 47984));
assert_eq!((o.width, o.height, o.fps, o.bitrate_kbps, o.packet_size), (1920, 1080, 60, 20_000, 1024));
assert_eq!((o.encryption, o.seconds, o.enet_channels, o.enet_mtu), (7, 20, 1, 1392));
assert_eq!(o.start_a, Body::Bytes(vec![]));
// U10 candidates (PROTOCOL.md 3.3): every body empty, a ping every 500 ms.
assert_eq!(
(o.start_b, o.periodic_ping, o.idr),
(Body::Bytes(vec![]), Body::Bytes(vec![]), Body::Bytes(vec![]))
);
assert_eq!(o.periodic_ping_ms, 500);
assert!(!o.wrong_pin && !o.nudge_mouse && !o.rfi);
}
#[test]
fn launch_needs_a_numeric_app_id() {
assert!(err("launch").contains("app id"));
assert!(err("launch --host 1.2.3.4 --out o").contains("not a valid number"));
assert!(err("launch abc --host 1.2.3.4 --out o").contains("not a valid number"));
assert_eq!(ok("launch 881448767 --host 1.2.3.4 --out o").command, Command::Launch { app_id: 881_448_767 });
}
#[test]
fn host_names_and_unknown_options_are_refused() {
assert!(err("apps --host my-pc --out o").contains("not an IP address"));
assert!(err("apps --host 1.2.3.4 --out o --verbose").contains("unknown option"));
assert!(err("apps --host 1.2.3.4 --out").contains("needs a value"));
assert!(err("dance").contains("unknown command"));
assert!(err("").contains("no command"));
}
#[test]
fn relay_must_be_loopback() {
assert!(err("apps --host 192.168.100.140 --out o --relay 192.168.100.2").contains("loopback"));
let o = ok("apps --host 192.168.100.140 --out o --relay 127.0.0.1").options;
assert_eq!(o.connect_ip(), Some("127.0.0.1".parse().unwrap()));
}
#[test]
fn launch_options_parse_and_are_ranged() {
let o = ok("launch 1 --host ::1 --out o --mode 1280x720x30 --codec hevc --audio 5.1 --seconds 600 \
--start-b 0a0B --start-a none --idr none --enet-channels 48 --control-channel 47 --hdr --rfi")
.options;
assert_eq!((o.width, o.height, o.fps), (1280, 720, 30));
assert_eq!((o.codec, o.audio), (VideoCodec::Hevc, AudioLayout::Surround51));
assert_eq!((o.start_a, o.start_b, o.idr), (Body::None, Body::Bytes(vec![0x0a, 0x0b]), Body::None));
assert!(o.hdr && o.rfi);
assert!(err("launch 1 --host ::1 --out o --seconds 601").contains("outside"));
assert!(err("launch 1 --host ::1 --out o --encryption 8").contains("outside"));
assert!(err("launch 1 --host ::1 --out o --mode 1920x1080").contains("WxHxFPS"));
assert!(err("launch 1 --host ::1 --out o --mode 0x1080x60").contains("outside"));
assert!(err("launch 1 --host ::1 --out o --control-channel 1").contains("--enet-channels"));
assert!(err("launch 1 --host ::1 --out o --codec vp9").contains("h264"));
}
#[test]
fn hex_bodies() {
assert_eq!(parse_hex("00 ff:A0-0b").unwrap(), vec![0x00, 0xff, 0xa0, 0x0b]);
assert!(parse_hex("abc").is_err());
assert!(parse_hex("zz").is_err());
assert!(parse_hex("").is_err());
assert!(parse_hex(&"00".repeat(MAX_BODY_BYTES + 1)).is_err());
assert_eq!(parse_body("x", "none", true).unwrap(), Body::None);
assert!(parse_body("x", "none", false).is_err());
}
#[test]
fn solve_audio_fec_is_offline() {
let i = ok("solve-audio-fec F:/runs/a/audio-packets.bin");
assert_eq!(i.command, Command::SolveAudioFec { dump: PathBuf::from("F:/runs/a/audio-packets.bin") });
assert!(!i.command.is_network());
}
#[test]
fn device_name_is_checked() {
assert!(err("pair --host 1.2.3.4 --out o --name").contains("needs a value"));
let long = format!("pair --host 1.2.3.4 --out o --name {}", "n".repeat(65));
assert!(err(&long).contains("1-64"));
}
}
+222
View File
@@ -0,0 +1,222 @@
//! `serverinfo`, `pair`, `apps`, `quit`, `unpair`.
use domistream::http::{
Scheme, app_list_request, cancel_request, parse_app_list, parse_server_info, parse_status_response,
server_info_request, unpair_request,
};
use domistream::pairing::{PairingSession, PairingState, PairingStep, Pin, ServerCert, parse_pair_response};
use crate::log::{J, Kind};
use crate::rng::sha256_hex;
use crate::{Ctx, body_j, state};
/// Non-200 HTTP status: stop and report (U27 is in the body).
fn check_status(ctx: &mut Ctx, step: &str, x: &crate::http::Exchange) -> Result<(), String> {
if x.response.status == 200 {
return Ok(());
}
let m = format!("HTTP status {} {}", x.response.status, x.response.reason);
ctx.log.stop(step, &["U27"], m.clone(), body_j(&x.response.body));
Err(m)
}
fn server_info(ctx: &mut Ctx, scheme: Scheme) -> Result<(), String> {
let step = match scheme {
Scheme::Http => "serverinfo.http",
Scheme::Https => "serverinfo.https",
};
let req = server_info_request(scheme, &ctx.id.unique_id).map_err(|e| e.to_string())?;
let x = ctx.http(step, &["U25", "U27"], &req, None)?;
check_status(ctx, step, &x)?;
let info = match parse_server_info(&x.response.body) {
Ok(i) => i,
Err(e) => {
ctx.log.parse_error(step, &["U25", "U27"], &e, body_j(&x.response.body));
ctx.log.stop(step, &["U25"], format!("serverinfo refused: {e}"), J::Null);
return Err(format!("serverinfo refused: {e}"));
}
};
let codec_bits = info.codec_mode_support.map_or(J::Null, |b| J::s(format!("{b:#010x} = {b:032b}")));
ctx.log.record(
step,
Kind::Note,
&["U25"],
J::O(vec![("parsed", J::dbg(&info)), ("codec_mode_support_bits", codec_bits)]),
);
println!("{step}:");
println!(" hostname {} appversion {} GfeVersion {:?}", info.hostname, info.app_version, info.gfe_version);
println!(
" HttpsPort {} ExternalPort {:?} state {} currentgame {}",
info.https_port, info.http_port, info.state, info.current_game
);
println!(
" ServerCodecModeSupport {:?} MaxLumaPixelsHEVC {:?} PairStatus {}",
info.codec_mode_support, info.max_luma_pixels_hevc, info.paired
);
if info.https_port != ctx.opts.https_port {
let m = format!(
"the host's HttpsPort is {}; pass --https-port {} for HTTPS calls",
info.https_port, info.https_port
);
ctx.log.note(step, &[], m.clone());
println!(" note: {m}");
}
Ok(())
}
pub fn serverinfo(ctx: &mut Ctx) -> Result<(), String> {
server_info(ctx, Scheme::Http)?;
if ctx.host_cert.is_some() {
server_info(ctx, Scheme::Https)?;
} else {
println!("(not paired yet: HTTPS serverinfo skipped)");
}
Ok(())
}
pub fn pair(ctx: &mut Ctx) -> Result<(), String> {
let shown = Pin::generate(&mut ctx.rng).map_err(|e| e.to_string())?;
let used = if ctx.opts.wrong_pin {
loop {
let p = Pin::generate(&mut ctx.rng).map_err(|e| e.to_string())?;
if p != shown {
break p;
}
}
} else {
shown
};
// The PIN goes to the operator's terminal only, never to the log.
let digits = String::from_utf8_lossy(shown.as_bytes()).into_owned();
println!();
println!(" PIN for the operator: {digits}");
println!(" Submit it through Sunshine's API now (docs/LIVE-INTEROP.md, step P). Waiting up to 120 s.");
if ctx.opts.wrong_pin {
println!(" (--wrong-pin: the probe itself uses another PIN; pairing is expected to fail, U28)");
}
println!();
ctx.log.note(
"pair",
&["U1", "U2", "U28"],
format!(
"PIN generated and shown to the operator (not logged); wrong_pin={}; device name '{}'; client cert sha256 {}",
ctx.opts.wrong_pin,
ctx.opts.name,
sha256_hex(ctx.id.client.cert_der())
),
);
let name = ctx.opts.name.clone();
let (mut session, mut req) = PairingSession::start(&ctx.id.client, &ctx.id.unique_id, &name, used, &mut ctx.rng)
.map_err(|e| format!("pairing start: {e}"))?;
let mut host_cert: Option<ServerCert> = None;
let mut n = 1;
loop {
let before = session.state();
let step = format!("pair.{n}");
let us: &[&str] = if n == 1 { &["U1", "U2", "U24"] } else { &["U1", "U2", "U28"] };
let x = match ctx.http(&step, us, &req, host_cert.as_ref()) {
Ok(x) => x,
Err(e) => {
println!("pairing stopped at step {n} ({before:?}): {e}");
return Err(e);
}
};
if before == PairingState::AwaitServerCert
&& let Ok(a) = parse_pair_response(&x.response.body)
&& let Some(pem) = a.plain_cert
{
match ServerCert::from_pem(&pem) {
Ok(c) => {
ctx.log.note(&step, &["U2"], format!("host certificate sha256 {}", sha256_hex(c.der())));
host_cert = Some(c);
}
Err(e) => ctx.log.parse_error(&step, &["U2"], &e, crate::log::text(&pem)),
}
}
let status = x.response.status;
match session.handle_response(&ctx.id.client, status, &x.response.body, &mut ctx.rng) {
Ok(PairingStep::Send(next)) => {
req = next;
n += 1;
}
Ok(PairingStep::Paired(p)) => {
state::save_host_cert(&ctx.out, &p.server_cert, ctx.host)?;
ctx.log.record(
"pair.done",
Kind::Summary,
&["U1", "U2"],
J::O(vec![("steps", J::U(n)), ("host_cert_sha256", J::s(sha256_hex(p.server_cert.der())))]),
);
ctx.host_cert = Some(p.server_cert);
println!(
"paired after {n} steps; host certificate pinned in {}",
state::identity_dir(&ctx.out).display()
);
// Evidence that the host now treats this certificate as paired.
return server_info(ctx, Scheme::Https);
}
Err(e) => {
let failed = session.state();
ctx.log.parse_error(&step, &["U1", "U28"], &e, body_j(&x.response.body));
ctx.log.stop(
&step,
&["U1", "U2", "U28"],
format!("pairing failed at step {n} ({before:?} -> {failed:?}): {e}"),
J::O(vec![("wrong_pin", J::Bool(ctx.opts.wrong_pin))]),
);
println!("pairing failed at step {n}: {failed:?} ({e})");
return Err(format!("pairing failed: {e}"));
}
}
}
}
pub fn apps(ctx: &mut Ctx) -> Result<(), String> {
let req = app_list_request(&ctx.id.unique_id).map_err(|e| e.to_string())?;
let x = ctx.http("apps", &["U24", "U27"], &req, None)?;
check_status(ctx, "apps", &x)?;
match parse_app_list(&x.response.body) {
Ok(apps) => {
ctx.log.record("apps", Kind::Note, &[], J::dbg(&apps));
println!("{} apps:", apps.len());
for a in &apps {
println!(" {:>12} hdr={} {}", a.id, u8::from(a.hdr_supported), a.title);
}
Ok(())
}
Err(e) => {
ctx.log.parse_error("apps", &["U27"], &e, body_j(&x.response.body));
ctx.log.stop("apps", &[], format!("applist refused: {e}"), J::Null);
Err(format!("applist refused: {e}"))
}
}
}
fn status_call(ctx: &mut Ctx, step: &str, req: domistream::http::HttpRequest) -> Result<(), String> {
let x = ctx.http(step, &["U27"], &req, None)?;
check_status(ctx, step, &x)?;
match parse_status_response(&x.response.body) {
Ok(()) => {
println!("{step}: done");
Ok(())
}
Err(e) => {
ctx.log.parse_error(step, &["U27"], &e, body_j(&x.response.body));
ctx.log.stop(step, &["U27"], format!("{step} refused: {e}"), J::Null);
Err(format!("{step} refused: {e}"))
}
}
}
pub fn quit(ctx: &mut Ctx) -> Result<(), String> {
let req = cancel_request(&ctx.id.unique_id).map_err(|e| e.to_string())?;
status_call(ctx, "quit", req)
}
pub fn unpair(ctx: &mut Ctx) -> Result<(), String> {
let req = unpair_request(&ctx.id.unique_id).map_err(|e| e.to_string())?;
status_call(ctx, "unpair", req)?;
state::forget_host_cert(&ctx.out)?;
ctx.host_cert = None;
Ok(())
}
+97
View File
@@ -0,0 +1,97 @@
//! Packet dumps for offline analysis after the sitting (U14 video parity, U16 audio parity matrix): a magic, then
//! one record per datagram: `t_us u64 LE`, `len u16 LE`, the bytes.
use std::fs::File;
use std::io::{self, BufWriter, Write};
use std::path::Path;
pub const MAGIC: &[u8; 8] = b"GSPROBE1";
/// Largest dump file read back.
pub const MAX_DUMP_BYTES: usize = 512 * 1024 * 1024;
pub fn encode_record(t_us: u64, bytes: &[u8]) -> Vec<u8> {
let len = u16::try_from(bytes.len()).unwrap_or(u16::MAX);
let shown = bytes.get(..usize::from(len)).unwrap_or(bytes);
let mut r = Vec::with_capacity(10 + shown.len());
r.extend_from_slice(&t_us.to_le_bytes());
r.extend_from_slice(&len.to_le_bytes());
r.extend_from_slice(shown);
r
}
/// Every record of a dump file's contents.
pub fn decode(data: &[u8]) -> Result<Vec<(u64, Vec<u8>)>, String> {
if data.len() > MAX_DUMP_BYTES {
return Err(format!("dump over {MAX_DUMP_BYTES} bytes"));
}
let mut rest = data.strip_prefix(MAGIC.as_slice()).ok_or("not a gs-probe dump (magic)")?;
let mut out = Vec::new();
while !rest.is_empty() {
let head = rest.get(..10).ok_or("record header cut")?;
let mut t = [0u8; 8];
t.copy_from_slice(&head[..8]);
let len = usize::from(u16::from_le_bytes([head[8], head[9]]));
let body = rest.get(10..10 + len).ok_or("record body cut")?;
out.push((u64::from_le_bytes(t), body.to_vec()));
rest = &rest[10 + len..];
}
Ok(out)
}
/// Writes up to `limit` records.
pub struct PacketDump {
w: Option<BufWriter<File>>,
pub written: u32,
limit: u32,
}
impl PacketDump {
pub fn create(path: &Path, limit: u32) -> io::Result<Self> {
if limit == 0 {
return Ok(Self { w: None, written: 0, limit });
}
let mut w = BufWriter::new(File::options().write(true).create_new(true).open(path)?);
w.write_all(MAGIC)?;
Ok(Self { w: Some(w), written: 0, limit })
}
pub fn push(&mut self, t_us: u64, bytes: &[u8]) -> io::Result<()> {
if self.written >= self.limit {
return Ok(());
}
if let Some(w) = &mut self.w {
w.write_all(&encode_record(t_us, bytes))?;
self.written += 1;
}
Ok(())
}
pub fn finish(&mut self) -> io::Result<()> {
if let Some(w) = &mut self.w {
w.flush()?;
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn records_round_trip() {
let mut file = MAGIC.to_vec();
file.extend(encode_record(7, b"abc"));
file.extend(encode_record(u64::MAX, b""));
assert_eq!(decode(&file).unwrap(), vec![(7, b"abc".to_vec()), (u64::MAX, vec![])]);
}
#[test]
fn cut_or_foreign_files_are_refused() {
assert!(decode(b"NOTADUMP").is_err());
let mut file = MAGIC.to_vec();
file.extend(encode_record(1, b"abcd"));
assert!(decode(&file[..file.len() - 1]).unwrap_err().contains("body cut"));
assert!(decode(&file[..MAGIC.len() + 5]).unwrap_err().contains("header cut"));
}
}
+390
View File
@@ -0,0 +1,390 @@
//! Two FEC measurements the sitting settles from real traffic, with our own arithmetic:
//!
//! - **U14** (video, live): for each complete block, DomiStream's Cauchy encoder must reproduce the parity packets
//! the host sent (offset 32 on). Two readings are checked: parity over whole data packets (PROTOCOL.md 5.3) and
//! over data packets with their 32 header bytes zeroed.
//! - **U16** (audio, offline from `audio-packets.bin`): each parity byte is a linear combination over GF(2^8)
//! (polynomial `0x11D`) of the four data bytes at the same offset, so a few offsets give the 2 × 4 matrix; every
//! other byte of every block then checks it.
use std::collections::BTreeMap;
use domistream::audio::{AudioPacket, parse_audio_packet};
use domistream::fec::{ReedSolomon, parity_count};
/// GF(2^8) with polynomial `0x11D`, generator 2.
pub struct Gf {
exp: [u8; 512],
log: [u8; 256],
}
impl Gf {
pub fn new() -> Self {
let (mut exp, mut log) = ([0u8; 512], [0u8; 256]);
let mut x: u16 = 1;
for (i, e) in exp.iter_mut().take(255).enumerate() {
*e = x as u8;
log[usize::from(x)] = i as u8;
x <<= 1;
if x & 0x100 != 0 {
x ^= 0x11D;
}
}
// exp[i + 255] = exp[i], so a product's log sum (at most 508) needs no reduction.
exp.copy_within(0..255, 255);
Self { exp, log }
}
pub fn mul(&self, a: u8, b: u8) -> u8 {
if a == 0 || b == 0 {
0
} else {
self.exp[usize::from(self.log[usize::from(a)]) + usize::from(self.log[usize::from(b)])]
}
}
/// `1 / a`; `a` must not be 0.
pub fn inv(&self, a: u8) -> u8 {
self.exp[255 - usize::from(self.log[usize::from(a)])]
}
}
/// What the audio solver found for one parity row.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum RowResult {
/// The four coefficients, and how many byte equations agreed and disagreed with them.
Solved { coefficients: [u8; 4], equations: u64, mismatches: u64 },
/// Not enough independent equations (rank below 4).
Underdetermined { rank: usize, equations: u64 },
}
/// The audio parity matrix from captured blocks.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct AudioFecReport {
pub data_packets: u64,
pub parity_packets: u64,
pub unparsed: u64,
pub blocks: usize,
/// Blocks with all 4 data packets and parity row 0 / row 1, all of one length.
pub complete: [usize; 2],
pub rows: [RowResult; 2],
}
impl AudioFecReport {
/// The 2 × 4 matrix, row-major, when both rows solved without a single mismatch.
pub fn matrix(&self) -> Option<[u8; 8]> {
match (&self.rows[0], &self.rows[1]) {
(
RowResult::Solved { coefficients: a, mismatches: 0, .. },
RowResult::Solved { coefficients: b, mismatches: 0, .. },
) => Some([a[0], a[1], a[2], a[3], b[0], b[1], b[2], b[3]]),
_ => None,
}
}
/// Whether DomiStream accepts the solved matrix as an MDS code (`AudioFec::ParityMatrix`).
pub fn matrix_is_mds(&self) -> Option<bool> {
self.matrix().map(|m| ReedSolomon::with_parity_matrix(4, 2, &m).is_ok())
}
}
#[derive(Default)]
struct AudioBlock {
data: [Option<Vec<u8>>; 4],
parity: [Option<Vec<u8>>; 2],
}
/// Solves U16 from raw audio datagrams (as received: encrypted payloads are the shards).
pub fn solve_audio(datagrams: &[Vec<u8>]) -> AudioFecReport {
let gf = Gf::new();
let mut blocks: BTreeMap<u16, AudioBlock> = BTreeMap::new();
let (mut data_packets, mut parity_packets, mut unparsed) = (0, 0, 0);
for d in datagrams {
match parse_audio_packet(d) {
Ok(AudioPacket::Data { rtp, payload }) => {
data_packets += 1;
let b = blocks.entry(rtp.sequence & !3).or_default();
b.data[usize::from(rtp.sequence & 3)] = Some(payload.to_vec());
}
Ok(AudioPacket::Parity { fec, parity, .. }) => {
parity_packets += 1;
let b = blocks.entry(fec.base_sequence).or_default();
b.parity[usize::from(fec.shard_index & 1)] = Some(parity.to_vec());
}
Err(_) => unparsed += 1,
}
}
let mut complete = [0usize; 2];
let rows = [0usize, 1].map(|row| {
let mut basis: Vec<(usize, [u8; 5])> = Vec::new();
let mut equations: Vec<[u8; 5]> = Vec::new();
for b in blocks.values() {
let (Some(d0), Some(d1), Some(d2), Some(d3), Some(p)) =
(&b.data[0], &b.data[1], &b.data[2], &b.data[3], &b.parity[row])
else {
continue;
};
let len = p.len();
if [d0, d1, d2, d3].iter().any(|d| d.len() != len) {
continue;
}
complete[row] += 1;
for o in 0..len {
let eq = [d0[o], d1[o], d2[o], d3[o], p[o]];
equations.push(eq);
if basis.len() < 4 {
add_to_basis(&gf, &mut basis, eq);
}
}
}
let count = equations.len() as u64;
if basis.len() < 4 {
return RowResult::Underdetermined { rank: basis.len(), equations: count };
}
let mut c = [0u8; 4];
for (pc, r) in &basis {
c[*pc] = r[4];
}
let mismatches =
equations.iter().filter(|e| (0..4).fold(0u8, |acc, i| acc ^ gf.mul(c[i], e[i])) != e[4]).count() as u64;
RowResult::Solved { coefficients: c, equations: count, mismatches }
});
AudioFecReport { data_packets, parity_packets, unparsed, blocks: blocks.len(), complete, rows }
}
/// Adds one augmented equation to a reduced row-echelon basis (pivot 1, zero in other rows' pivot columns).
fn add_to_basis(gf: &Gf, basis: &mut Vec<(usize, [u8; 5])>, mut row: [u8; 5]) {
for (pc, b) in basis.iter() {
let f = row[*pc];
if f != 0 {
for i in 0..5 {
row[i] ^= gf.mul(f, b[i]);
}
}
}
let Some(pc) = (0..4).find(|&i| row[i] != 0) else { return };
let inv = gf.inv(row[pc]);
for v in &mut row {
*v = gf.mul(*v, inv);
}
for (_, b) in basis.iter_mut() {
let f = b[pc];
if f != 0 {
for i in 0..5 {
b[i] ^= gf.mul(f, row[i]);
}
}
}
basis.push((pc, row));
}
/// How a complete video block compared with our encoder.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum VideoOutcome {
/// Parity over whole data packets (PROTOCOL.md 5.3) matches.
Whole,
/// Only parity over data packets with zeroed 32-byte headers matches.
PayloadOnly,
/// Neither reading matches.
Neither,
/// Not comparable (shards of different lengths, or a code DomiStream refuses).
Skipped,
}
struct VideoBlock {
k: u16,
m: usize,
shards: BTreeMap<u16, Vec<u8>>,
}
/// The live U14 check: collects each block's packets (plaintext) and compares the parity once it is complete.
pub struct VideoFecCheck {
pending: BTreeMap<(u32, u8), VideoBlock>,
limit: u64,
pub checked: u64,
pub whole: u64,
pub payload_only: u64,
pub neither: u64,
pub skipped: u64,
}
/// Blocks kept open at once; the oldest is dropped beyond this (a lost packet means it never completes).
const MAX_PENDING_BLOCKS: usize = 64;
impl VideoFecCheck {
/// Checks at most `limit` blocks.
pub fn new(limit: u64) -> Self {
Self { pending: BTreeMap::new(), limit, checked: 0, whole: 0, payload_only: 0, neither: 0, skipped: 0 }
}
/// One plaintext packet of block `block` of frame `frame`: shard `shard` of `k` data shards at `pct` percent.
pub fn push(&mut self, frame: u32, block: u8, shard: u16, k: u16, pct: u8, packet: &[u8]) -> Option<VideoOutcome> {
if self.checked >= self.limit {
return None;
}
let m = parity_count(usize::from(k), pct).ok()?;
if m == 0 {
return None;
}
let entry = self.pending.entry((frame, block)).or_insert_with(|| VideoBlock { k, m, shards: BTreeMap::new() });
if entry.k != k || entry.m != m {
return None;
}
entry.shards.insert(shard, packet.to_vec());
if entry.shards.len() < usize::from(k) + m {
while self.pending.len() > MAX_PENDING_BLOCKS {
self.pending.pop_first();
}
return None;
}
let b = self.pending.remove(&(frame, block))?;
self.checked += 1;
let outcome = compare(&b);
match outcome {
VideoOutcome::Whole => self.whole += 1,
VideoOutcome::PayloadOnly => self.payload_only += 1,
VideoOutcome::Neither => self.neither += 1,
VideoOutcome::Skipped => self.skipped += 1,
}
Some(outcome)
}
}
fn compare(b: &VideoBlock) -> VideoOutcome {
let k = usize::from(b.k);
let shards: Vec<&Vec<u8>> = b.shards.values().collect();
let len = shards.first().map_or(0, |s| s.len());
if len <= 32 || shards.iter().any(|s| s.len() != len) {
return VideoOutcome::Skipped;
}
let Ok(rs) = ReedSolomon::new(k, b.m) else { return VideoOutcome::Skipped };
let parity_matches = |zero_headers: bool| -> Option<bool> {
let mut work: Vec<Vec<u8>> = Vec::with_capacity(k + b.m);
for s in shards.iter().take(k) {
let mut d = (*s).clone();
if zero_headers {
d.iter_mut().take(32).for_each(|x| *x = 0);
}
work.push(d);
}
work.extend((0..b.m).map(|_| vec![0u8; len]));
rs.encode(&mut work).ok()?;
Some(work.iter().skip(k).zip(shards.iter().skip(k)).all(|(ours, theirs)| ours.get(32..) == theirs.get(32..)))
};
match (parity_matches(false), parity_matches(true)) {
(Some(true), _) => VideoOutcome::Whole,
(_, Some(true)) => VideoOutcome::PayloadOnly,
(Some(false), _) | (_, Some(false)) => VideoOutcome::Neither,
_ => VideoOutcome::Skipped,
}
}
#[cfg(test)]
mod tests {
use super::*;
fn rtp(pt: u8, seq: u16, payload: &[u8]) -> Vec<u8> {
let mut p = vec![0x80, pt];
p.extend_from_slice(&seq.to_be_bytes());
p.extend_from_slice(&[0, 0, 0, 0, 0, 0, 0, 0]);
p.extend_from_slice(payload);
p
}
fn parity_packet(seq: u16, shard: u8, base: u16, parity: &[u8]) -> Vec<u8> {
let mut fec = vec![shard, 97];
fec.extend_from_slice(&base.to_be_bytes());
fec.extend_from_slice(&[0; 8]);
fec.extend_from_slice(parity);
rtp(127, seq, &fec)
}
/// Blocks made with a known matrix; the solver must find it and every byte must agree.
#[test]
fn audio_matrix_is_recovered() {
let gf = Gf::new();
let m = [0x77, 0x40, 0x38, 0x0e, 0xc7, 0xa7, 0x0d, 0x6c];
let mut datagrams = Vec::new();
let mut x: u32 = 12345;
for block in 0..6u16 {
let base = block * 4;
let data: Vec<Vec<u8>> = (0..4)
.map(|_| {
(0..32)
.map(|_| {
x = x.wrapping_mul(1_103_515_245).wrapping_add(12_345);
(x >> 16) as u8
})
.collect()
})
.collect();
for (i, d) in data.iter().enumerate() {
datagrams.push(rtp(97, base + i as u16, d));
}
for row in 0..2 {
let p: Vec<u8> =
(0..32).map(|o| (0..4).fold(0u8, |acc, i| acc ^ gf.mul(m[row * 4 + i], data[i][o]))).collect();
datagrams.push(parity_packet(1000 + block * 2 + row as u16, row as u8, base, &p));
}
}
datagrams.push(vec![0x00, 0x01]);
let r = solve_audio(&datagrams);
assert_eq!((r.data_packets, r.parity_packets, r.unparsed, r.blocks, r.complete), (24, 12, 1, 6, [6, 6]));
assert_eq!(r.matrix(), Some(m), "{r:?}");
}
#[test]
fn too_little_audio_is_underdetermined() {
let r = solve_audio(&[rtp(97, 0, &[1, 2]), rtp(97, 1, &[3, 4])]);
assert!(matches!(r.rows[0], RowResult::Underdetermined { rank: 0, equations: 0 }));
assert_eq!(r.matrix(), None);
}
#[test]
fn gf_inverse() {
let gf = Gf::new();
for a in 1..=255u8 {
assert_eq!(gf.mul(a, gf.inv(a)), 1);
}
// 2 * 0x80 wraps through the polynomial.
assert_eq!(gf.mul(2, 0x80), 0x1D);
}
fn packet(shard: u16, fill: u8, len: usize) -> Vec<u8> {
let mut p = vec![fill; len];
p[0] = 0x90;
p[2..4].copy_from_slice(&shard.to_be_bytes());
p
}
#[test]
fn video_parity_from_our_encoder_matches_whole_packets() {
let (k, m, len) = (4usize, 2usize, 64usize);
let rs = ReedSolomon::new(k, m).unwrap();
let mut shards: Vec<Vec<u8>> = (0..k).map(|i| packet(i as u16, 0x10 + i as u8, len)).collect();
shards.extend((0..m).map(|_| vec![0u8; len]));
rs.encode(&mut shards).unwrap();
// The host overwrites parity bytes 0-31 with headers after computing the parity.
for s in shards.iter_mut().skip(k) {
s[..32].fill(0xEE);
}
let mut check = VideoFecCheck::new(10);
let mut last = None;
for (i, s) in shards.iter().enumerate() {
last = check.push(9, 0, i as u16, k as u16, 50, s);
}
assert_eq!(last, Some(VideoOutcome::Whole));
assert_eq!((check.checked, check.whole), (1, 1));
}
#[test]
fn foreign_video_parity_is_reported() {
let mut check = VideoFecCheck::new(10);
let mut last = None;
for i in 0..6u16 {
last = check.push(1, 0, i, 4, 50, &packet(i, 0x33 + i as u8, 64));
}
assert_eq!(last, Some(VideoOutcome::Neither));
assert_eq!(check.neither, 1);
}
}
+325
View File
@@ -0,0 +1,325 @@
//! A minimal HTTP/1.1 `GET` client for the host's HTTP and HTTPS ports: one request per connection
//! (`Connection: close`), size caps, a deadline, and a strict response parser (`Content-Length`, chunked, or the
//! connection close).
use std::io::{self, Read, Write};
use std::net::{SocketAddr, TcpStream};
use std::sync::Arc;
use std::time::{Duration, Instant};
use rustls::pki_types::ServerName;
use rustls::{ClientConfig, ClientConnection, StreamOwned};
/// Largest response accepted, headers included.
pub const MAX_RESPONSE_BYTES: usize = 2 * 1024 * 1024;
/// Largest header section.
pub const MAX_HEAD_BYTES: usize = 16 * 1024;
/// Most header lines.
pub const MAX_HEADERS: usize = 64;
/// How long a TCP connect may take.
pub const CONNECT_TIMEOUT: Duration = Duration::from_secs(5);
/// Read poll interval (the deadline is checked between reads).
const POLL: Duration = Duration::from_millis(250);
/// How the body's end was found.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Framing {
Length,
Chunked,
Close,
}
/// A parsed response.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Response {
pub status: u16,
pub reason: String,
pub headers: Vec<(String, String)>,
pub body: Vec<u8>,
pub framing: Framing,
}
impl Response {
pub fn header(&self, name: &str) -> Option<&str> {
self.headers.iter().find(|(n, _)| n.eq_ignore_ascii_case(name)).map(|(_, v)| v.as_str())
}
}
/// The request bytes. `host` is the `Host` header value (`ip:port`).
pub fn request(path_and_query: &str, host: &str) -> Vec<u8> {
format!(
"GET {path_and_query} HTTP/1.1\r\nHost: {host}\r\nUser-Agent: gs-probe/0.1\r\nAccept: */*\r\nConnection: close\r\n\r\n"
)
.into_bytes()
}
/// Parses what has arrived so far. `Ok(None)`: not complete yet (and the connection is still open).
pub fn parse(raw: &[u8], eof: bool) -> Result<Option<Response>, String> {
if raw.len() > MAX_RESPONSE_BYTES {
return Err(format!("response over {MAX_RESPONSE_BYTES} bytes"));
}
let Some(end) = raw.windows(4).position(|w| w == b"\r\n\r\n") else {
if raw.len() > MAX_HEAD_BYTES {
return Err(format!("headers over {MAX_HEAD_BYTES} bytes"));
}
return if eof { Err("connection closed inside the headers".into()) } else { Ok(None) };
};
if end > MAX_HEAD_BYTES {
return Err(format!("headers over {MAX_HEAD_BYTES} bytes"));
}
let head = std::str::from_utf8(raw.get(..end).unwrap_or(&[])).map_err(|_| "headers are not UTF-8".to_owned())?;
let mut lines = head.split("\r\n");
let status_line = lines.next().unwrap_or("");
let mut parts = status_line.splitn(3, ' ');
let (version, code, reason) = (parts.next().unwrap_or(""), parts.next().unwrap_or(""), parts.next().unwrap_or(""));
if !matches!(version, "HTTP/1.1" | "HTTP/1.0") || code.len() != 3 || !code.bytes().all(|b| b.is_ascii_digit()) {
return Err(format!("bad status line '{status_line}'"));
}
let status: u16 = code.parse().map_err(|_| format!("bad status line '{status_line}'"))?;
let mut headers = Vec::new();
for l in lines {
let (n, v) = l.split_once(':').ok_or_else(|| format!("bad header line '{l}'"))?;
if n.is_empty() || n.bytes().any(|b| !b.is_ascii_graphic()) {
return Err(format!("bad header name '{n}'"));
}
headers.push((n.to_owned(), v.trim().to_owned()));
if headers.len() > MAX_HEADERS {
return Err(format!("more than {MAX_HEADERS} headers"));
}
}
let rest = raw.get(end + 4..).unwrap_or(&[]);
let mut r = Response { status, reason: reason.to_owned(), headers, body: Vec::new(), framing: Framing::Close };
let chunked = r.header("Transfer-Encoding").is_some_and(|v| v.eq_ignore_ascii_case("chunked"));
if chunked {
r.framing = Framing::Chunked;
return match dechunk(rest)? {
Some(body) => {
r.body = body;
Ok(Some(r))
}
None if eof => Err("connection closed inside a chunked body".into()),
None => Ok(None),
};
}
if let Some(v) = r.header("Content-Length") {
let len: usize = v.parse().map_err(|_| format!("bad Content-Length '{v}'"))?;
if len > MAX_RESPONSE_BYTES {
return Err(format!("Content-Length {len} over the cap"));
}
r.framing = Framing::Length;
return match rest.get(..len) {
Some(body) => {
r.body = body.to_vec();
Ok(Some(r))
}
None if eof => Err(format!("connection closed after {} of {len} body bytes", rest.len())),
None => Ok(None),
};
}
if eof {
r.body = rest.to_vec();
Ok(Some(r))
} else {
Ok(None)
}
}
/// The body of a chunked message, or `None` while the last chunk has not arrived.
fn dechunk(mut data: &[u8]) -> Result<Option<Vec<u8>>, String> {
let mut body = Vec::new();
loop {
let Some(nl) = data.windows(2).position(|w| w == b"\r\n") else { return Ok(None) };
let line = std::str::from_utf8(data.get(..nl).unwrap_or(&[])).map_err(|_| "bad chunk size".to_owned())?;
let size_hex = line.split(';').next().unwrap_or("").trim();
if size_hex.is_empty() || size_hex.len() > 8 {
return Err(format!("bad chunk size '{line}'"));
}
let size = usize::from_str_radix(size_hex, 16).map_err(|_| format!("bad chunk size '{line}'"))?;
if body.len() + size > MAX_RESPONSE_BYTES {
return Err("chunked body over the cap".into());
}
let after = data.get(nl + 2..).unwrap_or(&[]);
if size == 0 {
return Ok(Some(body));
}
let Some(chunk) = after.get(..size) else { return Ok(None) };
match after.get(size..size + 2) {
None => return Ok(None),
Some(b"\r\n") => {}
Some(_) => return Err("chunk not followed by CRLF".into()),
}
body.extend_from_slice(chunk);
data = after.get(size + 2..).unwrap_or(&[]);
}
}
/// Reads until [`parse`] has a whole response, the peer closes, or `deadline` passes.
pub fn read_response<R: Read>(r: &mut R, deadline: Instant) -> Result<Response, String> {
let mut raw = Vec::new();
let mut buf = [0u8; 16 * 1024];
loop {
match r.read(&mut buf) {
Ok(0) => return parse(&raw, true)?.ok_or_else(|| "connection closed without an answer".into()),
Ok(n) => {
raw.extend_from_slice(buf.get(..n).unwrap_or(&[]));
if let Some(resp) = parse(&raw, false)? {
return Ok(resp);
}
}
// rustls reports a close without close_notify as UnexpectedEof: the body may still be complete.
Err(e) if e.kind() == io::ErrorKind::UnexpectedEof => {
return parse(&raw, true)?.ok_or_else(|| "connection closed without an answer".into());
}
Err(e) if matches!(e.kind(), io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut) => {}
Err(e) if e.kind() == io::ErrorKind::Interrupted => {}
Err(e) => return Err(format!("read failed: {e}")),
}
if Instant::now() >= deadline {
return Err(format!("no complete answer before the deadline ({} bytes so far)", raw.len()));
}
}
}
/// TLS facts of an HTTPS exchange (U24).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TlsInfo {
pub version: String,
pub suite: String,
}
/// One finished request.
#[derive(Clone, Debug)]
pub struct Exchange {
pub response: Response,
pub elapsed: Duration,
pub tls: Option<TlsInfo>,
}
fn connect(addr: SocketAddr) -> Result<TcpStream, String> {
let s = TcpStream::connect_timeout(&addr, CONNECT_TIMEOUT).map_err(|e| format!("connect to {addr} failed: {e}"))?;
s.set_read_timeout(Some(POLL)).map_err(|e| format!("socket setup failed: {e}"))?;
s.set_write_timeout(Some(CONNECT_TIMEOUT)).map_err(|e| format!("socket setup failed: {e}"))?;
s.set_nodelay(true).map_err(|e| format!("socket setup failed: {e}"))?;
Ok(s)
}
/// `GET path` to `addr`, plain or over TLS with `tls`, answered within `timeout`.
pub fn get(
addr: SocketAddr,
path_and_query: &str,
timeout: Duration,
tls: Option<Arc<ClientConfig>>,
) -> Result<Exchange, String> {
let started = Instant::now();
let deadline = started + timeout;
let mut tcp = connect(addr)?;
let req = request(path_and_query, &addr.to_string());
match tls {
None => {
tcp.write_all(&req).map_err(|e| format!("write failed: {e}"))?;
let response = read_response(&mut tcp, deadline)?;
Ok(Exchange { response, elapsed: started.elapsed(), tls: None })
}
Some(cfg) => {
let name = ServerName::IpAddress(addr.ip().into());
let mut conn = ClientConnection::new(cfg, name).map_err(|e| format!("TLS setup failed: {e}"))?;
while conn.is_handshaking() {
match conn.complete_io(&mut tcp) {
Ok(_) => {}
Err(e) if matches!(e.kind(), io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut) => {
if Instant::now() >= deadline {
return Err("TLS handshake timed out".into());
}
}
Err(e) => return Err(format!("TLS handshake failed: {e}")),
}
}
let info = TlsInfo {
version: conn.protocol_version().map_or_else(|| "?".into(), |v| format!("{v:?}")),
suite: conn.negotiated_cipher_suite().map_or_else(|| "?".into(), |s| format!("{:?}", s.suite())),
};
let mut stream = StreamOwned::new(conn, tcp);
stream.write_all(&req).map_err(|e| format!("write failed: {e}"))?;
stream.flush().map_err(|e| format!("write failed: {e}"))?;
let response = read_response(&mut stream, deadline)?;
Ok(Exchange { response, elapsed: started.elapsed(), tls: Some(info) })
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::net::TcpListener;
#[test]
fn content_length_body() {
let raw = b"HTTP/1.1 200 OK\r\nContent-Type: text/xml\r\nContent-Length: 5\r\n\r\nhelloEXTRA";
let r = parse(raw, false).unwrap().unwrap();
assert_eq!((r.status, r.reason.as_str(), r.framing), (200, "OK", Framing::Length));
assert_eq!(r.body, b"hello");
assert_eq!(r.header("content-type"), Some("text/xml"));
// Cut after "hell": 4 of the 5 body bytes.
let cut = &raw[..raw.len() - 6];
assert_eq!(parse(cut, false).unwrap(), None);
assert!(parse(cut, true).unwrap_err().contains("4 of 5"));
}
#[test]
fn chunked_body() {
let raw = b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n4\r\n<roo\r\n3;x=y\r\nt/>\r\n0\r\n\r\n";
let r = parse(raw, false).unwrap().unwrap();
assert_eq!((r.body.as_slice(), r.framing), (&b"<root/>"[..], Framing::Chunked));
assert_eq!(parse(&raw[..raw.len() - 5], false).unwrap(), None);
assert!(parse(b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\nzz\r\n", false).is_err());
assert!(parse(b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n2\r\nabXX", false).is_err());
}
#[test]
fn close_delimited_body() {
let raw = b"HTTP/1.0 404 Not Found\r\n\r\n<root status_code=\"404\"/>";
assert_eq!(parse(raw, false).unwrap(), None);
let r = parse(raw, true).unwrap().unwrap();
assert_eq!((r.status, r.framing), (404, Framing::Close));
assert_eq!(r.body, b"<root status_code=\"404\"/>");
}
#[test]
fn hostile_answers_are_refused() {
assert!(parse(b"HTTP/2 200 OK\r\n\r\n", true).unwrap_err().contains("status line"));
assert!(parse(b"HTTP/1.1 20x OK\r\n\r\n", true).unwrap_err().contains("status line"));
assert!(parse(b"HTTP/1.1 200 OK\r\nno colon\r\n\r\n", true).unwrap_err().contains("header line"));
assert!(parse(b"HTTP/1.1 200 OK\r\nContent-Length: -1\r\n\r\n", true).unwrap_err().contains("Content-Length"));
assert!(parse(b"HTTP/1.1 200 OK\r\nContent-Length: 99999999\r\n\r\n", true).unwrap_err().contains("cap"));
assert!(parse(&vec![b'a'; MAX_HEAD_BYTES + 1], false).unwrap_err().contains("headers over"));
assert!(parse(b"HTTP/1.1 200", true).unwrap_err().contains("inside the headers"));
let many: String = (0..=MAX_HEADERS).map(|i| format!("X-{i}: 1\r\n")).collect();
assert!(parse(format!("HTTP/1.1 200 OK\r\n{many}\r\n").as_bytes(), true).unwrap_err().contains("headers"));
}
#[test]
fn request_line_and_headers() {
let r = String::from_utf8(request("/serverinfo?uniqueid=AB", "192.0.2.1:47989")).unwrap();
assert!(r.starts_with("GET /serverinfo?uniqueid=AB HTTP/1.1\r\nHost: 192.0.2.1:47989\r\n"));
assert!(r.ends_with("Connection: close\r\n\r\n"));
}
/// The only socket the tests open: a loopback listener on an ephemeral port.
#[test]
fn get_over_loopback() {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
let server = std::thread::spawn(move || {
let (mut s, _) = listener.accept().unwrap();
let mut buf = [0u8; 1024];
let n = s.read(&mut buf).unwrap();
let req = String::from_utf8_lossy(&buf[..n]).into_owned();
s.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 7\r\n\r\n<root/>").unwrap();
req
});
let x = get(addr, "/serverinfo?uniqueid=AB", Duration::from_secs(5), None).unwrap();
assert_eq!((x.response.status, x.response.body.as_slice()), (200, &b"<root/>"[..]));
assert!(x.tls.is_none());
assert!(server.join().unwrap().starts_with("GET /serverinfo?uniqueid=AB HTTP/1.1\r\n"));
}
}
+367
View File
@@ -0,0 +1,367 @@
//! The structured log: one JSON object per line (`log.jsonl` in the run folder), flushed after every record so a
//! crash keeps everything before it.
//!
//! ```text
//! {"n":7,"t_ms":812.441,"step":"rtsp.describe","kind":"recv","u":["U5","U26"],"data":{…}}
//! ```
//!
//! `kind` is one of `send`, `recv`, `note`, `parse_error`, `stop`, `summary`. A `stop` record is the
//! stop-and-report rule of docs/LIVE-INTEROP.md: something unexpected happened, the probe ends the step and the
//! operator reports before changing anything.
//!
//! Secrets: HTTP paths and bodies are redacted by the callers (`crate::redact`), and every line is scanned once more
//! for the hex of each registered secret (the session's `rikey`) before it is written. The PIN is never passed to
//! the log at all.
use std::fs::File;
use std::io::{self, BufWriter, Write};
use std::path::{Path, PathBuf};
use std::time::Instant;
use crate::redact::MARK;
/// Bytes shown per byte field; the rest is cut and marked `truncated`.
pub const MAX_LOGGED_BYTES: usize = 4096;
/// Characters shown per text field.
pub const MAX_LOGGED_TEXT: usize = 64 * 1024;
/// A JSON value, built by the probe and written by [`J::write`].
#[derive(Clone, Debug, PartialEq)]
pub enum J {
Null,
Bool(bool),
U(u64),
I(i64),
F(f64),
S(String),
A(Vec<J>),
O(Vec<(&'static str, J)>),
}
impl J {
pub fn s(v: impl Into<String>) -> Self {
Self::S(v.into())
}
/// A string via `Debug` (for DomiStream's own types, which never print key material).
pub fn dbg(v: &impl std::fmt::Debug) -> Self {
let mut s = format!("{v:?}");
cut(&mut s, MAX_LOGGED_TEXT);
Self::S(s)
}
pub fn write(&self, out: &mut String) {
match self {
Self::Null => out.push_str("null"),
Self::Bool(b) => out.push_str(if *b { "true" } else { "false" }),
Self::U(n) => out.push_str(&n.to_string()),
Self::I(n) => out.push_str(&n.to_string()),
Self::F(f) if f.is_finite() => out.push_str(&format!("{f:.3}")),
Self::F(_) => out.push_str("null"),
Self::S(s) => escape(s, out),
Self::A(items) => {
out.push('[');
for (i, v) in items.iter().enumerate() {
if i > 0 {
out.push(',');
}
v.write(out);
}
out.push(']');
}
Self::O(fields) => {
out.push('{');
for (i, (k, v)) in fields.iter().enumerate() {
if i > 0 {
out.push(',');
}
escape(k, out);
out.push(':');
v.write(out);
}
out.push('}');
}
}
}
}
fn cut(s: &mut String, max: usize) {
if s.len() > max {
let mut end = max;
while !s.is_char_boundary(end) {
end -= 1;
}
s.truncate(end);
s.push_str("…<cut>");
}
}
/// A JSON string literal.
pub fn escape(s: &str, out: &mut String) {
out.push('"');
for c in s.chars() {
match c {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
'\n' => out.push_str("\\n"),
'\r' => out.push_str("\\r"),
'\t' => out.push_str("\\t"),
c if (c as u32) < 0x20 || c == '\u{7f}' => out.push_str(&format!("\\u{:04x}", c as u32)),
c => out.push(c),
}
}
out.push('"');
}
/// Lower-case hex.
pub fn hex(bytes: &[u8]) -> String {
const D: &[u8; 16] = b"0123456789abcdef";
let mut s = String::with_capacity(bytes.len() * 2);
for b in bytes {
s.push(char::from(D[usize::from(b >> 4)]));
s.push(char::from(D[usize::from(b & 0xF)]));
}
s
}
/// `{"len":n,"hex":"…"}`, the hex cut at [`MAX_LOGGED_BYTES`] bytes (`"truncated":true`).
pub fn bytes(b: &[u8]) -> J {
let shown = b.get(..MAX_LOGGED_BYTES).unwrap_or(b);
let mut f = vec![("len", J::U(b.len() as u64)), ("hex", J::S(hex(shown)))];
if shown.len() < b.len() {
f.push(("truncated", J::Bool(true)));
}
J::O(f)
}
/// `{"len":n,"text":"…"}` when `b` is UTF-8 text (tabs and line ends allowed), else [`bytes`].
pub fn text(b: &[u8]) -> J {
match std::str::from_utf8(b) {
Ok(s) if !s.chars().any(|c| c.is_control() && !matches!(c, '\r' | '\n' | '\t')) => {
let mut t = s.to_owned();
cut(&mut t, MAX_LOGGED_TEXT);
J::O(vec![("len", J::U(b.len() as u64)), ("text", J::S(t))])
}
_ => bytes(b),
}
}
/// What a record is.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Kind {
Send,
Recv,
Note,
ParseError,
Stop,
Summary,
}
impl Kind {
pub const fn as_str(self) -> &'static str {
match self {
Self::Send => "send",
Self::Recv => "recv",
Self::Note => "note",
Self::ParseError => "parse_error",
Self::Stop => "stop",
Self::Summary => "summary",
}
}
}
/// One log line, without the trailing newline, with every registered secret's hex replaced by [`MARK`].
pub fn format_line(n: u64, t_ms: f64, step: &str, kind: Kind, us: &[&str], data: &J, secrets: &[String]) -> String {
let rec = J::O(vec![
("n", J::U(n)),
("t_ms", J::F(t_ms)),
("step", J::s(step)),
("kind", J::s(kind.as_str())),
("u", J::A(us.iter().map(|u| J::s(*u)).collect())),
("data", data.clone()),
]);
let mut line = String::new();
rec.write(&mut line);
for s in secrets {
if line.contains(s.as_str()) {
line = line.replace(s.as_str(), MARK);
}
}
line
}
/// The run's log file.
pub struct Log {
out: Option<BufWriter<File>>,
start: Instant,
n: u64,
secrets: Vec<String>,
pub path: PathBuf,
pub stops: u32,
pub parse_errors: u32,
}
impl Log {
/// Creates `path` (it must not exist yet).
pub fn create(path: &Path, start: Instant) -> io::Result<Self> {
let f = File::options().write(true).create_new(true).open(path)?;
Ok(Self {
out: Some(BufWriter::new(f)),
start,
n: 0,
secrets: Vec::new(),
path: path.to_owned(),
stops: 0,
parse_errors: 0,
})
}
/// A log that writes nothing (tests of code that logs).
#[cfg(test)]
pub fn discard() -> Self {
Self {
out: None,
start: Instant::now(),
n: 0,
secrets: Vec::new(),
path: PathBuf::new(),
stops: 0,
parse_errors: 0,
}
}
/// From now on, the hex of `secret` (both cases) never reaches the file.
pub fn register_secret(&mut self, secret: &[u8]) {
let lower = hex(secret);
self.secrets.push(lower.to_ascii_uppercase());
self.secrets.push(lower);
}
/// Milliseconds since the run started.
pub fn t_ms(&self) -> f64 {
self.start.elapsed().as_secs_f64() * 1000.0
}
pub fn record(&mut self, step: &str, kind: Kind, us: &[&str], data: J) {
self.n += 1;
match kind {
Kind::Stop => self.stops += 1,
Kind::ParseError => self.parse_errors += 1,
_ => {}
}
let line = format_line(self.n, self.t_ms(), step, kind, us, &data, &self.secrets);
if let Some(out) = &mut self.out {
// A log that cannot be written is reported once on stderr; the probe goes on.
if writeln!(out, "{line}").and_then(|()| out.flush()).is_err() {
eprintln!("probe: cannot write the log {}", self.path.display());
self.out = None;
}
}
}
pub fn note(&mut self, step: &str, us: &[&str], text: impl Into<String>) {
self.record(step, Kind::Note, us, J::O(vec![("text", J::S(text.into()))]));
}
/// A parser refused something: the error and the bytes that caused it.
pub fn parse_error(&mut self, step: &str, us: &[&str], error: &dyn std::fmt::Display, input: J) {
self.record(step, Kind::ParseError, us, J::O(vec![("error", J::s(error.to_string())), ("input", input)]));
}
/// The stop-and-report rule: records why, and tells the operator on stderr.
pub fn stop(&mut self, step: &str, us: &[&str], reason: impl Into<String>, data: J) {
let reason = reason.into();
eprintln!("STOP AND REPORT [{step}]: {reason}");
eprintln!(" log: {}", self.path.display());
self.record(step, Kind::Stop, us, J::O(vec![("reason", J::S(reason)), ("data", data)]));
}
}
/// `YYYYMMDDTHHMMSSZ` for Unix seconds (UTC), for run folder names.
pub fn utc_stamp(unix_secs: u64) -> String {
let days = (unix_secs / 86_400) as i64;
let rem = unix_secs % 86_400;
// Civil date from days since 1970-01-01 (H. Hinnant's algorithm).
let z = days + 719_468;
let era = z.div_euclid(146_097);
let doe = z.rem_euclid(146_097);
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let d = doy - (153 * mp + 2) / 5 + 1;
let m = if mp < 10 { mp + 3 } else { mp - 9 };
let y = yoe + era * 400 + i64::from(m <= 2);
format!("{y:04}{m:02}{d:02}T{:02}{:02}{:02}Z", rem / 3600, rem % 3600 / 60, rem % 60)
}
#[cfg(test)]
mod tests {
use super::*;
fn line(data: J, secrets: &[String]) -> String {
format_line(3, 12.5, "pair.1", Kind::Send, &["U1", "U2"], &data, secrets)
}
#[test]
fn line_has_the_documented_fields_in_order() {
assert_eq!(
line(J::O(vec![("x", J::U(1))]), &[]),
r#"{"n":3,"t_ms":12.500,"step":"pair.1","kind":"send","u":["U1","U2"],"data":{"x":1}}"#
);
}
#[test]
fn strings_are_escaped() {
let mut s = String::new();
escape("a\"b\\c\nd\u{1}é", &mut s);
assert_eq!(s, r#""a\"b\\c\nd\u0001é""#);
let mut n = String::new();
J::A(vec![J::Null, J::Bool(false), J::I(-2), J::F(f64::NAN)]).write(&mut n);
assert_eq!(n, "[null,false,-2,null]");
}
#[test]
fn registered_secrets_never_reach_a_line() {
let key = [0x5Au8, 0x01, 0xFE, 0x33, 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB];
let mut log = Log::discard();
log.register_secret(&key);
let lower = hex(&key);
let upper = lower.to_ascii_uppercase();
let data = J::O(vec![
("in_bytes", bytes(&[&[1, 2][..], &key, &[3][..]].concat())),
("in_text", J::s(format!("rikey={upper}&x=1"))),
]);
let l = line(data, &log.secrets);
assert!(!l.contains(&lower) && !l.contains(&upper), "{l}");
assert!(l.contains("0102<redacted>03"), "{l}");
assert!(l.contains("rikey=<redacted>&x=1"), "{l}");
}
#[test]
fn byte_fields_are_capped() {
let big = vec![0xABu8; MAX_LOGGED_BYTES + 10];
let mut s = String::new();
bytes(&big).write(&mut s);
assert!(s.starts_with(&format!(r#"{{"len":{},"hex":"abab"#, big.len())));
assert!(s.ends_with(r#","truncated":true}"#));
assert_eq!(s.matches("ab").count(), MAX_LOGGED_BYTES);
}
#[test]
fn text_or_hex() {
let mut s = String::new();
text(b"RTSP/1.0 200 OK\r\nCSeq: 1\r\n\r\n").write(&mut s);
assert_eq!(s, r#"{"len":28,"text":"RTSP/1.0 200 OK\r\nCSeq: 1\r\n\r\n"}"#);
let mut b = String::new();
text(&[0x80, 0x00]).write(&mut b);
assert_eq!(b, r#"{"len":2,"hex":"8000"}"#);
}
#[test]
fn utc_stamps() {
assert_eq!(utc_stamp(0), "19700101T000000Z");
assert_eq!(utc_stamp(951_782_400), "20000229T000000Z");
assert_eq!(utc_stamp(951_782_400 + 86_399), "20000229T235959Z");
assert_eq!(utc_stamp(946_684_799), "19991231T235959Z");
}
}
+247
View File
@@ -0,0 +1,247 @@
//! gs-probe (`probe`): a desktop GameStream client that drives DomiStream's state machines over real sockets
//! against ONE host address, and writes a structured log of every step for the live interop sitting
//! (`docs/LIVE-INTEROP.md`). A dev tool, never shipped: it prints the pairing PIN for the operator to submit through
//! Sunshine's API.
//!
//! Exit codes: 0 done, 1 error, 2 bad command line, 3 stop and report (something unexpected; see the log).
mod args;
mod commands;
mod dump;
mod fec;
mod http;
mod log;
mod redact;
mod rng;
mod rtsp;
mod state;
mod stream;
mod tls;
use std::fs;
use std::net::{IpAddr, SocketAddr};
use std::path::{Path, PathBuf};
use std::process::ExitCode;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use domistream::http::{HttpRequest, Scheme};
use domistream::pairing::ServerCert;
use args::{Command, Options};
use log::{J, Kind, Log};
/// Everything a network command needs.
pub struct Ctx {
pub opts: Options,
/// `--host`: the one host.
pub host: IpAddr,
/// Where sockets connect: `--relay` when given, else `--host`.
pub connect: IpAddr,
pub out: PathBuf,
pub run_dir: PathBuf,
pub log: Log,
pub rng: rng::OsRandom,
pub id: state::Identity,
pub host_cert: Option<ServerCert>,
pub epoch: Instant,
}
/// An HTTP body for the log: text (secret XML elements redacted) or hex.
pub fn body_j(body: &[u8]) -> J {
match std::str::from_utf8(body) {
Ok(s) => log::text(redact::xml(s).as_bytes()),
Err(_) => log::bytes(body),
}
}
impl Ctx {
/// Sends one DomiStream-built request and logs both directions (redacted). HTTPS pins `pinned` (pairing step 5)
/// or the stored host certificate.
pub fn http(
&mut self,
step: &str,
us: &[&str],
req: &HttpRequest,
pinned: Option<&ServerCert>,
) -> Result<http::Exchange, String> {
let (port, tls) = match req.scheme {
Scheme::Http => (self.opts.http_port, None),
Scheme::Https => {
let cert = pinned.or(self.host_cert.as_ref()).ok_or("not paired yet: run `probe pair` first")?;
(self.opts.https_port, Some(tls::client_config(&self.id.client, cert)?))
}
};
let addr = SocketAddr::new(self.connect, port);
let timeout = req.timeout.unwrap_or(Duration::from_secs(10));
self.log.record(
step,
Kind::Send,
us,
J::O(vec![
("scheme", J::dbg(&req.scheme)),
("to", J::s(addr.to_string())),
("path", J::s(redact::query(&req.path_and_query))),
("timeout_ms", J::U(u64::try_from(timeout.as_millis()).unwrap_or(u64::MAX))),
]),
);
match http::get(addr, &req.path_and_query, timeout, tls) {
Ok(x) => {
let r = &x.response;
self.log.record(
step,
Kind::Recv,
us,
J::O(vec![
("status", J::U(u64::from(r.status))),
("reason", J::s(r.reason.clone())),
("elapsed_ms", J::F(x.elapsed.as_secs_f64() * 1000.0)),
("framing", J::dbg(&r.framing)),
(
"headers",
J::A(r.headers.iter().map(|(n, v)| J::A(vec![J::s(n.clone()), J::s(v.clone())])).collect()),
),
(
"tls",
x.tls.as_ref().map_or(J::Null, |t| {
J::O(vec![("version", J::s(t.version.clone())), ("suite", J::s(t.suite.clone()))])
}),
),
("body", body_j(&r.body)),
]),
);
Ok(x)
}
Err(e) => {
let m = format!("{} {addr}: {e}", req.path_and_query.split('?').next().unwrap_or(""));
self.log.stop(step, us, m.clone(), J::Null);
Err(m)
}
}
}
}
/// U16 from a dump file, as a log value.
pub fn solve_audio_file(path: &Path) -> Result<J, String> {
let len = fs::metadata(path).map_err(|e| format!("{}: {e}", path.display()))?.len();
if len > dump::MAX_DUMP_BYTES as u64 {
return Err(format!("{}: larger than {} bytes", path.display(), dump::MAX_DUMP_BYTES));
}
let data = fs::read(path).map_err(|e| format!("{}: {e}", path.display()))?;
let records = dump::decode(&data)?;
let datagrams: Vec<Vec<u8>> = records.into_iter().map(|(_, b)| b).collect();
let r = fec::solve_audio(&datagrams);
Ok(J::O(vec![
("report", J::dbg(&r)),
("matrix", r.matrix().map_or(J::Null, |m| J::s(log::hex(&m)))),
("matrix_is_mds", r.matrix_is_mds().map_or(J::Null, J::Bool)),
]))
}
fn run(cmd: &Command, opts: Options) -> Result<u8, String> {
if let Command::SolveAudioFec { dump } = cmd {
let j = solve_audio_file(dump)?;
let mut s = String::new();
j.write(&mut s);
println!("{s}");
return Ok(0);
}
let (Some(host), Some(out)) = (opts.host, opts.out.clone()) else {
return Err("--host and --out are required".into());
};
let connect = opts.connect_ip().unwrap_or(host);
let epoch = Instant::now();
let now = SystemTime::now().duration_since(UNIX_EPOCH).map_err(|_| "the clock is before 1970")?.as_secs();
let run_dir = out.join("runs").join(format!("{}-{}", log::utc_stamp(now), cmd.name()));
fs::create_dir_all(&run_dir).map_err(|e| format!("{}: {e}", run_dir.display()))?;
let mut log = Log::create(&run_dir.join("log.jsonl"), epoch).map_err(|e| format!("log: {e}"))?;
println!(
"probe {}: host {host}{}; log {}",
cmd.name(),
opts.relay.map_or(String::new(), |r| format!(" via relay {r}")),
log.path.display()
);
log.record(
"start",
Kind::Note,
&[],
J::O(vec![
("probe", J::s(env!("CARGO_PKG_VERSION"))),
("command", J::dbg(cmd)),
("host", J::s(host.to_string())),
("connect", J::s(connect.to_string())),
("options", J::dbg(&opts)),
]),
);
let mut rng = rng::OsRandom::new();
let id = state::load_or_create(&out, &opts.name, &mut rng)?;
log.note(
"identity",
&["U2"],
format!(
"{} client identity: uniqueid {}, certificate sha256 {} (test-only key in {}, never logged)",
if id.created { "generated a new" } else { "loaded the" },
id.unique_id,
rng::sha256_hex(id.client.cert_der()),
state::identity_dir(&out).display()
),
);
let host_cert = match state::load_host_cert(&out)? {
Some((cert, paired_at)) => {
if paired_at != host.to_string() {
log.note(
"identity",
&[],
format!("the pinned host certificate was paired at '{paired_at}', not {host}"),
);
}
Some(cert)
}
None => None,
};
let mut ctx = Ctx { opts, host, connect, out, run_dir, log, rng, id, host_cert, epoch };
let result = match cmd {
Command::ServerInfo => commands::serverinfo(&mut ctx),
Command::Pair => commands::pair(&mut ctx),
Command::Apps => commands::apps(&mut ctx),
Command::Launch { app_id } => stream::launch(&mut ctx, *app_id),
Command::Quit => commands::quit(&mut ctx),
Command::Unpair => commands::unpair(&mut ctx),
Command::SolveAudioFec { .. } => Ok(()),
};
let stops = ctx.log.stops;
ctx.log.record(
"end",
Kind::Note,
&[],
J::O(vec![
("ok", J::Bool(result.is_ok())),
("error", result.as_ref().err().map_or(J::Null, |e| J::s(e.clone()))),
("stops", J::U(u64::from(stops))),
("parse_errors", J::U(u64::from(ctx.log.parse_errors))),
]),
);
println!("log: {}", ctx.log.path.display());
match result {
_ if stops > 0 => Ok(3),
Ok(()) => Ok(0),
Err(e) => Err(e),
}
}
fn main() -> ExitCode {
let argv: Vec<String> = std::env::args().skip(1).collect();
let inv = match args::parse(&argv) {
Ok(i) => i,
Err(e) => {
eprintln!("probe: {e}\n\n{}", args::USAGE);
return ExitCode::from(2);
}
};
match run(&inv.command, inv.options) {
Ok(code) => ExitCode::from(code),
Err(e) => {
eprintln!("probe: {e}");
ExitCode::from(1)
}
}
}
+111
View File
@@ -0,0 +1,111 @@
//! Hides secrets before anything reaches the log or the terminal: the stream key (`rikey`) and the pairing values
//! that, together with the PIN, would let someone redo the pairing proofs. Names stay, values go, so the log still
//! shows which parameters were sent and in which order (U1, U4).
/// Query parameters whose values never reach the log.
pub const SECRET_PARAMS: [&str; 6] =
["rikey", "salt", "clientchallenge", "serverchallengeresp", "clientpairingsecret", "pin"];
/// XML elements whose text never reaches the log.
pub const SECRET_ELEMENTS: [&str; 2] = ["challengeresponse", "pairingsecret"];
/// What replaces a secret value.
pub const MARK: &str = "<redacted>";
/// `path?k=v&…` with the value of every [`SECRET_PARAMS`] name replaced by [`MARK`] (names compared ignoring case).
pub fn query(path_and_query: &str) -> String {
let Some((path, q)) = path_and_query.split_once('?') else { return path_and_query.to_owned() };
let parts: Vec<String> = q
.split('&')
.map(|kv| match kv.split_once('=') {
Some((k, _)) if SECRET_PARAMS.iter().any(|s| s.eq_ignore_ascii_case(k)) => format!("{k}={MARK}"),
_ => kv.to_owned(),
})
.collect();
format!("{path}?{}", parts.join("&"))
}
/// `text` with the content of every `<name>…</…>` of [`SECRET_ELEMENTS`] replaced by [`MARK`] (names compared
/// ignoring case; an element left open is redacted to the end).
pub fn xml(text: &str) -> String {
let lower = text.to_ascii_lowercase();
let mut out = String::with_capacity(text.len());
let mut i = 0;
'scan: while i < text.len() {
for name in SECRET_ELEMENTS {
let open = format!("<{name}>");
if lower.get(i..).is_some_and(|rest| rest.starts_with(&open)) {
out.push_str(text.get(i..i + open.len()).unwrap_or(""));
out.push_str(MARK);
i += open.len();
i = lower.get(i..).and_then(|rest| rest.find("</")).map_or(text.len(), |p| i + p);
continue 'scan;
}
}
let Some(c) = text.get(i..).and_then(|rest| rest.chars().next()) else { break };
out.push(c);
i += c.len_utf8();
}
out
}
#[cfg(test)]
mod tests {
use super::*;
use domistream::SessionKeys;
use domistream::http::launch::{AudioLayout, LaunchParams, launch_request};
#[test]
fn launch_key_is_hidden_and_the_rest_stays() {
assert_eq!(
query("/launch?uniqueid=0123&appid=1&rikey=00112233445566778899aabbccddeeff&rikeyid=7"),
"/launch?uniqueid=0123&appid=1&rikey=<redacted>&rikeyid=7"
);
}
#[test]
fn a_real_launch_request_never_shows_its_key() {
let keys = SessionKeys { rikey: [0xA5; 16], rikeyid: 42 };
let params = LaunchParams {
app_id: 5,
width: 1920,
height: 1080,
fps: 60,
keys,
hdr: false,
audio: AudioLayout::Stereo,
};
let req = launch_request(&params, "0123456789ABCDEF").unwrap();
let shown = query(&req.path_and_query);
assert!(!shown.to_ascii_lowercase().contains("a5a5a5a5"), "{shown}");
assert!(shown.contains("rikey=<redacted>") && shown.contains("rikeyid=42") && shown.contains("appid=5"));
}
#[test]
fn pairing_values_are_hidden_but_names_and_certs_stay() {
assert_eq!(
query("/pair?uniqueid=1&devicename=x&updateState=1&phrase=getservercert&salt=ABCD&clientcert=2D2D"),
"/pair?uniqueid=1&devicename=x&updateState=1&phrase=getservercert&salt=<redacted>&clientcert=2D2D"
);
assert_eq!(query("/pair?uniqueid=1&ClientChallenge=ff"), "/pair?uniqueid=1&ClientChallenge=<redacted>");
assert_eq!(
xml("<root status_code=\"200\"><paired>1</paired><pairingsecret>ffee</pairingsecret></root>"),
"<root status_code=\"200\"><paired>1</paired><pairingsecret><redacted></pairingsecret></root>"
);
assert_eq!(
xml("<root><challengeresponse>0011</challengeresponse><plaincert>2D2D</plaincert></root>"),
"<root><challengeresponse><redacted></challengeresponse><plaincert>2D2D</plaincert></root>"
);
}
#[test]
fn lookalikes_and_plain_text_are_untouched() {
assert_eq!(query("/x?rikeyid=5&nosalt=1&pinned=2"), "/x?rikeyid=5&nosalt=1&pinned=2");
assert_eq!(query("/serverinfo"), "/serverinfo");
assert_eq!(xml("<root><hostname>PC é</hostname></root>"), "<root><hostname>PC é</hostname></root>");
}
#[test]
fn an_open_element_is_redacted_to_the_end() {
assert_eq!(xml("<challengeresponse>abc"), "<challengeresponse><redacted>");
assert_eq!(query("?rikey=abc"), "?rikey=<redacted>");
}
}
+28
View File
@@ -0,0 +1,28 @@
//! DomiStream's randomness comes from the caller; the probe hands it the OS generator.
use domistream::RandomSource;
use ring::rand::{SecureRandom, SystemRandom};
/// The operating system's cryptographic generator.
pub struct OsRandom(SystemRandom);
impl OsRandom {
pub fn new() -> Self {
Self(SystemRandom::new())
}
}
impl RandomSource for OsRandom {
fn fill(&mut self, dest: &mut [u8]) {
// Keys, salts and the PIN depend on this; without the OS generator nothing may go on.
if self.0.fill(dest).is_err() {
eprintln!("probe: the OS random generator failed; stopping");
std::process::exit(1);
}
}
}
/// SHA-256 of `data`, as lower-case hex (certificate fingerprints in the log).
pub fn sha256_hex(data: &[u8]) -> String {
crate::log::hex(ring::digest::digest(&ring::digest::SHA256, data).as_ref())
}
+258
View File
@@ -0,0 +1,258 @@
//! Drives DomiStream's `RtspClient` over real TCP and records what U5 needs: whether answers carry
//! `Content-Length`, whether the host closes the connection after each answer, and every header it sends.
use std::io::{self, Read, Write};
use std::net::{IpAddr, SocketAddr, TcpStream};
use std::time::{Duration, Instant};
use domistream::rtsp::client::{RtspClientState, StreamConfig};
use domistream::rtsp::{DEFAULT_RTSP_PORT, NegotiatedStream, RtspClient, RtspFramer, RtspProgress, parse_response};
use crate::log::{J, Kind, Log, text};
/// A whole exchange may take this long.
const ANSWER_TIMEOUT: Duration = Duration::from_secs(15);
/// With headers in and no `Content-Length`, an open connection that stays quiet this long ends the message.
const IDLE_CUT: Duration = Duration::from_secs(2);
const POLL: Duration = Duration::from_millis(200);
/// Where to connect for RTSP and the URL the requests name.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Target {
pub addr: SocketAddr,
pub url: String,
/// Set when the host named another address than the one the probe talks to (it is never used).
pub foreign_host: Option<String>,
/// `sessionUrl0` was missing and port 48010 was assumed (U4).
pub assumed_port: bool,
}
/// The RTSP target from the launch answer. The probe only ever connects to `connect_ip`; the host part of
/// `sessionUrl0` is compared with `host` and otherwise ignored.
pub fn target(session_url: Option<&str>, host: IpAddr, connect_ip: IpAddr) -> Result<Target, String> {
let Some(url) = session_url else {
let url = format!("rtsp://{}", SocketAddr::new(host, DEFAULT_RTSP_PORT));
return Ok(Target {
addr: SocketAddr::new(connect_ip, DEFAULT_RTSP_PORT),
url,
foreign_host: None,
assumed_port: true,
});
};
let rest = url.strip_prefix("rtsp://").ok_or_else(|| format!("sessionUrl0 '{url}' is not rtsp://"))?;
let authority = rest.split('/').next().unwrap_or("");
let (h, p) = authority.rsplit_once(':').ok_or_else(|| format!("sessionUrl0 '{url}' has no port"))?;
let port: u16 = p.parse().map_err(|_| format!("sessionUrl0 '{url}' has a bad port"))?;
if port == 0 {
return Err(format!("sessionUrl0 '{url}' has port 0"));
}
let named = h.trim_start_matches('[').trim_end_matches(']');
let foreign_host = match named.parse::<IpAddr>() {
Ok(ip) if ip == host => None,
_ => Some(named.to_owned()),
};
Ok(Target { addr: SocketAddr::new(connect_ip, port), url: url.to_owned(), foreign_host, assumed_port: false })
}
fn state_name(s: RtspClientState) -> &'static str {
match s {
RtspClientState::Options => "options",
RtspClientState::Describe => "describe",
RtspClientState::SetupAudio => "setup_audio",
RtspClientState::SetupVideo => "setup_video",
RtspClientState::SetupControl => "setup_control",
RtspClientState::Announce => "announce",
RtspClientState::Play => "play",
RtspClientState::Ready => "ready",
RtspClientState::Failed => "failed",
}
}
fn unknowns(s: RtspClientState) -> &'static [&'static str] {
match s {
RtspClientState::Describe => &["U5", "U26"],
RtspClientState::SetupAudio | RtspClientState::SetupVideo | RtspClientState::SetupControl => &["U5", "U7"],
RtspClientState::Announce => &["U5", "U6"],
_ => &["U5"],
}
}
/// How an answer's end was found.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum End {
/// Headers plus `Content-Length` (the connection stays open).
Length,
/// The host closed the connection.
Closed,
/// No `Content-Length`; the open connection went quiet ([`IDLE_CUT`]).
Idle,
}
fn connect(addr: SocketAddr) -> io::Result<TcpStream> {
let s = TcpStream::connect_timeout(&addr, Duration::from_secs(5))?;
s.set_read_timeout(Some(POLL))?;
s.set_nodelay(true)?;
Ok(s)
}
fn read_answer(s: &mut TcpStream) -> Result<(Vec<u8>, End), String> {
let started = Instant::now();
let mut last_data = Instant::now();
let mut framer = RtspFramer::new();
let mut buf = [0u8; 8192];
loop {
match s.read(&mut buf) {
Ok(0) => {
return match framer.finish() {
Ok(Some(m)) => Ok((m, End::Closed)),
Ok(None) => Err("closed with no answer".into()),
Err(e) => Err(format!("closed inside an answer: {e}")),
};
}
Ok(n) => {
framer.push(buf.get(..n).unwrap_or(&[])).map_err(|e| e.to_string())?;
if let Some(m) = framer.next_message().map_err(|e| e.to_string())? {
return Ok((m, End::Length));
}
last_data = Instant::now();
}
Err(e) if matches!(e.kind(), io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut) => {
if framer.buffered() > 0 && last_data.elapsed() >= IDLE_CUT {
// Complete headers without Content-Length: the message ends here. Otherwise keep waiting.
if let Ok(Some(m)) = framer.finish() {
return Ok((m, End::Idle));
}
}
}
Err(e) if e.kind() == io::ErrorKind::Interrupted => {}
Err(e) => return Err(format!("read failed: {e}")),
}
if started.elapsed() >= ANSWER_TIMEOUT {
return Err(format!(
"no complete answer within {} s ({} bytes buffered)",
ANSWER_TIMEOUT.as_secs(),
framer.buffered()
));
}
}
}
/// OPTIONS … PLAY. Every request and answer goes to the log in full (RTSP carries no secrets).
pub fn negotiate(log: &mut Log, t: &Target, config: StreamConfig) -> Result<NegotiatedStream, String> {
let mut client = RtspClient::new(&t.url, config).map_err(|e| format!("rtsp setup: {e}"))?;
let mut conn: Option<TcpStream> = None;
let mut connections = 0u32;
while let Some(req) = client.poll_request() {
let state = client.state();
let step = format!("rtsp.{}", state_name(state));
let us = unknowns(state);
log.record(&step, Kind::Send, us, J::O(vec![("to", J::s(t.addr.to_string())), ("message", text(&req))]));
let mut retried = false;
let (answer, end) = loop {
let reused = conn.is_some();
if conn.is_none() {
let s = connect(t.addr).map_err(|e| {
let m = format!("RTSP connect to {} failed: {e}", t.addr);
log.stop(&step, us, m.clone(), J::Null);
m
})?;
connections += 1;
log.note(&step, &["U5"], format!("TCP connection #{connections} to {}", t.addr));
conn = Some(s);
}
let Some(s) = conn.as_mut() else { return Err("no RTSP connection".into()) };
let result = s.write_all(&req).map_err(|e| format!("write failed: {e}")).and_then(|()| read_answer(s));
match result {
Ok(x) => break x,
Err(e) if reused && !retried => {
log.note(
&step,
&["U5"],
format!("the kept connection failed ({e}); the host closes between requests; reconnecting"),
);
conn = None;
retried = true;
}
Err(e) => {
let m = format!("RTSP {}: {e}", state_name(state));
log.stop(&step, us, m.clone(), J::Null);
return Err(m);
}
}
};
if end == End::Closed {
conn = None;
}
let parsed = parse_response(&answer).ok();
let has_length =
parsed.as_ref().is_some_and(|r| r.headers.iter().any(|(n, _)| n.eq_ignore_ascii_case("content-length")));
let headers = parsed
.map(|r| J::A(r.headers.iter().map(|(n, v)| J::A(vec![J::s(n.clone()), J::s(v.clone())])).collect()))
.unwrap_or(J::Null);
log.record(
&step,
Kind::Recv,
us,
J::O(vec![
("end", J::s(format!("{end:?}"))),
("content_length_header", J::Bool(has_length)),
("headers", headers),
("message", text(&answer)),
]),
);
match client.handle_response(&answer) {
Ok(RtspProgress::Continue) => {}
Ok(RtspProgress::Ready(n)) => {
log.note("rtsp.ready", &["U5"], format!("negotiated over {connections} TCP connection(s)"));
return Ok(n);
}
Err(e) => {
log.parse_error(&step, us, &e, text(&answer));
let m = format!("RTSP {} answer refused: {e}", state_name(state));
log.stop(&step, us, m.clone(), J::Null);
return Err(m);
}
}
}
Err("RTSP ended without a request to send".into())
}
#[cfg(test)]
mod tests {
use super::*;
fn ip(s: &str) -> IpAddr {
s.parse().unwrap()
}
#[test]
fn session_url_port_is_used_with_the_given_address_only() {
let t = target(Some("rtsp://192.168.100.140:48010"), ip("192.168.100.140"), ip("192.168.100.140")).unwrap();
assert_eq!((t.addr, t.foreign_host, t.assumed_port), ("192.168.100.140:48010".parse().unwrap(), None, false));
let t = target(Some("rtsp://10.0.0.9:48011"), ip("192.168.100.140"), ip("192.168.100.140")).unwrap();
assert_eq!(t.addr, "192.168.100.140:48011".parse().unwrap());
assert_eq!(t.foreign_host.as_deref(), Some("10.0.0.9"));
assert_eq!(t.url, "rtsp://10.0.0.9:48011");
}
#[test]
fn relay_and_ipv6() {
let t = target(Some("rtsp://[::1]:48010"), ip("::1"), ip("127.0.0.1")).unwrap();
assert_eq!((t.addr, t.foreign_host), ("127.0.0.1:48010".parse().unwrap(), None));
}
#[test]
fn missing_session_url_assumes_48010() {
let t = target(None, ip("192.168.100.140"), ip("192.168.100.140")).unwrap();
assert_eq!((t.url.as_str(), t.assumed_port), ("rtsp://192.168.100.140:48010", true));
}
#[test]
fn bad_session_urls_are_refused() {
let h = ip("192.168.100.140");
assert!(target(Some("http://x:1"), h, h).is_err());
assert!(target(Some("rtsp://x"), h, h).is_err());
assert!(target(Some("rtsp://x:0"), h, h).is_err());
assert!(target(Some("rtsp://x:99999"), h, h).is_err());
}
}
+147
View File
@@ -0,0 +1,147 @@
//! The probe's own state in `--out/identity/`: its client id, its test-only key and certificate (generated on the
//! first run), and the host certificate pinned by `probe pair`. Nothing here is a real device's key; the folder
//! stays out of git and is deleted after the sitting.
use std::fs;
use std::io::Write;
use std::net::IpAddr;
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};
use domistream::RandomSource;
use domistream::pairing::{ClientIdentity, ServerCert};
/// Largest state file read back.
const MAX_STATE_FILE: u64 = 16 * 1024;
pub const UNIQUE_ID_FILE: &str = "uniqueid.txt";
pub const CERT_FILE: &str = "client-cert.der";
pub const KEY_FILE: &str = "client-key.pk8";
pub const HOST_CERT_FILE: &str = "host-cert.der";
pub const HOST_ADDR_FILE: &str = "host-address.txt";
pub fn identity_dir(out: &Path) -> PathBuf {
out.join("identity")
}
fn read_capped(path: &Path) -> Result<Vec<u8>, String> {
let len = fs::metadata(path).map_err(|e| format!("{}: {e}", path.display()))?.len();
if len > MAX_STATE_FILE {
return Err(format!("{}: larger than {MAX_STATE_FILE} bytes", path.display()));
}
fs::read(path).map_err(|e| format!("{}: {e}", path.display()))
}
fn write_new(path: &Path, data: &[u8]) -> Result<(), String> {
let mut f =
fs::File::options().write(true).create_new(true).open(path).map_err(|e| format!("{}: {e}", path.display()))?;
f.write_all(data).and_then(|()| f.sync_all()).map_err(|e| format!("{}: {e}", path.display()))
}
/// 16 upper-case hex characters, as the crate's own clients use.
pub fn new_unique_id(rng: &mut dyn RandomSource) -> String {
let mut b = [0u8; 8];
rng.fill(&mut b);
crate::log::hex(&b).to_ascii_uppercase()
}
pub fn valid_unique_id(s: &str) -> bool {
s.len() == 16 && s.bytes().all(|b| b.is_ascii_hexdigit())
}
/// The probe's identity.
pub struct Identity {
pub unique_id: String,
pub client: ClientIdentity,
/// Generated by this run (else loaded).
pub created: bool,
}
/// Loads the identity, or makes one on the first run. Never prints or logs the key.
pub fn load_or_create(out: &Path, common_name: &str, rng: &mut dyn RandomSource) -> Result<Identity, String> {
let dir = identity_dir(out);
fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?;
let (id_path, cert_path, key_path) = (dir.join(UNIQUE_ID_FILE), dir.join(CERT_FILE), dir.join(KEY_FILE));
if cert_path.exists() || key_path.exists() || id_path.exists() {
let unique_id = String::from_utf8(read_capped(&id_path)?).map_err(|_| "uniqueid.txt is not text".to_owned())?;
let unique_id = unique_id.trim().to_owned();
if !valid_unique_id(&unique_id) {
return Err(format!("{}: not 16 hex characters", id_path.display()));
}
let client = ClientIdentity::from_der(&read_capped(&cert_path)?, &read_capped(&key_path)?)
.map_err(|e| format!("stored identity refused: {e}"))?;
return Ok(Identity { unique_id, client, created: false });
}
let now = SystemTime::now().duration_since(UNIX_EPOCH).map_err(|_| "the clock is before 1970".to_owned())?;
// A day of slack for a host whose clock is behind.
let not_before = i64::try_from(now.as_secs()).unwrap_or(i64::MAX) - 86_400;
let client = ClientIdentity::generate(rng, common_name, not_before).map_err(|e| format!("key generation: {e}"))?;
let unique_id = new_unique_id(rng);
write_new(&cert_path, client.cert_der())?;
write_new(&key_path, client.key_pkcs8_der())?;
write_new(&id_path, unique_id.as_bytes())?;
Ok(Identity { unique_id, client, created: true })
}
/// The pinned host certificate and the address it was paired at, if `probe pair` succeeded before.
pub fn load_host_cert(out: &Path) -> Result<Option<(ServerCert, String)>, String> {
let dir = identity_dir(out);
let path = dir.join(HOST_CERT_FILE);
if !path.exists() {
return Ok(None);
}
let cert =
ServerCert::from_der(&read_capped(&path)?).map_err(|e| format!("stored host certificate refused: {e}"))?;
let addr = read_capped(&dir.join(HOST_ADDR_FILE))
.map(|b| String::from_utf8_lossy(&b).trim().to_owned())
.unwrap_or_default();
Ok(Some((cert, addr)))
}
/// Stores the host certificate after pairing (replacing an older one).
pub fn save_host_cert(out: &Path, cert: &ServerCert, host: IpAddr) -> Result<(), String> {
let dir = identity_dir(out);
let (path, addr) = (dir.join(HOST_CERT_FILE), dir.join(HOST_ADDR_FILE));
for p in [&path, &addr] {
if p.exists() {
fs::remove_file(p).map_err(|e| format!("{}: {e}", p.display()))?;
}
}
write_new(&path, cert.der())?;
write_new(&addr, host.to_string().as_bytes())
}
/// Forgets the host certificate (after `probe unpair`).
pub fn forget_host_cert(out: &Path) -> Result<(), String> {
let dir = identity_dir(out);
for p in [dir.join(HOST_CERT_FILE), dir.join(HOST_ADDR_FILE)] {
if p.exists() {
fs::remove_file(&p).map_err(|e| format!("{}: {e}", p.display()))?;
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
struct Counter(u8);
impl RandomSource for Counter {
fn fill(&mut self, dest: &mut [u8]) {
for b in dest {
self.0 = self.0.wrapping_add(0x3B);
*b = self.0;
}
}
}
#[test]
fn unique_ids_are_16_upper_hex() {
let id = new_unique_id(&mut Counter(0));
assert!(valid_unique_id(&id), "{id}");
assert_eq!(id, id.to_ascii_uppercase());
assert!(!valid_unique_id("0123"));
assert!(!valid_unique_id("0123456789ABCDEG"));
}
}
File diff suppressed because it is too large Load Diff
+76
View File
@@ -0,0 +1,76 @@
//! HTTPS as a GameStream client does it: the probe presents its own client certificate and accepts exactly the host
//! certificate it pinned while pairing (`plaincert`), byte for byte (`ServerCert::matches`). Handshake signatures
//! are still checked against that certificate's key.
use std::sync::Arc;
use domistream::pairing::{ClientIdentity, ServerCert};
use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier};
use rustls::crypto::{WebPkiSupportedAlgorithms, verify_tls12_signature, verify_tls13_signature};
use rustls::pki_types::{CertificateDer, PrivateKeyDer, PrivatePkcs8KeyDer, ServerName, UnixTime};
use rustls::{ClientConfig, DigitallySignedStruct, SignatureScheme};
/// Accepts exactly the pinned host certificate.
#[derive(Debug)]
struct PinnedHost {
pinned: ServerCert,
algs: WebPkiSupportedAlgorithms,
}
impl ServerCertVerifier for PinnedHost {
fn verify_server_cert(
&self,
end_entity: &CertificateDer<'_>,
_intermediates: &[CertificateDer<'_>],
_server_name: &ServerName<'_>,
_ocsp_response: &[u8],
_now: UnixTime,
) -> Result<ServerCertVerified, rustls::Error> {
match self.pinned.matches(end_entity.as_ref()) {
Ok(true) => Ok(ServerCertVerified::assertion()),
_ => {
Err(rustls::Error::General("the host presented another certificate than the one it paired with".into()))
}
}
}
fn verify_tls12_signature(
&self,
message: &[u8],
cert: &CertificateDer<'_>,
dss: &DigitallySignedStruct,
) -> Result<HandshakeSignatureValid, rustls::Error> {
verify_tls12_signature(message, cert, dss, &self.algs)
}
fn verify_tls13_signature(
&self,
message: &[u8],
cert: &CertificateDer<'_>,
dss: &DigitallySignedStruct,
) -> Result<HandshakeSignatureValid, rustls::Error> {
verify_tls13_signature(message, cert, dss, &self.algs)
}
fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
self.algs.supported_schemes()
}
}
/// A client configuration presenting `identity` and pinning `host`. TLS 1.2 and 1.3 are both offered (U24 is
/// whatever the host picks; the log records it).
pub fn client_config(identity: &ClientIdentity, host: &ServerCert) -> Result<Arc<ClientConfig>, String> {
let provider = Arc::new(rustls::crypto::ring::default_provider());
let algs = provider.signature_verification_algorithms;
let cert = CertificateDer::from(identity.cert_der().to_vec());
let key = PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(identity.key_pkcs8_der().to_vec()));
let cfg = ClientConfig::builder_with_provider(provider)
.with_safe_default_protocol_versions()
.map_err(|e| format!("TLS setup failed: {e}"))?
.dangerous()
.with_custom_certificate_verifier(Arc::new(PinnedHost { pinned: host.clone(), algs }))
.with_client_auth_cert(vec![cert], key)
// The error text never carries key bytes.
.map_err(|e| format!("TLS client certificate refused: {e}"))?;
Ok(Arc::new(cfg))
}