Compare commits

...

28 Commits

Author SHA1 Message Date
mnovak 597484425e [repo] Docs: L2 demo measurement of Arena Domi Remote against lumen-host (RTSP read-to-close, ANNOUNCE attributes) [L1] 2026-12-04 15:29:58 +01:00
mnovak 0d45628c4e [repo] Merge: release/stream-v0.2.1 (stream-v0.2.1, PR #16) 2026-12-04 14:29:18 +01:00
mnovak 25557d4c38 [repo] Release: version 0.2.1 (empty-body START_B, PERIODIC_PING, IDR request), handover 2026-12-04 14:29:10 +01:00
mnovak 9434d16422 [repo] Merge: feature/control-empty-bodies (empty-body START_B, PERIODIC_PING, IDR request, PR #15) 2026-12-04 13:46:32 +01:00
mnovak 4300b6b7fb [domistream] Control: START_B, PERIODIC_PING and the IDR request with empty bodies (PROTOCOL.md 3.3); START_A stays refused 2026-12-04 13:46:12 +01:00
mnovak 66679229db [domistream] Control: tests first, START_B, PERIODIC_PING and the IDR request with empty bodies (START_A stays refused) 2026-12-04 13:45:04 +01:00
mnovak 51db5a962b [repo] Merge: feature/host-session (session test, fixes, mutation, L1 measurement, 0.2.0, PR #14) 2026-12-04 13:40:12 +01:00
mnovak a907f705f1 [repo] Docs: the L1 black-box measurement of Arena Domi Remote against lumen-host [L1]; handover evidence (422 tests, mutation 26/27 + 1 equivalent, host_pairing 601 s) 2026-12-04 13:40:02 +01:00
mnovak 1f95cc8db4 [repo] Release: version 0.2.0 (client and host); const assertions for the applist cap (clippy) 2026-12-04 13:31:17 +01:00
mnovak 1fca3abd49 [repo] Mutation: host rows M25-M51 (26 caught, 1 equivalent) 2026-12-04 13:28:50 +01:00
mnovak c2e3c28ed6 [domistream] ENet host: test that a ping before the verify ack is not acknowledged (kills mutant M36) 2026-12-04 13:28:50 +01:00
mnovak 110eed8c14 [repo] Docs: host side overview in PROTOCOL.md, README status and the stream-v0.2.0 handover (evidence filled in after the mutation pass) 2026-12-04 13:28:50 +01:00
mnovak a355532881 [repo] Mutation: host mutants M25-M51 (pairing, HTTP, RTSP, ANNOUNCE, DESCRIBE, ENet host and client session ids, control host, video and audio packetizers); a row may name several test binaries 2026-12-04 13:28:50 +01:00
mnovak 6207624cb8 [domistream] Session: a whole GameStream session between our client and our host, in memory
serverinfo over HTTP, pairing with the owner typing the phone's code, serverinfo over HTTPS (PairStatus 1), applist, launch (keys handed over), RTSP with one connection per request (the host's StreamConfig equals the client's ANNOUNCE), ENet + START_B, sealed video over a lossy link (exactly the parity budget lost per block, then a burst beyond it reported lost and answered with reference invalidation and an IDR request, then a recovery frame), sealed audio without parity (losses reported), typed input and a gamepad state, rumble, graceful termination, ENet disconnect and cancel. Also the Tessera-trusted path (no /pair, pinned host certificate) and an unpaired client refused over HTTPS. START_B, PERIODIC_PING and the IDR request go with empty bodies over the probe-style stack because ControlStream refuses them (U10).
2026-12-04 13:28:50 +01:00
mnovak fd6333620d [domistream] HTTP: MAX_APPS = 4095, derived from the XML element cap, on client and host alike
4096 apps of four elements each (App, AppTitle, ID, IsHdrSupported) plus the root need 16385 elements, one over MAX_XML_ELEMENTS, so the app cap could never be reached by a list as hosts write it and the host writer already stopped at 4095. Lowering the app cap to (MAX_XML_ELEMENTS - 1) / 4 = 4095 instead of raising the element cap keeps the XML parser's memory bound where it was and makes the two caps one number: the host's MAX_WRITTEN_APPS is now MAX_APPS, with a compile-time check that it fits.
2026-12-04 13:28:50 +01:00
mnovak fa08511804 [domistream] ENet: take VERIFY_CONNECT's session ids as stock ENet does (incoming = verify.incoming)
The client stored them the other way round (out_session from verify.incoming_session_id). Against a fresh stock slot both are 0, so it never showed; after a reconnect stock ENet answers with two different ids and the client would send with the host's outgoing id and drop every host datagram. Found by the ENet host engineer; facts from stock ENet v1.3.18 as logged in S-17/S-34 (PROTOCOL.md 3.1), no new source read.
2026-12-04 13:28:50 +01:00
mnovak 3dd7a8fe94 [domistream] HTTP: test that a full applist at MAX_APPS fits the XML element cap (fails: 4096 apps need 16385 elements)
Hosts write four elements per app; MAX_APPS of them plus the root must fit MAX_XML_ELEMENTS, so the app cap is reachable.
2026-12-04 13:28:50 +01:00
mnovak c06fec4be5 [domistream] ENet: test that the client takes the verify's session ids as stock ENet does (fails: they are swapped)
A host that answers VERIFY_CONNECT with different incoming and outgoing session ids (stock ENet after a reconnect, PROTOCOL.md 3.1) must see the client send with the verify's outgoing id and accept datagrams carrying the verify's incoming id.
2026-12-04 13:28:50 +01:00
mnovak 10f88e69cd [repo] Merge: fix/fuzz-manifest (fuzz manifest duplicated keys, PR #13) 2026-12-04 13:25:30 +01:00
mnovak a263ef0f9a [fuzz] Manifest: drop the duplicated keys left by a merge in the announce entry 2026-12-04 13:25:10 +01:00
mnovak 337f6a72c5 [repo] Merge: feature/host-pairing-http (host HTTP, XML answers and pairing, PR #12) 2026-12-04 12:49:58 +01:00
mnovak 80047c65df [fuzz] rustfmt of the host targets 2026-12-04 12:48:26 +01:00
mnovak 509e82d914 [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:48:26 +01:00
mnovak 989defcc88 [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:48:25 +01:00
mnovak 3106f2cb46 [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:48:25 +01:00
mnovak bdd867c521 [domistream] Host pairing: tests first (client and host paired in memory, wrong PIN on both sides, order, timeouts, trusted clients) 2026-12-04 12:48:25 +01:00
mnovak 3aa3775de8 [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:48:25 +01:00
mnovak 7b9b1f4e9c [repo] Merge: feature/host-enet-control (ENet accepting side and control host, PR #11) 2026-12-04 12:48:07 +01:00
31 changed files with 4423 additions and 36 deletions
Generated
+1 -1
View File
@@ -241,7 +241,7 @@ dependencies = [
[[package]]
name = "domistream"
version = "0.1.0"
version = "0.2.1"
dependencies = [
"aes",
"aes-gcm",
+1 -1
View File
@@ -5,7 +5,7 @@ exclude = ["fuzz"]
resolver = "3"
[workspace.package]
version = "0.1.0"
version = "0.2.1"
edition = "2024"
rust-version = "1.89"
license = "CPAL-1.0"
+10 -6
View File
@@ -7,6 +7,7 @@ bytes, events and deadlines out.
| Part | What | Day |
| :-- | :-- | :-- |
| GameStream client | pairing handshake, app list, RTSP, the ENet-compatible control channel, input and gamepad messages, RTP video depacketizer with FEC recovery, Opus audio with FEC, stream encryption | 1 |
| GameStream host (Lumen) | the host's half of the same protocols: HTTP requests and XML answers, the pairing machine and Tessera-trusted clients, the RTSP session with DESCRIBE and a strict ANNOUNCE parser, the accepting ENet peer, the control host, video packetizer with FEC parity, Opus audio packetizer | Lumen L1 |
| Harness maths | clock sync and the added-latency statistics | 2 |
| Lumen | the protocol, FEC, pacing and congestion maths of Arena Domi's own engine | 3–7 |
@@ -18,13 +19,16 @@ Rubylight or moonlight-common-c was opened, pasted or ported. See [`docs/CLEAN_R
cargo test --workspace
```
## Status: `stream-v0.1.0`
## Status: `stream-v0.2.0`
Written from the Wolf protocol docs and the approved permissive sources (stock ENet, tokio-enet, fec-rs). **Interop is
unverified**: this release has not yet talked to a real Sunshine host. Ten details that block interop (U1, U2, U4–U10,
U17 in [`docs/PROTOCOL.md`](docs/PROTOCOL.md)) are settled live on Arena Domi's Play remotely Day 1, and a
`stream-v0.1.x` patch is expected. Evidence for this release: 242 tests, a mutation pass (24 of 24 caught,
[`docs/MUTATION.md`](docs/MUTATION.md)), and 25 fuzz targets with 0 crashes ([`docs/HANDOVER.md`](docs/HANDOVER.md)).
| Side | State |
| :-- | :-- |
| Client (since `stream-v0.1.0`) | complete for Day 1. **Interop with a real Sunshine host is unverified**: ten details that block it (U1, U2, U4–U10, U17 in [`docs/PROTOCOL.md`](docs/PROTOCOL.md)) are settled live on Play remotely Day 1 |
| Host, for Lumen (new in `stream-v0.2.0`) | complete for Lumen L1 and tested against our own client in one in-memory session. **Interop with real clients (Arena Domi Remote, the Moonlight PC app) is unverified**: it is measured black-box at the end of L1 |
Written from the Wolf protocol docs, Moonshine (BSD-2, facts only) and the approved permissive sources (stock ENet,
tokio-enet, fec-rs). Evidence for this release is in [`docs/HANDOVER.md`](docs/HANDOVER.md): the test suite, the
mutation pass ([`docs/MUTATION.md`](docs/MUTATION.md)) and 32 fuzz targets with 0 crashes.
| Path | What |
| :-- | :-- |
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "domistream"
description = "Sans-I/O GameStream client protocol for Arena Domi Play remotely"
description = "Sans-I/O GameStream protocol (client and host) for Arena Domi Play remotely"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
+18 -11
View File
@@ -269,11 +269,11 @@ pub fn parse_host_message(message: &[u8]) -> Result<HostMessage> {
pub enum ClientMessage {
/// `START_A` (body UNKNOWN U10).
StartA,
/// `START_B` (body UNKNOWN U10): the host starts video and audio.
/// `START_B`: the host starts video and audio. Sent with an empty body (PROTOCOL.md 3.3).
StartB,
/// Keep-alive (body UNKNOWN U10).
/// Keep-alive, sent with an empty body (3.3).
PeriodicPing,
/// Ask for an IDR frame (body UNKNOWN U10).
/// Ask for an IDR frame, sent with an empty body (3.3).
RequestIdrFrame,
/// Ask the host to stop referencing frames `first..=last`.
InvalidateRefFrames {
@@ -289,8 +289,9 @@ pub enum ClientMessage {
/// Serializes a message to the host (type, length, body), ready for [`super::ControlCipher::seal`].
///
/// # Errors
/// [`crate::Error::Unsupported`] for a message whose body is still UNKNOWN (U10: START_A, START_B,
/// PERIODIC_PING, IDR request; refused rather than guessed); input errors as [`crate::input::encode_input`].
/// [`crate::Error::Unsupported`] for START_A, whose body is still UNKNOWN (U10; refused rather than guessed);
/// input errors as [`crate::input::encode_input`]. START_B, PERIODIC_PING and the IDR request carry an empty body:
/// what Moonshine and Lumen read (PROTOCOL.md 3.3); whether Sunshine reads more is still U10.
pub fn encode_client_message(message: &ClientMessage) -> Result<Vec<u8>> {
match message {
ClientMessage::InvalidateRefFrames { first, last } => {
@@ -304,11 +305,17 @@ pub fn encode_client_message(message: &ClientMessage) -> Result<Vec<u8>> {
Ok(m)
}
ClientMessage::Input(e) => crate::input::encode_input(e),
ClientMessage::StartA
| ClientMessage::StartB
| ClientMessage::PeriodicPing
| ClientMessage::RequestIdrFrame => {
Err(crate::Error::Unsupported { what: "a control message whose body is still UNKNOWN (U10)" })
}
ClientMessage::StartB => Ok(empty_body(MessageType::StartB)),
ClientMessage::PeriodicPing => Ok(empty_body(MessageType::PeriodicPing)),
ClientMessage::RequestIdrFrame => Ok(empty_body(MessageType::IdrFrame)),
ClientMessage::StartA => Err(crate::Error::Unsupported { what: "START_A, whose body is still UNKNOWN (U10)" }),
}
}
/// A message of type `t` with a zero-length body: type and length (0), both little-endian (PROTOCOL.md 3.3).
fn empty_body(t: MessageType) -> Vec<u8> {
let mut m = Vec::with_capacity(4);
m.extend_from_slice(&(t as u16).to_le_bytes());
m.extend_from_slice(&0u16.to_le_bytes());
m
}
+4 -2
View File
@@ -333,8 +333,10 @@ impl EnetClient {
}
if self.state == EnetState::Connecting && p.connect_id == self.connect_id {
self.host_peer_id = p.outgoing_peer_id & protocol::MAX_PEER_ID;
self.out_session = p.incoming_session_id & 0x3;
self.in_session = p.outgoing_session_id & 0x3;
// Both ids are given from the client's point of view (PROTOCOL.md 3.1 [E]): the incoming one is
// what the host sends with, the outgoing one what we send with.
self.in_session = p.incoming_session_id & 0x3;
self.out_session = p.outgoing_session_id & 0x3;
let count = u8::try_from(p.channel_count.clamp(1, 255)).unwrap_or(1);
self.channel_count = self.channel_count.min(count);
let mtu = usize::try_from(p.mtu).unwrap_or(MAX_DATAGRAM_BYTES);
+275
View File
@@ -0,0 +1,275 @@
//! 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`], which is set so the
/// document (the root plus four elements per app) stays within the client's [`crate::http::xml::MAX_XML_ELEMENTS`].
pub const MAX_WRITTEN_APPS: usize = MAX_APPS;
const _: () =
assert!(4 * MAX_WRITTEN_APPS < MAX_XML_ELEMENTS, "an applist at the cap (root + 4 per app) must fit the XML cap");
/// 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()
}
}
+5 -2
View File
@@ -1,12 +1,15 @@
//! `GET /applist` (`docs/PROTOCOL.md` 1.3).
use super::xml::MAX_XML_ELEMENTS;
use crate::Result;
use crate::util::{cap, malformed, parse_u32};
/// Maximum size of an applist body, in bytes.
pub const MAX_APPLIST_BYTES: usize = 1024 * 1024;
/// Maximum number of apps accepted in one list.
pub const MAX_APPS: usize = 4096;
/// Maximum number of apps accepted in one list: as many as fit the XML element cap with the four elements a host
/// writes per app (`App`, `AppTitle`, `ID`, `IsHdrSupported`) plus the root, so a full list is refused by this cap and
/// never by the XML parser first.
pub const MAX_APPS: usize = (MAX_XML_ELEMENTS - 1) / 4;
/// Maximum length of an app title, in bytes.
pub const MAX_APP_TITLE_BYTES: usize = 512;
+2
View File
@@ -28,6 +28,7 @@
//! | [`fec`] | Reed-Solomon erasure coding over GF(2^8) |
//! | [`video`] | video depacketizer with FEC recovery and decryption (section 5); the host's packetizer |
//! | [`audio`] | audio depacketizer with FEC recovery and decryption (section 6); the host's packetizer |
//! | [`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).
@@ -40,6 +41,7 @@ pub mod enet;
pub mod entropy;
pub mod error;
pub mod fec;
pub mod host;
pub mod http;
pub mod input;
pub mod keys;
+1 -1
View File
@@ -95,7 +95,7 @@ pub(crate) fn hex_encode(bytes: &[u8]) -> String {
s
}
fn hex_digit(c: u8) -> Option<u8> {
pub(crate) fn hex_digit(c: u8) -> Option<u8> {
match c {
b'0'..=b'9' => Some(c - b'0'),
b'a'..=b'f' => Some(c - b'a' + 10),
+18
View File
@@ -135,6 +135,20 @@ fn lying_inputs() -> Vec<Case> {
v.push(("pairing secret", vec![0; 17], |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
}
@@ -267,6 +281,10 @@ fn parsers_never_allocate_past_their_caps() {
("video", |b| common::implemented(&domistream::video::parse_video_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))),
("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| {
common::implemented(
&domistream::audio::AudioCipher::new(&SessionKeys { rikey: [2; 16], rikeyid: 0 }).decrypt(0, b),
+1
View File
@@ -214,6 +214,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 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 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.
pub fn base64_decode(s: &str) -> Vec<u8> {
+11 -4
View File
@@ -381,11 +381,18 @@ fn client_messages() {
encode_client_message(&ClientMessage::Input(ev.clone())).unwrap(),
domistream::input::encode_input(&ev).unwrap()
);
// Bodies still UNKNOWN (U10) are refused rather than guessed.
for m in [ClientMessage::StartA, ClientMessage::StartB, ClientMessage::PeriodicPing, ClientMessage::RequestIdrFrame]
{
assert_err!(encode_client_message(&m), Error::Unsupported { .. }, "{m:?}");
// START_B, PERIODIC_PING and the IDR request go with an empty body (PROTOCOL.md 3.3: what Moonshine and Lumen
// read; the lead's decision of 2026-12-04). START_A's body is still UNKNOWN (U10) and stays refused.
for (m, t) in [
(ClientMessage::StartB, 0x0307u16),
(ClientMessage::PeriodicPing, 0x0200),
(ClientMessage::RequestIdrFrame, 0x0302),
] {
let mut want = t.to_le_bytes().to_vec();
want.extend_from_slice(&0u16.to_le_bytes());
assert_eq!(encode_client_message(&m).unwrap(), want, "{m:?}");
}
assert_err!(encode_client_message(&ClientMessage::StartA), Error::Unsupported { .. });
}
proptest! {
+47
View File
@@ -497,6 +497,53 @@ fn verify_with_wrong_connect_id_does_not_connect() {
assert!(link.events().is_empty());
}
#[test]
fn verify_session_ids_are_taken_as_stock_enet_takes_them() {
// PROTOCOL.md 3.1 [E]: the verify carries both session ids from the client's point of view. Its incoming id is
// the host's outgoing one (what the host puts in its headers, so what the client must accept) and its outgoing id
// is the host's incoming one (what the client must put in its headers). A fresh host slot answers 0/0, which hides
// a swap; after a reconnect stock ENet answers with two different ids, as here.
let (mut client, d, params, _, connect_seq) = start();
let host = |session_id: u8, sent_time: u16, commands: Vec<Command>| {
encode_datagram(&Datagram {
peer_id: params.outgoing_peer_id,
session_id,
sent_time: Some(sent_time),
commands,
})
.unwrap()
};
let verify = ConnectParams { outgoing_peer_id: 7, incoming_session_id: 1, outgoing_session_id: 2, ..params };
let ack = CommandBody::Acknowledge {
received_reliable_sequence: connect_seq,
received_sent_time: d.sent_time.unwrap_or(0),
};
client
.handle_datagram(
at(1),
&host(1, 1, vec![cmd(false, 0xFF, 0, ack), cmd(true, 0xFF, 1, CommandBody::VerifyConnect(verify))]),
)
.unwrap();
assert_eq!(client.poll_event(), Some(EnetEvent::Connected));
// The client's datagrams carry its outgoing session id: the verify's outgoing id, 2.
let sent: Vec<Datagram> =
core::iter::from_fn(|| client.poll_transmit(at(1))).map(|d| parse_datagram(&d).unwrap()).collect();
assert!(!sent.is_empty(), "the verify is acknowledged");
for d in &sent {
assert_eq!((d.peer_id, d.session_id), (7, 2), "{d:?}");
}
// The host's datagrams carry the host's outgoing id (the verify's incoming id, 1): taken. Id 2 is not the
// client's incoming id: dropped.
let wrong = cmd(true, 0, 1, CommandBody::SendReliable(b"wrong session".to_vec()));
assert_eq!(client.handle_datagram(at(2), &host(2, 2, vec![wrong])), Ok(()));
assert_eq!(client.poll_event(), None, "a datagram with the client's outgoing id is not for it");
let right = cmd(true, 0, 1, CommandBody::SendReliable(b"right session".to_vec()));
client.handle_datagram(at(3), &host(1, 3, vec![right])).unwrap();
assert_eq!(client.poll_event(), Some(EnetEvent::Received { channel: 0, data: b"right session".to_vec() }));
}
#[test]
fn garbage_never_changes_state() {
let mut link = connected();
+18
View File
@@ -464,6 +464,24 @@ fn data_before_the_verify_ack_is_not_taken() {
);
}
#[test]
fn ping_before_the_verify_ack_is_not_acknowledged() {
// Mutation M36: only a connected peer acknowledges a ping (PROTOCOL.md 3.1, the accepting side); before the
// client has acknowledged the verify, an acknowledged ping must not be answered with an ACK.
let mut h = EnetHostPeer::accept(host_config(), at(0), &connect_datagram(connect_params(3), 0)).unwrap();
let _ = transmitted(&mut h, at(0));
let ping = cmd(true, 0xFF, 1, CommandBody::Ping);
h.handle_datagram(at(1), &to_host(0, Some(1), vec![ping])).unwrap();
assert!(
!transmitted(&mut h, at(1))
.iter()
.flat_map(|d| &d.commands)
.any(|c| matches!(c.body, CommandBody::Acknowledge { .. })),
"no acknowledgement before the verify is acknowledged"
);
assert_eq!(h.state(), EnetHostState::AcknowledgingConnect);
}
#[test]
fn lost_verify_is_retransmitted() {
let mut w = wire(Impair::clean(5), Impair::clean(5), 2);
+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);
}
+18
View File
@@ -497,6 +497,24 @@ fn applist_caps() {
);
}
#[test]
fn applist_cap_is_reachable_with_full_apps() {
// Hosts write four elements per app (App, AppTitle, ID, IsHdrSupported; the host writer does too): a list of
// MAX_APPS such apps plus the root must fit the XML element cap, so a list at the app cap parses (one app more is
// refused, by whichever cap comes first; `applist_caps` checks the app cap itself with three-element apps).
use domistream::http::applist::MAX_APPS;
let full = |n: usize| {
(0..n)
.map(|i| format!("<App><AppTitle>g</AppTitle><ID>{i}</ID><IsHdrSupported>1</IsHdrSupported></App>"))
.collect::<String>()
};
const { assert!(4 * MAX_APPS < MAX_XML_ELEMENTS, "root + 4 per app must fit the element cap") };
let apps = http::parse_app_list(&xml_root(200, &full(MAX_APPS))).expect("a full list at the app cap");
assert_eq!(apps.len(), MAX_APPS);
assert!(apps.iter().all(|a| a.hdr_supported));
assert_err!(http::parse_app_list(&xml_root(200, &full(MAX_APPS + 1))), Error::TooLarge { .. });
}
// ================================================================================================ launch
#[test]
+963
View File
@@ -0,0 +1,963 @@
//! A whole GameStream session between DomiStream's client and DomiStream's host (Lumen's protocol half), in memory,
//! with simulated time and seeded randomness (`docs/LUMEN-HOST-PLAN.md` 3.1, 7.1). Every stage goes through both
//! sides' own parsers and writers, so an asymmetric mistake shows here before a real client is involved:
//!
//! serverinfo (HTTP) → pairing with the owner typing the phone's code → serverinfo (HTTPS, paired) → applist → launch
//! (session keys handed over) → RTSP (the host's stream config equals the client's ANNOUNCE) → ENet + START_B →
//! video over a lossy link (FEC within the parity budget, then a burst beyond it, the client asks for recovery) →
//! audio (losses reported, no parity) → input and gamepad → rumble → termination, ENet disconnect, cancel.
//!
//! Also: a Tessera-trusted client that never pairs over the wire, and an unpaired client that HTTPS refuses.
//!
//! What the client cannot do with its shipped API is said where it happens: `ControlStream` refuses START_B,
//! PERIODIC_PING and the IDR request (bodies UNKNOWN U10, PROTOCOL.md 3.3), so the client side of control here is the
//! probe-style stack (`EnetClient` + `ControlCipher`) that sends those three with empty bodies, as `tools/gs-probe` does.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::indexing_slicing, missing_docs)]
mod common;
use core::time::Duration;
use common::wire::{Endpoint, Impair, Wire, at};
use common::{HOST_KEY_PEM, SeqRng, pem_blocks};
use domistream::audio::{
AudioCipher, AudioConfig, AudioDepacketizer, AudioEvent, AudioFec, AudioPacketizer, AudioPacketizerConfig,
AudioParity,
};
use domistream::control::host::{DEFAULT_STOP_TIMEOUT, TERMINATION_GRACEFUL};
use domistream::control::message::encode_client_message;
use domistream::control::{
ClientControlMessage, ClientMessage, ControlCipher, ControlHost, ControlHostConfig, ControlHostEvent, Direction,
HostMessage, MessageType, parse_host_message,
};
use domistream::enet::{Delivery, EnetClient, EnetConfig, EnetEvent, EnetHostConfig, EnetHostState, EnetState};
use domistream::host::http::{
HostInfo, LaunchRequest, Route, app_list_xml, error_xml, launch_xml, ok_xml, pair_answer_xml, parse_request_head,
server_info_xml,
};
use domistream::host::pairing::{
HostIdentity, HostPairingConfig, HostPairingSession, HostPairingStep, PairAnswer, PairPhase, PairRequest,
PairedClient, Transport,
};
use domistream::http::launch::{AudioLayout, LaunchParams, launch_request};
use domistream::http::{
App, HttpRequest, Scheme, ServerInfo, app_list_request, cancel_request, parse_app_list, parse_launch_response,
parse_server_info, parse_status_response, server_info_request,
};
use domistream::input::{ButtonFlags, GamepadState, InputEvent, MouseButton};
use domistream::pairing::{
ClientIdentity, PairedHost, PairingSession, PairingStep, Pin, ServerCert, parse_pair_response,
};
use domistream::rtsp::client::{PING_PAYLOAD, VideoCodec};
use domistream::rtsp::sdp::{FeatureFlags, parse_surround_params};
use domistream::rtsp::server::{
ChromaSampling, DEFAULT_SESSION_TIMEOUT_SECS, StreamConfig as HostStreamConfig, SurroundSettings,
};
use domistream::rtsp::{
EncryptionFlags, HostOffer, NegotiatedStream, RtspClient, RtspFramer, RtspProgress, RtspServer, ServerConfig,
ServerEvent, StreamConfig as ClientStreamConfig, StreamPorts,
};
use domistream::video::packet::FRAME_HEADER_LEN;
use domistream::video::packetizer::{FecBlock, plan_fec_blocks};
use domistream::video::{
EncodedFrame, FrameType, VideoCipher, VideoConfig, VideoDepacketizer, VideoEvent, VideoPacketizer,
VideoPacketizerConfig,
};
use domistream::{Error, Instant, SessionKeys};
const UID: &str = "0123456789ABCDEF";
const DEVICE: &str = "Arena Domi TV test";
const HOST_ADDR: &str = "192.0.2.10";
const RTSP_PORT: u16 = 48010;
const PORTS: StreamPorts = StreamPorts { audio: 48000, video: 47998, control: 47999 };
const ALL: u8 = EncryptionFlags::CONTROL_V2 | EncryptionFlags::VIDEO | EncryptionFlags::AUDIO;
/// The host's video FEC percentage: Moonshine's default (S-31).
const FEC_PERCENT: u8 = 20;
// ================================================================================================ identities
fn host_identity() -> HostIdentity {
let key = pem_blocks(HOST_KEY_PEM, "PRIVATE KEY").pop().expect("host key PEM");
HostIdentity::from_der(&common::pairing_vectors().bytes("host_cert_der"), &key).expect("test-only host identity")
}
fn client_identity(name: &str) -> ClientIdentity {
let v = common::pairing_vectors();
ClientIdentity::from_der(&v.bytes(&format!("{name}_cert_der")), &v.bytes(&format!("{name}_key_pkcs8_der")))
.expect("test-only client identity")
}
// ================================================================================================ the host's HTTP side
/// Lumen's HTTP and HTTPS listeners as the caller of `host::http` and `host::pairing` builds them.
struct LumenHttp {
identity: HostIdentity,
info: HostInfo,
apps: Vec<App>,
/// Clients whose certificate HTTPS accepts (paired, or recorded from a Tessera grant).
paired: Vec<PairedClient>,
pairing: Option<HostPairingSession>,
/// The code the owner types into "Enter the code from your phone" when a pairing request is held.
owner_code: Option<Pin>,
launched: Option<LaunchRequest>,
rng: SeqRng,
now: Instant,
}
impl LumenHttp {
fn new(seed: u64) -> Self {
Self {
identity: host_identity(),
info: HostInfo {
hostname: "Lumen test host".into(),
app_version: "7.1.431.-1".into(),
gfe_version: "3.23.0.74".into(),
unique_id: "LUMEN-TEST-HOST-1".into(),
https_port: 47984,
http_port: 47989,
mac: Some([0x02, 0, 0x5e, 0x10, 0x20, 0x30]),
local_ip: HOST_ADDR.into(),
max_luma_pixels_hevc: 1_869_449_984,
codec_mode_support: 0x0101,
current_game: 0,
state_prefix: "LUMEN".into(),
},
apps: vec![
App { id: 1, title: "Desktop".into(), hdr_supported: false },
App { id: 881_100, title: "Hollow & <Knight>".into(), hdr_supported: false },
App { id: 4_000_000_000, title: "Forza Horizon 5".into(), hdr_supported: true },
],
paired: Vec::new(),
pairing: None,
owner_code: None,
launched: None,
rng: SeqRng::new(seed),
now: Instant::ZERO,
}
}
fn is_paired(&self, cert_der: &[u8]) -> bool {
self.paired.iter().any(|p| p.matches(cert_der).unwrap())
}
/// One GET: the head through the host's strict parser, the answer from the host's XML writers. HTTPS routes other
/// than `/pair` and `/serverinfo` need a paired certificate (refused with status 401 otherwise).
fn serve(&mut self, request: &HttpRequest, transport: Transport<'_>) -> Vec<u8> {
self.now = self.now.saturating_add(Duration::from_millis(40));
let head = format!("GET {} HTTP/1.1\r\nHost: {HOST_ADDR}\r\n\r\n", request.path_and_query);
let parsed = parse_request_head(head.as_bytes()).expect("the host parses every request our client builds");
assert_eq!(parsed.unique_id.as_deref(), Some(UID));
// The host reads every parameter our client sends, except `updateState=1` on `/pair` (U1: whether a host
// needs it is unknown; Lumen's parser keeps it for the logs and does not need it).
let unread: Vec<&str> = parsed.other_params.iter().map(|(name, _)| name.as_str()).collect();
let allowed: &[&str] = if matches!(parsed.route, Route::Pair(_)) { &["updateState"] } else { &[] };
assert_eq!(unread, allowed, "parameters the host does not read");
let paired = match transport {
Transport::Https { client_cert_der } => self.is_paired(client_cert_der),
Transport::Http => false,
};
match parsed.route {
Route::ServerInfo => server_info_xml(&self.info, transport.scheme(), paired).unwrap(),
Route::Pair(p) => self.pair(&p, transport),
_ if !paired => error_xml(401, "This device is not paired with Arena Domi").unwrap(),
Route::AppList => app_list_xml(&self.apps).unwrap(),
Route::Launch(l) => {
self.info.current_game = l.app_id;
self.launched = Some(l);
launch_xml(HOST_ADDR, RTSP_PORT).unwrap()
}
Route::Cancel => {
self.info.current_game = 0;
ok_xml()
}
other => panic!("the session test does not use {other:?}"),
}
}
/// `/pair`: phase 1 opens a new attempt and is held until the owner types the code.
fn pair(&mut self, request: &PairRequest, transport: Transport<'_>) -> Vec<u8> {
if matches!(request.phase, PairPhase::GetServerCert { .. }) {
self.pairing = Some(HostPairingSession::new(&self.identity, HostPairingConfig::default(), self.now));
}
let Some(session) = self.pairing.as_mut() else { return pair_answer_xml(&PairAnswer::Refused).unwrap() };
let answer = match session.handle(&self.identity, request, transport, self.now, &mut self.rng) {
Ok(HostPairingStep::Answer(a)) => a,
Ok(HostPairingStep::HoldForPin) => {
let code = self.owner_code.take().expect("the owner has the phone's code to type");
self.now = self.now.saturating_add(Duration::from_secs(4));
session.supply_pin(&self.identity, code, self.now).unwrap_or(PairAnswer::Refused)
}
Ok(HostPairingStep::Paired(client)) => {
self.paired.push(client);
PairAnswer::Paired
}
Err(_) => PairAnswer::Refused,
};
pair_answer_xml(&answer).unwrap()
}
}
/// The client's HTTP(S) call. Over HTTPS the client presents its certificate and pins the host's: the TLS stack's
/// job in the app (PROTOCOL.md 1.1), an explicit check here.
fn get(host: &mut LumenHttp, request: &HttpRequest, client: &ClientIdentity, pinned: Option<&ServerCert>) -> Vec<u8> {
match request.scheme {
Scheme::Http => host.serve(request, Transport::Http),
Scheme::Https => {
let pin = pinned.expect("HTTPS only with a pinned host certificate");
assert_eq!(
pin.matches(host.identity.cert_der()),
Ok(true),
"TLS: the host presents the pinned certificate"
);
host.serve(request, Transport::Https { client_cert_der: client.cert_der() })
}
}
}
/// Pairs `client` with `host`: the phone makes the code, the owner types it on the PC (`docs/LUMEN-HOST-PLAN.md`
/// 1.9). The client pins the phase-1 `plaincert` for the HTTPS phase 5.
fn pair(host: &mut LumenHttp, client: &ClientIdentity, rng: &mut SeqRng) -> PairedHost {
let code = Pin::generate(rng).unwrap();
host.owner_code = Some(code);
let (mut session, mut request) = PairingSession::start(client, UID, DEVICE, code, rng).unwrap();
let mut plaincert: Option<ServerCert> = None;
for _ in 0..5 {
let body = get(host, &request, client, plaincert.as_ref());
if plaincert.is_none() {
let pem = parse_pair_response(&body).unwrap().plain_cert.expect("phase 1 carries plaincert");
plaincert = Some(ServerCert::from_pem(&pem).unwrap());
}
match session.handle_response(client, 200, &body, rng).expect("every phase passes") {
PairingStep::Send(next) => request = next,
PairingStep::Paired(paired) => return paired,
}
}
panic!("pairing did not finish in five round trips");
}
// ================================================================================================ RTSP
fn client_stream_config() -> ClientStreamConfig {
ClientStreamConfig {
width: 1920,
height: 1080,
fps: 60,
bitrate_kbps: 20_000,
packet_size: 1024,
codec: VideoCodec::Hevc,
hdr: false,
audio: AudioLayout::Stereo,
audio_packet_duration_ms: 5,
min_fec_packets: 2,
reference_frame_invalidation: true,
encryption: EncryptionFlags(ALL),
}
}
fn rtsp_server_config() -> ServerConfig {
ServerConfig {
ports: PORTS,
offer: HostOffer {
feature_flags: FeatureFlags(3),
encryption_supported: EncryptionFlags(ALL),
reference_frame_invalidation: true,
h264: true,
hevc: true,
av1: false,
hdr: false,
yuv444: false,
opus_configs: vec![parse_surround_params("21101").unwrap()],
},
required_encryption: EncryptionFlags(EncryptionFlags::CONTROL_V2),
// Our client echoes the SETUP session id, so the strict setting holds.
require_session_header: true,
session_timeout_secs: DEFAULT_SESSION_TIMEOUT_SECS,
}
}
/// What the host must read from our client's ANNOUNCE for `c` (the attributes `rtsp::sdp::build_announce` writes).
fn announced_by(c: &ClientStreamConfig, enabled: EncryptionFlags) -> HostStreamConfig {
let channels = c.audio.channels();
HostStreamConfig {
width: c.width,
height: c.height,
max_fps: c.fps,
packet_size: c.packet_size,
bitrate_kbps: c.bitrate_kbps,
codec: c.codec,
min_fec_packets: c.min_fec_packets,
video_qos_traffic_type: 5,
audio_packet_duration_ms: c.audio_packet_duration_ms,
audio_qos_traffic_type: 4,
max_reference_frames: if c.reference_frame_invalidation { 0 } else { 1 },
reference_frame_invalidation: c.reference_frame_invalidation,
dynamic_range_mode: u32::from(c.hdr),
encoder_csc_mode: if c.hdr { 5 } else { 0 },
chroma: ChromaSampling::Yuv420,
encryption: enabled,
surround: SurroundSettings {
enabled: channels > 2,
channels,
channel_mask: c.audio.channel_mask(),
high_quality: true,
},
unknown_attributes: 0,
}
}
/// OPTIONS … PLAY, one TCP connection per request (PROTOCOL.md 2.5), bytes cut 7 at a time by both framers.
fn negotiate(
session_url: &str,
config: ClientStreamConfig,
server: &mut RtspServer,
) -> (NegotiatedStream, Vec<ServerEvent>) {
let mut client = RtspClient::new(session_url, config).unwrap();
let mut events = Vec::new();
for _ in 0..7 {
let request = client.poll_request().expect("the client has its next request");
let mut to_server = RtspFramer::for_requests();
let mut replies = Vec::new();
for piece in request.chunks(7) {
to_server.push(piece).unwrap();
while let Some(message) = to_server.next_message().unwrap() {
replies.push(server.handle_request(&message));
}
}
assert_eq!(replies.len(), 1, "one request, one answer");
assert_eq!(replies[0].status, 200, "{:?}", replies[0].error);
events.extend(core::iter::from_fn(|| server.poll_event()));
let mut to_client = RtspFramer::new();
let mut answers = Vec::new();
for piece in replies[0].bytes.chunks(7) {
to_client.push(piece).unwrap();
answers.extend(to_client.next_message().unwrap());
}
assert_eq!(answers.len(), 1, "the answer is framed by Content-Length");
if let RtspProgress::Ready(n) = client.handle_response(&answers[0]).unwrap() {
return (n, events);
}
}
panic!("RTSP never finished");
}
// ================================================================================================ control
/// The client's control stream, probe-style (see the top of this file).
struct ClientControl {
enet: EnetClient,
cipher: ControlCipher,
next_sequence: u32,
last_host_sequence: Option<u32>,
host_messages: Vec<HostMessage>,
enet_events: Vec<EnetEvent>,
}
impl ClientControl {
fn connect(rikey: [u8; 16], rng: &mut SeqRng) -> Self {
let config = EnetConfig {
channel_count: 1,
mtu: 1392,
connect_data: 0,
ping_interval: Duration::from_millis(500),
timeout: Duration::from_secs(10),
};
Self {
enet: EnetClient::connect(config, Instant::ZERO, rng).unwrap(),
cipher: ControlCipher::new(rikey),
next_sequence: 0,
last_host_sequence: None,
host_messages: Vec::new(),
enet_events: Vec::new(),
}
}
fn send_plain(&mut self, now: Instant, plain: &[u8]) {
let frame = self.cipher.seal(self.next_sequence, Direction::ClientToHost, plain).unwrap();
self.enet.send(now, 0, Delivery::Reliable, &frame).unwrap();
self.next_sequence += 1;
}
fn send(&mut self, now: Instant, message: &ClientMessage) {
self.send_plain(now, &encode_client_message(message).unwrap());
}
/// A message with an empty body: START_B, PERIODIC_PING, IDR request (PROTOCOL.md 3.3).
fn send_empty(&mut self, now: Instant, message_type: MessageType) {
let mut plain = (message_type as u16).to_le_bytes().to_vec();
plain.extend_from_slice(&0u16.to_le_bytes());
self.send_plain(now, &plain);
}
fn drain(&mut self) {
while let Some(event) = self.enet.poll_event() {
match event {
EnetEvent::Received { data, .. } => {
let (sequence, plain) = self.cipher.open(Direction::HostToClient, &data).expect("host frames open");
assert!(self.last_host_sequence.is_none_or(|last| sequence > last), "host sequence goes up");
self.last_host_sequence = Some(sequence);
self.host_messages.push(parse_host_message(&plain).expect("the client reads every host message"));
}
other => self.enet_events.push(other),
}
}
}
}
impl Endpoint for ClientControl {
fn transmit(&mut self, now: Instant) -> Option<Vec<u8>> {
self.enet.poll_transmit(now)
}
fn receive(&mut self, now: Instant, datagram: &[u8]) {
let _ = self.enet.handle_datagram(now, datagram);
self.drain();
}
fn deadline(&self) -> Option<Instant> {
self.enet.poll_timeout()
}
fn tick(&mut self, now: Instant) {
self.enet.handle_timeout(now).unwrap();
self.drain();
}
}
/// Lumen's control listener for this client's address: the first datagram must be the CONNECT.
struct HostControl {
config: ControlHostConfig,
host: Option<ControlHost>,
events: Vec<ControlHostEvent>,
}
impl HostControl {
fn h(&mut self) -> &mut ControlHost {
self.host.as_mut().expect("accepted")
}
fn messages(&self) -> Vec<ClientControlMessage> {
self.events
.iter()
.filter_map(|e| match e {
ControlHostEvent::Message(m) => Some(m.clone()),
_ => None,
})
.collect()
}
fn drain(&mut self) {
if let Some(h) = self.host.as_mut() {
self.events.extend(core::iter::from_fn(|| h.poll_event()));
}
}
}
impl Endpoint for HostControl {
fn transmit(&mut self, now: Instant) -> Option<Vec<u8>> {
self.host.as_mut()?.poll_transmit(now)
}
fn receive(&mut self, now: Instant, datagram: &[u8]) {
match self.host.as_mut() {
None => self.host = ControlHost::accept(self.config.clone(), now, datagram).ok(),
Some(h) => {
let _ = h.handle_datagram(now, datagram);
}
}
self.drain();
}
fn deadline(&self) -> Option<Instant> {
self.host.as_ref()?.poll_timeout()
}
fn tick(&mut self, now: Instant) {
if let Some(h) = self.host.as_mut() {
h.handle_timeout(now).unwrap();
}
self.drain();
}
}
type Control = Wire<ClientControl, HostControl>;
/// Runs the control wire until the host has seen `n` messages; returns the new ones.
fn host_receives(w: &mut Control, n: usize) -> Vec<ClientControlMessage> {
let before = w.host.messages().len();
assert!(w.run_until(w.now_ms + 10_000, |w| w.host.messages().len() >= before + n), "the host never got them");
w.host.messages()[before..].to_vec()
}
// ================================================================================================ media
/// A synthetic HEVC access unit of exactly `len` bytes (at least 6): start code, a NAL header (IDR_W_RADL for a key
/// frame, TRAIL_R otherwise), random payload.
fn access_unit(rng: &mut SeqRng, len: usize, key: bool) -> Vec<u8> {
let mut au = vec![0, 0, 0, 1, if key { 0x26 } else { 0x02 }, 0x01];
au.extend(rng.bytes(len - 6));
au
}
/// How the lossy link treats one FEC block: the indices (data first, then parity) it drops.
type LossPlan<'a> = &'a mut dyn FnMut(&FecBlock, &mut SeqRng) -> Vec<usize>;
/// The worst loss FEC still repairs: exactly `m` of the block's `k + m` datagrams, at least one of them data.
fn within_budget(b: &FecBlock, rng: &mut SeqRng) -> Vec<usize> {
let (k, m) = (usize::from(b.data_shards), usize::from(b.parity_shards));
let mut lost = rng.subset(k + m, m);
if !lost.is_empty() && lost.iter().all(|&i| i >= k) {
lost[0] = rng.below(k);
}
lost
}
/// Sends one frame over the link: drops what `loss` picks per block, duplicates one survivor, shuffles the rest.
/// Returns the data shards lost (what FEC must rebuild) and the duplicates sent.
fn send_frame(
packetizer: &mut VideoPacketizer,
receiver: &mut VideoDepacketizer,
frame: &EncodedFrame<'_>,
min_parity: u8,
loss: LossPlan<'_>,
rng: &mut SeqRng,
now: Instant,
) -> (usize, usize) {
let packets = packetizer.packetize(frame).unwrap();
let payload = usize::from(client_stream_config().packet_size) - 16;
let shards = (FRAME_HEADER_LEN + frame.bitstream.len()).div_ceil(payload);
let plan = plan_fec_blocks(shards, FEC_PERCENT, min_parity).unwrap();
assert_eq!(plan.iter().map(|b| usize::from(b.data_shards + b.parity_shards)).sum::<usize>(), packets.len());
let mut survivors = Vec::new();
let mut data_lost = 0;
let mut start = 0;
for block in &plan {
let size = usize::from(block.data_shards + block.parity_shards);
let lost = loss(block, rng);
data_lost += lost.iter().filter(|&&i| i < usize::from(block.data_shards)).count();
survivors.extend((0..size).filter(|i| !lost.contains(i)).map(|i| packets[start + i].clone()));
start += size;
}
let duplicate = survivors[rng.below(survivors.len())].clone();
survivors.push(duplicate);
rng.shuffle(&mut survivors);
for datagram in &survivors {
receiver.push(now, datagram).unwrap();
}
(data_lost, 1)
}
fn video_events(receiver: &mut VideoDepacketizer, now: Instant, out: &mut Vec<VideoEvent>) {
if receiver.poll_timeout().is_some_and(|t| t <= now) {
receiver.handle_timeout(now).unwrap();
}
out.extend(core::iter::from_fn(|| receiver.poll_event()));
}
// ================================================================================================ the session
#[test]
fn a_whole_session_between_our_client_and_our_host() {
let mut rng = SeqRng::new(0x5E55_1011);
let client = client_identity("client");
let mut host = LumenHttp::new(0x1u64 << 40);
// serverinfo over HTTP: the host is there, this client is not paired.
let info: ServerInfo =
parse_server_info(&get(&mut host, &server_info_request(Scheme::Http, UID).unwrap(), &client, None)).unwrap();
assert_eq!((info.hostname.as_str(), info.unique_id.as_str()), ("Lumen test host", "LUMEN-TEST-HOST-1"));
assert_eq!((info.https_port, info.http_port, info.mac), (47984, Some(47989), host.info.mac));
assert_eq!((info.paired, info.current_game, info.state.as_str()), (false, 0, "LUMEN_SERVER_FREE"));
// Pairing: the owner types the phone's code; the client pins exactly the host's certificate, the host
// authorizes exactly the client's.
let paired = pair(&mut host, &client, &mut rng);
assert_eq!(paired.server_cert.der(), host.identity.cert_der());
assert_eq!(host.paired.len(), 1);
assert_eq!(host.paired[0].cert_der, client.cert_der());
assert_eq!((host.paired[0].unique_id.as_deref(), host.paired[0].device_name.as_deref()), (Some(UID), Some(DEVICE)));
let pin = Some(&paired.server_cert);
// serverinfo over HTTPS: PairStatus 1. Then the app list, byte for byte as the host holds it.
let info =
parse_server_info(&get(&mut host, &server_info_request(Scheme::Https, UID).unwrap(), &client, pin)).unwrap();
assert!(info.paired, "PairStatus 1 over HTTPS with the paired certificate");
let apps = parse_app_list(&get(&mut host, &app_list_request(UID).unwrap(), &client, pin)).unwrap();
assert_eq!(apps, host.apps);
// launch: the session keys reach the host unchanged.
let keys = SessionKeys::generate(&mut rng).unwrap();
let params = LaunchParams {
app_id: apps[2].id,
width: 1920,
height: 1080,
fps: 60,
keys: keys.clone(),
hdr: false,
audio: AudioLayout::Stereo,
};
let launch = parse_launch_response(&get(&mut host, &launch_request(&params, UID).unwrap(), &client, pin)).unwrap();
assert!(launch.game_session);
let session_url = launch.session_url.expect("sessionUrl0");
assert_eq!(session_url, format!("rtsp://{HOST_ADDR}:{RTSP_PORT}"));
let launched = host.launched.clone().expect("the host took the launch");
assert_eq!(launched.keys, keys);
assert_eq!(
(launched.app_id, launched.mode.width, launched.mode.height, launched.mode.fps),
(4_000_000_000, 1920, 1080, 60)
);
assert_eq!(
(launched.hdr, launched.surround_audio_info),
(Some(false), Some(AudioLayout::Stereo.surround_audio_info()))
);
assert_eq!(host.info.current_game, 4_000_000_000);
// RTSP: the host's stream config is exactly what the client announced.
let mut rtsp = RtspServer::new(rtsp_server_config(), &mut rng).unwrap();
let (negotiated, events) = negotiate(&session_url, client_stream_config(), &mut rtsp);
assert_eq!(negotiated.ports, PORTS);
assert_eq!(negotiated.encryption, EncryptionFlags(ALL));
assert_eq!(negotiated.session_id.as_deref(), Some(rtsp.session_id()));
assert_eq!(negotiated.opus, parse_surround_params("21101").unwrap());
assert!(negotiated.host.reference_frame_invalidation);
assert_eq!(negotiated.ping_payload, PING_PAYLOAD, "the PING the host's media listeners wait for");
let announced = announced_by(&client_stream_config(), negotiated.encryption);
assert_eq!(events, vec![ServerEvent::Announced(announced.clone()), ServerEvent::PlayRequested]);
assert_eq!(rtsp.announced(), Some(&announced));
assert_eq!(
(announced.width, announced.height, announced.max_fps),
(launched.mode.width, launched.mode.height, launched.mode.fps)
);
// ENet connect on the control port, then START_B. ControlStream sends START_B with an empty body (3.3); the
// session below drives the same bytes over EnetClient + ControlCipher, as gs-probe does.
assert_eq!(encode_client_message(&ClientMessage::StartB).unwrap(), vec![0x07, 0x03, 0x00, 0x00]);
let host_control = HostControl {
config: ControlHostConfig {
enet: EnetHostConfig {
peer_id: 0,
channel_limit: 0x30,
mtu: 1392,
ping_interval: Duration::from_millis(500),
timeout: Duration::from_secs(10),
},
rikey: launched.keys.rikey,
stop_timeout: Some(DEFAULT_STOP_TIMEOUT),
},
host: None,
events: Vec::new(),
};
let mut w: Control = Wire::new(
ClientControl::connect(keys.rikey, &mut rng),
host_control,
Impair::lossy(30, 5),
Impair::lossy(30, 5),
77,
);
assert!(w.run_until(10_000, |w| w.client.enet.state() == EnetState::Connected
&& w.host.host.as_ref().is_some_and(|h| h.enet().state() == EnetHostState::Connected)));
assert_eq!(w.client.enet_events, vec![EnetEvent::Connected]);
assert_eq!(w.host.events, vec![ControlHostEvent::Connected]);
let t = at(w.now_ms);
w.client.send_empty(t, MessageType::StartB);
assert_eq!(host_receives(&mut w, 1), vec![ClientControlMessage::StartB]);
// A PERIODIC_PING moves the host's stop deadline out (a ControlStream client never sends one: U10).
let deadline = w.host.h().stop_deadline().expect("the stop clock runs");
w.run_for(1_000);
let t = at(w.now_ms);
w.client.send_empty(t, MessageType::PeriodicPing);
assert_eq!(host_receives(&mut w, 1), vec![ClientControlMessage::PeriodicPing]);
assert!(w.host.h().stop_deadline().unwrap() > deadline);
// Video: the packet size and minimum parity the client announced, sealed with the session key.
let mut packetizer = VideoPacketizer::new(VideoPacketizerConfig {
packet_size: announced.packet_size,
fec_percentage: FEC_PERCENT,
min_required_fec_packets: announced.min_fec_packets,
cipher: announced.encryption.contains(EncryptionFlags::VIDEO).then(|| VideoCipher::new(launched.keys.rikey)),
first_sequence: 0xFFF0, // the RTP sequence wraps inside the first frame
})
.unwrap();
let mut receiver = VideoDepacketizer::new(VideoConfig {
packet_size: client_stream_config().packet_size,
cipher: negotiated.encryption.contains(EncryptionFlags::VIDEO).then(|| VideoCipher::new(keys.rikey)),
frame_timeout: Duration::from_millis(60),
})
.unwrap();
// A large IDR (two FEC blocks), sizes at and around one shard, then varied P-frames; frame 12 loses a burst.
let mut sizes = vec![400_000, 6, 1_000, 1_001, 2_016, 3_000, 25_000, 60_000, 12_345, 1_500, 90_000];
sizes.extend((0..14).map(|_| 500 + rng.below(40_000)));
const BURST: u32 = 12;
let mut sent: Vec<(u32, FrameType, Vec<u8>)> = Vec::new();
let mut video = Vec::new();
let (mut rebuilt, mut duplicates) = (0, 0);
for (i, &len) in sizes.iter().enumerate() {
let index = i as u32;
let frame_type = if index == 0 { FrameType::Key } else { FrameType::Predicted };
let bitstream = access_unit(&mut rng, len, index == 0);
let frame = EncodedFrame {
frame_index: index,
frame_type,
rtp_timestamp: index.wrapping_mul(1500),
processing_latency: 20,
bitstream: &bitstream,
};
let now = at(w.now_ms);
let mut burst = |b: &FecBlock, rng: &mut SeqRng| {
rng.subset(usize::from(b.data_shards + b.parity_shards), usize::from(b.parity_shards) + 1)
};
let mut fine = within_budget;
let loss: LossPlan<'_> = if index == BURST { &mut burst } else { &mut fine };
let (lost, dups) =
send_frame(&mut packetizer, &mut receiver, &frame, announced.min_fec_packets, loss, &mut rng, now);
if index != BURST {
rebuilt += lost;
}
duplicates += dups;
sent.push((index, frame_type, bitstream));
w.run_for(16);
video_events(&mut receiver, at(w.now_ms), &mut video);
}
w.run_for(200);
video_events(&mut receiver, at(w.now_ms), &mut video);
// Every frame but the burst comes out byte-identical and in order; the burst is reported lost.
let lost: Vec<(u32, u32)> = video
.iter()
.filter_map(|e| if let VideoEvent::FrameLost { first, last } = e { Some((*first, *last)) } else { None })
.collect();
assert_eq!(lost, vec![(BURST, BURST)]);
let frames: Vec<_> =
video.iter().filter_map(|e| if let VideoEvent::Frame(f) = e { Some(f) } else { None }).collect();
let expected: Vec<_> = sent.iter().filter(|(i, _, _)| *i != BURST).collect();
assert_eq!(frames.len(), expected.len());
for (got, (index, frame_type, bitstream)) in frames.iter().zip(expected) {
assert_eq!(got.frame_index, *index);
assert_eq!(got.header.frame_type, *frame_type, "frame {index}");
assert_eq!(got.header.processing_latency, 20);
assert_eq!(got.rtp_timestamp, index.wrapping_mul(1500));
assert!(got.bitstream == *bitstream, "frame {index}: the bitstream differs");
}
let stats = receiver.stats();
assert!(rebuilt > 0);
assert_eq!(stats.shards_recovered, rebuilt as u64, "FEC rebuilt every data shard lost within the budget");
assert_eq!((stats.frames, stats.frames_lost, stats.packets_dropped), (frames.len() as u64, 1, duplicates as u64));
// The client asks for recovery over control: reference invalidation (the host offered it), and an IDR request
// (empty body, as above). The host sees both, then sends a recovery frame.
let t = at(w.now_ms);
w.client.send(t, &ClientMessage::InvalidateRefFrames { first: BURST, last: BURST });
w.client.send_empty(t, MessageType::IdrFrame);
assert_eq!(
host_receives(&mut w, 2),
vec![ClientControlMessage::InvalidateRefFrames { first: BURST, last: BURST }, ClientControlMessage::IdrRequest]
);
let index = sizes.len() as u32;
let bitstream = access_unit(&mut rng, 30_000, false);
let recovery = EncodedFrame {
frame_index: index,
frame_type: FrameType::Recovery,
rtp_timestamp: index * 1500,
processing_latency: 20,
bitstream: &bitstream,
};
send_frame(
&mut packetizer,
&mut receiver,
&recovery,
announced.min_fec_packets,
&mut within_budget,
&mut rng,
at(w.now_ms),
);
let mut after = Vec::new();
video_events(&mut receiver, at(w.now_ms), &mut after);
match after.as_slice() {
[VideoEvent::Frame(f)] => {
assert_eq!((f.frame_index, f.header.frame_type), (index, FrameType::Recovery));
assert!(f.bitstream == bitstream);
}
other => panic!("expected the recovery frame, got {other:?}"),
}
// Audio: Opus-sized packets sealed with the session keys; no parity, so lost packets come out as lost.
let mut audio_tx = AudioPacketizer::new(AudioPacketizerConfig {
cipher: announced.encryption.contains(EncryptionFlags::AUDIO).then(|| AudioCipher::new(&launched.keys)),
packet_duration_ms: announced.audio_packet_duration_ms,
parity: AudioParity::None,
first_sequence: 0,
first_timestamp_ms: 0,
})
.unwrap();
let mut audio_rx = AudioDepacketizer::new(AudioConfig {
cipher: negotiated.encryption.contains(EncryptionFlags::AUDIO).then(|| AudioCipher::new(&keys)),
packet_duration_ms: client_stream_config().audio_packet_duration_ms,
fec: AudioFec::Disabled,
loss_timeout: Duration::from_millis(20),
})
.unwrap();
let dropped = [6u16, 17, 18, 31];
let mut opus_sent = Vec::new();
let mut audio = Vec::new();
for sequence in 0..40u16 {
let len = 60 + rng.below(140);
let opus = rng.bytes(len);
let datagrams = audio_tx.packetize(&opus).unwrap();
assert_eq!(datagrams.len(), 1, "no parity packets (U16)");
let now = at(w.now_ms);
if !dropped.contains(&sequence) {
audio_rx.push(now, &datagrams[0]).unwrap();
}
opus_sent.push(opus);
w.run_for(5);
let now = at(w.now_ms);
if audio_rx.poll_timeout().is_some_and(|t| t <= now) {
audio_rx.handle_timeout(now).unwrap();
}
audio.extend(core::iter::from_fn(|| audio_rx.poll_event()));
}
let expected_audio: Vec<AudioEvent> = (0..40u16)
.map(|sequence| {
if dropped.contains(&sequence) {
AudioEvent::Lost { sequence }
} else {
AudioEvent::Packet {
sequence,
timestamp_ms: u32::from(sequence) * 5,
opus: opus_sent[usize::from(sequence)].clone(),
recovered: false,
}
}
})
.collect();
assert_eq!(audio, expected_audio, "in order, losses reported, nothing rebuilt");
assert_eq!((audio_rx.stats().lost, audio_rx.stats().recovered), (dropped.len() as u64, 0));
// Input: every kind the client sends arrives typed on the host, in order.
let inputs = vec![
InputEvent::MouseMoveRel { dx: -12, dy: 7 },
InputEvent::MouseMoveAbs { x: 1464, y: 528, width: 1919, height: 1079 },
InputEvent::MouseButton { pressed: true, button: MouseButton::Left },
InputEvent::MouseButton { pressed: false, button: MouseButton::Left },
InputEvent::Key { pressed: true, flags: 0, key_code: 0x41, modifiers: 0 },
InputEvent::Key { pressed: false, flags: 0, key_code: 0x41, modifiers: 0 },
InputEvent::Scroll { amount: -120 },
InputEvent::Gamepad(GamepadState {
controller: 0,
active_mask: 1,
buttons: ButtonFlags(ButtonFlags::A | ButtonFlags::DPAD_UP | ButtonFlags::PADDLE1),
left_trigger: 0x40,
right_trigger: 0xFF,
left_stick_x: -32768,
left_stick_y: 32767,
right_stick_x: 1200,
right_stick_y: -104,
}),
];
let t = at(w.now_ms);
for e in &inputs {
w.client.send(t, &ClientMessage::Input(e.clone()));
}
let typed: Vec<ClientControlMessage> = inputs.iter().cloned().map(ClientControlMessage::Input).collect();
assert_eq!(host_receives(&mut w, inputs.len()), typed);
// Rumble from the host reaches the client.
let t = at(w.now_ms);
w.host.h().send_rumble(t, 0, 0x4000, 0xC000).unwrap();
w.host.h().send_rumble_triggers(t, 0, 0x1000, 0x2000).unwrap();
assert!(w.run_until(w.now_ms + 10_000, |w| w.client.host_messages.len() >= 2));
assert_eq!(
w.client.host_messages,
vec![
HostMessage::Rumble { controller: 0, low_frequency: 0x4000, high_frequency: 0xC000 },
HostMessage::RumbleTriggers { controller: 0, left: 0x1000, right: 0x2000 },
]
);
// Nothing on control was dropped, timed out or stopped for want of pings.
assert!(
!w.host.events.iter().any(|e| matches!(
e,
ControlHostEvent::Dropped | ControlHostEvent::TimedOut | ControlHostEvent::PingTimedOut
))
);
// Graceful termination, then the ENet disconnect; both ends close. (Should the client's one acknowledgement of
// the disconnect be lost, the host gives up after its timeout, as stock ENet does.)
let t = at(w.now_ms);
w.host.h().send_termination(t, TERMINATION_GRACEFUL).unwrap();
w.host.h().close(t).unwrap();
assert!(w.run_until(w.now_ms + 30_000, |w| w.client.enet.state() == EnetState::Disconnected
&& w.host.host.as_ref().is_some_and(|h| h.enet().state() == EnetHostState::Disconnected)));
assert_eq!(w.client.host_messages.last(), Some(&HostMessage::Termination { error_code: Some(0x8003_0023) }));
assert_eq!(w.client.enet_events, vec![EnetEvent::Connected, EnetEvent::Disconnected { data: 0 }]);
// The client quits the game; the host is free again.
parse_status_response(&get(&mut host, &cancel_request(UID).unwrap(), &client, pin)).unwrap();
let info =
parse_server_info(&get(&mut host, &server_info_request(Scheme::Https, UID).unwrap(), &client, pin)).unwrap();
assert_eq!((info.paired, info.current_game, info.state.as_str()), (true, 0, "LUMEN_SERVER_FREE"));
}
#[test]
fn a_tessera_trusted_client_needs_no_pairing() {
let mut rng = SeqRng::new(0x7E55);
let client = client_identity("client");
let mut host = LumenHttp::new(2);
// The grant: the host records the client's certificate, the client gets the host's out of band. No PIN anywhere.
host.paired.push(PairedClient::trusted(client.cert_der()).unwrap());
let host_cert = ServerCert::from_der(host.identity.cert_der()).unwrap();
let pin = Some(&host_cert);
let info =
parse_server_info(&get(&mut host, &server_info_request(Scheme::Https, UID).unwrap(), &client, pin)).unwrap();
assert!(info.paired);
assert_eq!(parse_app_list(&get(&mut host, &app_list_request(UID).unwrap(), &client, pin)).unwrap(), host.apps);
let keys = SessionKeys::generate(&mut rng).unwrap();
let params = LaunchParams {
app_id: 1,
width: 1280,
height: 720,
fps: 30,
keys: keys.clone(),
hdr: false,
audio: AudioLayout::Stereo,
};
assert!(
parse_launch_response(&get(&mut host, &launch_request(&params, UID).unwrap(), &client, pin))
.unwrap()
.game_session
);
assert_eq!(host.launched.map(|l| l.keys), Some(keys));
assert!(host.pairing.is_none(), "no /pair call was made");
// The pin is what makes it safe: a host presenting another certificate is not the paired one.
let rogue_host = ServerCert::from_der(client_identity("rogue").cert_der()).unwrap();
assert_eq!(rogue_host.matches(host.identity.cert_der()), Ok(false));
assert_eq!(host_cert.matches(client_identity("rogue").cert_der()), Ok(false));
}
#[test]
fn an_unpaired_client_is_refused_over_https() {
let mut host = LumenHttp::new(3);
let paired_client = client_identity("client");
host.paired.push(PairedClient::trusted(paired_client.cert_der()).unwrap());
let stranger = client_identity("rogue");
let host_cert = ServerCert::from_der(host.identity.cert_der()).unwrap();
let pin = Some(&host_cert);
// serverinfo answers, but says "not paired"; everything else is refused.
let info =
parse_server_info(&get(&mut host, &server_info_request(Scheme::Https, UID).unwrap(), &stranger, pin)).unwrap();
assert!(!info.paired);
assert_err!(
parse_app_list(&get(&mut host, &app_list_request(UID).unwrap(), &stranger, pin)),
Error::HostStatus { code: 401 }
);
let keys = SessionKeys::generate(&mut SeqRng::new(4)).unwrap();
let params =
LaunchParams { app_id: 1, width: 1280, height: 720, fps: 30, keys, hdr: false, audio: AudioLayout::Stereo };
assert_err!(
parse_launch_response(&get(&mut host, &launch_request(&params, UID).unwrap(), &stranger, pin)),
Error::HostStatus { code: 401 }
);
assert!(host.launched.is_none());
// Plain HTTP never reaches the HTTPS routes either.
let over_http = HttpRequest { scheme: Scheme::Http, ..app_list_request(UID).unwrap() };
assert_err!(parse_app_list(&get(&mut host, &over_http, &paired_client, None)), Error::HostStatus { code: 401 });
}
+51
View File
@@ -1,5 +1,56 @@
# DomiStream — handover
## stream-v0.2.1 (2026-12-04)
Patch for Lumen L2: the client's `ControlStream` sends `START_B`, `PERIODIC_PING` and the IDR request with empty
bodies (PROTOCOL.md 3.3; `START_A` stays refused, U10), so our own clients can start and keep a stream on Lumen
(PR #15, tests first). Workspace 422 passed, 0 failed; clippy, fmt and rustdoc clean.
## stream-v0.2.0 (2026-12-04)
The GameStream host side, sans-I/O, for Lumen (milestone L1, `docs/LUMEN-HOST-PLAN.md` 3.1), next to the client of
v0.1.0. The host notes per protocol are listed at the top of `docs/PROTOCOL.md` ("Host side (Lumen)").
| Part | Module |
| :-- | :-- |
| request head and query parsing into typed routes, XML answers (serverinfo, applist, launch/resume, pair, errors) | `host::http` |
| the host's pairing machine (pending-PIN slot, proof and signature checks), Tessera-trusted clients without a PIN | `host::pairing` |
| RTSP session (order, `Session`, statuses), DESCRIBE writer, strict ANNOUNCE parser | `rtsp::server` |
| accepting ENet peer, as stock ENet 1.3 accepts | `enet::host` |
| control host: client frames (replay refusal), rumble, termination, stop deadline | `control::host` |
| video packetizer (FEC blocks with Cauchy parity, AES-GCM sealing), Opus audio packetizer (AES-CBC, no parity: U16) | `video::packetizer`, `audio::packetizer` |
Fixed on the client side (tests first, separate commits):
- **ENet session ids.** `EnetClient` took VERIFY_CONNECT's session ids the wrong way round (stock ENet: the client's
incoming id is the verify's incoming id). Hidden against a fresh slot (0/0); after a reconnect a stock host answers
with two different ids and the client would have dropped every host datagram. Found by the ENet host engineer.
- **Applist cap.** `MAX_APPS` was 4096, but 4096 apps of four elements need 16,385 XML elements (cap 16,384), so the
app cap could never be reached. Now 4095 = (`MAX_XML_ELEMENTS` − 1) / 4 on both sides.
Evidence (worktree checks, 2026-12-04, every cargo run gated on CPU and RAM below 90 % and drives below 95 %):
- `cargo test --workspace`: **422 passed, 0 failed**, among them `tests/session.rs`: a whole session between our
client and our host in memory (pairing with the owner typing the code, HTTPS, launch, RTSP, ENet + START_B, sealed
video with FEC repairing exactly the parity budget per block and a burst beyond it reported lost and answered with
invalidation and an IDR request, sealed audio, input, gamepad, rumble, termination), plus the Tessera-trusted path
and an unpaired client refused over HTTPS.
- Mutation pass on the host modules: **26 of 27 caught, 1 equivalent** (M25–M51, `docs/MUTATION.md`; M36 first survived and got a test; M39 is unreachable for a fresh peer slot); the client rows M1–M24 are those
of v0.1.0.
- Fuzz, host targets (module engineers; Windows MSVC, SanitizerCoverage, libFuzzer), **0 crashes**: host_http_request
8,784,228 runs in 75 s; host_pairing 45,096 in 75 s, then 778,128 in 601 s (lead, 2026-12-04); rtsp_server 895,897 in 121 s; announce 11,659,642 in 121 s;
enet_host 2,534,001 in 60 s, then 26,839,291 in 600 s; control_host 611,513 in 60 s; video_packetizer_roundtrip
113,740 in 76 s. 32 targets in all; the 25 client targets' runs are those of v0.1.0.
- clippy `-D warnings`, fmt and rustdoc `-D warnings` are clean.
Open:
- **Interop with real clients: pairing, serverinfo and applist measured.** Arena Domi Remote 0.1.2 in the Android
emulator paired with Arena's lumen-host L1 skeleton (this release's host side) over loopback and listed all games
(PROTOCOL.md, "Measured" [L1]). Streaming against a real client starts in L2. The Moonlight PC app is not
measured yet.
- **START_B, PERIODIC_PING, IDR request from our own client.** `ControlStream` refuses them (bodies U10); decided:
it sends them with empty bodies, with the first streaming client of L2. The session test sends them over
`EnetClient` + `ControlCipher`, as gs-probe does.
- Audio parity (U16), `HDR_MODE` and the plain `TERMINATION` are refused on the host until measured.
## stream-v0.1.0 (2026-11-26)
The GameStream client, sans-I/O, for Arena Domi TV (Play remotely Day 1).
+47
View File
@@ -44,3 +44,50 @@ caught; none failed to compile, so every row is a real behaviour change the test
- **M23.** The mutation compiled, against the cached getrandom 0.4.3, and the guard caught the source use. Since
27b26a9 the dependency tree has no getrandom at all.
- **Missing tests.** No mutation got through, so none were added.
## Host side (stream-v0.2.0)
27 rows for the host modules: **26 caught, 1 equivalent** (M39). M36 first survived and now has a test.
- **When:** 2026-12-04, on `feature/host-session` (the session engineer wrote M25-M51; the lead finished the run,
added the M36 test and re-ran M36). Rows may name several test binaries; the tool now runs with `--no-fail-fast`.
- **Driver:** as above, `python tools/mutation/mutate.py M25 ... M51`, output on E: through the resource gate.
| # | Area | Mutation | Test binary | Caught by | Result |
| :-- | :-- | :-- | :-- | :-- | :-- |
| M25 | host pairing phase | phase 4 accepted while phase 3 is expected (a skipped step) | host_pairing, session | `out_of_order_phases_are_refused` | caught |
| M26 | host pairing proof | the client's proof H_c is not compared (any PIN pairs) | host_pairing | `the_right_pin_but_a_forged_proof_is_a_wrong_pin`, `wrong_pin_is_caught_by_the_host_when_the_client_carries_on` | caught |
| M27 | host pairing phase 5 | phase 5 accepts any HTTPS client certificate | host_pairing | `phase_5_needs_https_with_the_phase_1_certificate` | caught |
| M28 | host HTTP cap | query parameter cap off by one (allows 33) | host_http | `query_caps` | caught |
| M29 | host HTTP body | a GET with Content-Length other than 0 accepted | host_http | `heads_that_are_refused` | caught |
| M30 | host HTTP answer | PairStatus 1 over plain HTTP too | host_http, session | `serverinfo_pair_status_per_scheme` | caught |
| M31 | RTSP order | PLAY accepted before ANNOUNCE | rtsp_server | `order_violations_get_455_and_change_nothing`, `server_random_sequences` | caught |
| M32 | RTSP order | a second SETUP of the same stream accepted | rtsp_server | `options_at_any_time_and_setup_once_each` | caught |
| M33 | RTSP session | a Session header with another id accepted once issued | rtsp_server | `session_id_is_random_hex_and_checked` | caught |
| M34 | ANNOUNCE | a known attribute given twice accepted (the first value kept) | rtsp_server | `announce_duplicates_and_unknowns`, `announce_hostile_lines` | caught |
| M35 | DESCRIBE | the refPicInvalidation line written exactly when not offered | rtsp_server, session | `client_and_server_negotiate_in_memory`, `describe_follows_the_offer`, `describe_lines_and_order`, `a_whole_session_between_our_client_and_our_host` | caught |
| M36 | ENet host ack | pings acknowledged before the verify is acknowledged | enet_host | `ping_before_the_verify_ack_is_not_acknowledged` | caught |
| M37 | ENet host ack | a datagram without sent time goes on after an acknowledged command | enet_host | `acknowledged_commands_need_the_sent_time` | caught |
| M38 | ENet host session id | host session ids taken from the wrong offered field | enet_host | `session_ids_follow_stock_enet` | caught |
| M39 | ENet host session id | the slot's previous session id not skipped | enet_host | none (see notes) | **equivalent** |
| M40 | ENet client session id | verify's session ids swapped again (the bug fixed for v0.2.0) | enet | `verify_session_ids_are_taken_as_stock_enet_takes_them` | caught |
| M41 | control host replay | a repeated client sequence number accepted (< instead of <=) | control_host | `replays_and_forgeries_are_dropped` | caught |
| M42 | control host replay | the client replay check removed | control_host | `client_sequence_at_u32_wrap`, `replays_and_forgeries_are_dropped` | caught |
| M43 | control host message | extended termination code written little-endian | control_host, session | `close_from_either_side`, `host_message_layouts`, `host_messages_reach_the_client`, `a_whole_session_between_our_client_and_our_host` | caught |
| M44 | control host stop | a PERIODIC_PING does not move the stop deadline | control_host, session | `no_periodic_ping_ends_the_session`, `stop_deadline_rules`, `a_whole_session_between_our_client_and_our_host` | caught |
| M45 | video parity order | parity computed after the parity headers are written (headers become parity) | video_packetizer, session | `a_whole_session_between_our_client_and_our_host`, `every_data_shard_lost_is_rebuilt_when_parity_covers_it`, `fixed_vector_cauchy_parity_k3_m1`, `fixed_vector_one_small_frame` and 9 more | caught |
| M46 | video parity | the client's minimum parity count ignored | video_packetizer | `fec_plan_properties`, `minimum_parity_raises_the_written_percentage` | caught |
| M47 | video parity | parity shard index written one too high | video_packetizer | `every_data_shard_lost_is_rebuilt_when_parity_covers_it`, `fixed_vector_cauchy_parity_k3_m1`, `fixed_vector_one_small_frame`, `encrypted_stream_round_trips_with_loss` and 8 more | caught |
| M48 | video nonce | the GCM nonce counter does not advance per datagram (nonce reuse) | video_packetizer | `encrypted_stream_round_trips_with_loss` | caught |
| M49 | audio IV | the host encrypts with the IV of the next sequence number | audio_packetizer, session | `audio_cipher_encrypt_matches_openssl_vectors`, `fixed_vector_encrypted`, `lost_packets_are_reported_and_the_rest_arrive`, `round_trip_encrypted_across_sequence_and_timestamp_wrap` and 3 more | caught |
| M50 | audio IV | IV counter written little-endian (both sides) | media, audio_packetizer | `audio_cipher_encrypt_matches_openssl_vectors`, `fixed_vector_encrypted`, `audio_iv_and_decrypt_match_openssl_vectors`, `audio_round_trip_through_the_oracle` | caught |
| M51 | audio block start | a first sequence number that is not a block start accepted | audio_packetizer | `config_refusals` | caught |
### Notes on the host rows
- **M36.** A ping that the client asks to have acknowledged, sent before it acknowledged the verify, was answered
with an ACK in the mutant and no test noticed. `ping_before_the_verify_ack_is_not_acknowledged` (enet_host) now
catches it.
- **M39, equivalent.** `next_session` skips "the value the slot used last", as stock ENet does when a slot is
reused. An `EnetHostPeer` is always a fresh slot, so it is called with `current` = 0xFF while the result is in
0..3: the branch can never run and removing it changes nothing. It is kept so the function matches stock ENet if
a peer slot is ever reused.
+70 -1
View File
@@ -1,10 +1,78 @@
# GameStream protocol, as DomiStream speaks it (client side)
# GameStream protocol, as DomiStream speaks it (client and host side)
The protocol between a GameStream host (Sunshine, later Lumen) and a client (Arena Domi TV). Written from the Wolf
protocol docs in our own words, completed with facts read in Moonshine (BSD-2). Every fact has a tag; every gap is
marked **UNKNOWN Un** with what would settle it. Status: 2026-11-25, implemented as stream-v0.1.0 per these docs and the approved sources; interop with a real host
is unverified (the lab capture was not run, [LAB_CAPTURE.md](LAB_CAPTURE.md)). U9 narrowed and U14 settled from the
approved sources (sections 3.1, 5.3); where an UNKNOWN remains, the code follows the Wolf-documented behaviour.
2026-12-04: the host side for Lumen added as stream-v0.2.0 (below).
## Host side (Lumen)
Since stream-v0.2.0 DomiStream also holds the host's half of every protocol, for Lumen, Arena Domi's own streaming
host ([LUMEN-HOST-PLAN.md](LUMEN-HOST-PLAN.md) 3.1). The wire is the one this document describes; what is a choice of
ours on the host side is marked as such in the host notes:
| Section | Host module | Host notes |
| :-- | :-- | :-- |
| 1.1-1.4 HTTP/HTTPS | `host::http` | strict request head and query parsing into typed routes; XML answers that the client's parsers accept; `PairStatus` 1 only over HTTPS with a paired certificate (1.2). Notes in the module docs |
| 1.5 Pairing | `host::pairing` | the mirror state machine with a pending-PIN slot; Tessera-trusted clients recorded without a PIN. Notes in the module docs |
| 2.2-2.4 RTSP | `rtsp::server` | 2.5: one session per launch, order, statuses, `Session`, DESCRIBE writer, strict ANNOUNCE parser |
| 3.1 ENet | `enet::host` | 3.1, "The accepting side, as stock ENet 1.3 does it" |
| 3.2-3.3 Control | `control::host` | 3.3, last paragraph: client frames, host messages, stop deadline |
| 5.2-5.3 Video | `video::packetizer` | 5.3, "Host side": FEC block split and parity |
| 6.2-6.4 Audio | `audio::packetizer` | 6.4, last paragraph: no parity until U16 |
Both halves are tested against each other in one in-memory session (`crates/domistream/tests/session.rs`). The
client's `ControlStream` sends `START_B`, `PERIODIC_PING` and the IDR request with empty bodies (lead's decision,
2026-12-04, since stream-v0.2.1): what Moonshine and Lumen read (3.3). Whether Sunshine reads more is still U10;
`START_A` stays refused. The host keeps the client's `updateState` (1.5, U1) for the logs without reading it.
### Measured: Arena Domi Remote against lumen-host [L1]
Our own black-box measurement (decision D2), 2026-12-04: Arena Domi Remote 0.1.2 (a GameStream client; its code is
never read) in the Android emulator on the reference PC, against Arena's lumen-host L1 skeleton (DomiStream
`337f6a7`) on loopback, HTTP 48989 / HTTPS 48984, reached as `10.0.2.2:48989`. Facts from lumen-host's request log
and the operator's notes:
- The client accepts a host entered as `address:port` and uses that port for HTTP; it then reached HTTPS on the port
serverinfo gave (`HttpsPort`). While unpaired it polls `/serverinfo` over HTTP every 0.5 to 2.5 s.
- Every request carries `uniqueid=0123456789ABCDEF` (the same on every request) and a parameter `uuid` with a fresh
random UUID per request (not in sections 1.1-1.5; the host ignores it).
- **Pairing (U1, for this client):** five requests in the order of 1.5, phase 4 (`clientpairingsecret`) before
phase 5; phases 1-4 over HTTP, phase 5 (`phrase=pairchallenge`) over HTTPS with the client certificate. Every
phase also carries `devicename` and `updateState=1`. With the code typed on the host the client showed the PC as
paired about 12 s after the code was entered. DomiStream's host pairing (1.5) and lumen-host's TLS (TLS 1.3 offered,
ALPN `h2` and `http/1.1`, a self-signed client certificate) were accepted without change.
- After pairing: `/serverinfo` and `/applist` over HTTPS; the client showed all 11 games of the applist.
- **Box art:** `/appasset?appid=<id>&AssetType=2&AssetIdx=0` over HTTPS for each app, retried about every 2 s while
it fails (lumen-host L1 answered 404; the client showed no covers).
- **Launch (U4, for this client):** `/launch` over HTTPS with `appid`, `mode` (`1280x720x60`), `additionalStates=1`,
`sops=1`, `rikey`, `rikeyid`, `localAudioPlayMode=0`, `surroundAudioInfo=196610`, `remoteControllersBitmap=0`,
`gcmap=0`, `gcpersist=0`, `corever=1`, plus `uniqueid` and `uuid`. An answer with HTTP status 503 is shown as
"Failed to start <game> (error 503)".
The other clients (the Moonlight PC app, Arena Domi TV) are measured when they connect.
**L2 demo, the same client against lumen-host with streaming (2026-12-04) [L1]:** pairing again in about 4 s from
the typed code; box art from `/appasset` shown for all 11 games; `/launch` (1280x720x60, `surroundAudioInfo=196610`)
answered with `sessionUrl0=rtsp://127.0.0.1:49010`. Then, for this client:
- **RTSP (U5):** one TCP connection per request, and the client **reads until the host closes the connection**; a
host that keeps it open makes every request wait for a timeout (measured: about 10.5 s per request against
lumen-host before its fix; Arena PR #56 now closes after every answer). Requests: OPTIONS (target
`rtsp://0.0.0.0:49010`; headers `CSeq`, `X-GS-ClientVersion: 14`, `Host`), DESCRIBE (adds `Accept`,
`If-Modified-Since`), SETUP `streamid=audio/0/0`, `streamid=video/0/0`, `streamid=control/13/0` (adds `Transport`;
`Session` from the second SETUP on), ANNOUNCE (on `streamid=control/13/0`, 1491 bytes), PLAY.
- **ANNOUNCE (U6):** 37 attributes, among them `x-nv-vqos[0].bitStreamFormat` = HEVC, viewport 1280x720, `maxFPS`
60, `packetSize` 1360, `configuredBitrateKbps` 10000, `x-ss-general.encryptionEnabled` 7, `minRequiredFecPackets`
2, `maxNumReferenceFrames` 1, `dynamicRangeMode` 0, `encoderCscMode` 2, stereo (`surround.enable` 0, 2 channels,
mask 3), `x-nv-aqos.packetDuration` 5; no `refPicInvalidation` line. Also sent: `x-ml-general.featureFlags`,
`x-nv-video[0].rateControlMode`, `timeoutLengthMs`, `framesWithInvalidRefThreshold`, `initialBitrateKbps`,
`initialPeakBitrateKbps`, `x-nv-vqos[0].bw.minimumBitrateKbps`/`maximumBitrateKbps`, `fec.enable`,
`videoQualityScoreUpdateTime`, `x-nv-general.featureFlags`, `useReliableUdp`, `bllFec.enable`, `drc.enable`,
`enableRecoveryMode`, `videoEncoderSlicesPerFrame`, `x-nv-clientSupportHevc`, `clientRefreshRateX100`.
- The client's own error text, when the RTSP handshake failed, named the GameStream default ports (TCP 48010, UDP
48000, 48010), not the ports it was using: it is a fixed text, not a statement of what it connected to.
- `/cancel` answered 200 with the ok root brings the client back to its game list without an error.
**Tags** (details in the source log, [CLEAN_ROOM.md](CLEAN_ROOM.md)):
@@ -13,6 +81,7 @@ approved sources (sections 3.1, 5.3); where an UNKNOWN remains, the code follows
| [W1]-[W7] | Wolf docs: index, pairing, RTSP, control, RTP video, RTP Opus, input (S-1 to S-7) |
| [M] | Moonshine `f184d5e` (S-9). A host implementation: we mirror its behaviour for the client. |
| [M*] | Moonshine, but the value has GPL provenance (Moonshine cites Sunshine or moonlight-common-c). Confirm by measurement before use. |
| [L1] | our own black-box measurement of Arena Domi Remote 0.1.2 against lumen-host, 2026-12-04 ("Measured" above) |
| [T] | tokio-enet `364628e` (S-10), approved 2026-11-25 |
| [E] | stock ENet v1.3.18 `2662c0d` (S-17), MIT, approved 2026-11-25 |
| [F] | fec-rs README and source `402f41f` (S-13, S-18), BSD-2, approved 2026-11-25 |
+1 -1
View File
@@ -236,7 +236,7 @@ dependencies = [
[[package]]
name = "domistream"
version = "0.1.0"
version = "0.2.1"
dependencies = [
"aes",
"aes-gcm",
+14 -3
View File
@@ -219,6 +219,13 @@ test = false
doc = false
bench = false
[[bin]]
name = "host_http_request"
path = "fuzz_targets/host_http_request.rs"
test = false
doc = false
bench = false
[[bin]]
name = "enet_host"
path = "fuzz_targets/enet_host.rs"
@@ -239,9 +246,6 @@ path = "fuzz_targets/announce.rs"
test = false
doc = false
bench = false
test = false
doc = false
bench = false
[[bin]]
name = "control_host"
@@ -249,3 +253,10 @@ path = "fuzz_targets/control_host.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"
);
}
});
+1 -1
View File
@@ -228,7 +228,7 @@ dependencies = [
[[package]]
name = "domistream"
version = "0.1.0"
version = "0.2.1"
dependencies = [
"aes",
"aes-gcm",
+87 -1
View File
@@ -127,6 +127,91 @@ mut("M23", "OS randomness", "getrandom added as a dependency and used in src/ent
"\n#[allow(dead_code)]\nfn os_fill(dest: &mut [u8]) {\n let _ = getrandom::fill(dest);\n}\n")])
# ---- host side (Lumen, stream-v0.2.0, 2026-12-04). `test` may name several test binaries, space-separated.
HP = SRC + "host/pairing.rs"
mut("M25", "host pairing phase", "phase 4 accepted while phase 3 is expected (a skipped step)", "host_pairing session",
[(HP, "(HostPairingState::AwaitClientPairingSecret, PairPhase::ClientPairingSecret(value)) => {",
"(HostPairingState::AwaitClientPairingSecret | HostPairingState::AwaitServerChallengeResp, "
"PairPhase::ClientPairingSecret(value)) => {")])
mut("M26", "host pairing proof", "the client's proof H_c is not compared (any PIN pairs)", "host_pairing",
[(HP, "if !ct_eq(&expected, &self.client_proof) {", "if false && !ct_eq(&expected, &self.client_proof) {")])
mut("M27", "host pairing phase 5", "phase 5 accepts any HTTPS client certificate", "host_pairing",
[(HP, "if !ct_eq(client_cert_der, &pending.cert_der) {", "if false && !ct_eq(client_cert_der, &pending.cert_der) {")])
HH = SRC + "host/http/mod.rs"
mut("M28", "host HTTP cap", "query parameter cap off by one (allows 33)", "host_http",
[(HH, 'cap("http query parameters", MAX_PARAMS, count)?;', 'cap("http query parameters", MAX_PARAMS + 1, count)?;')])
mut("M29", "host HTTP body", "a GET with Content-Length other than 0 accepted", "host_http",
[(HH, 'if content_length || value != "0" {', "if content_length {")])
mut("M30", "host HTTP answer", "PairStatus 1 over plain HTTP too", "host_http session",
[(SRC + "host/http/answer.rs", "let paired = scheme == Scheme::Https && client_paired;",
"let paired = client_paired;")])
RS = SRC + "rtsp/server/mod.rs"
mut("M31", "RTSP order", "PLAY accepted before ANNOUNCE", "rtsp_server",
[(RS, 'self.expect(RtspServerState::Play, "PLAY after ANNOUNCE").map_err(|e| refuse(455, e))?;',
'let _ = self.expect(RtspServerState::Play, "PLAY after ANNOUNCE");')])
mut("M32", "RTSP order", "a second SETUP of the same stream accepted", "rtsp_server",
[(RS, " if *slot {\n", " if *slot && false {\n")])
mut("M33", "RTSP session", "a Session header with another id accepted once issued", "rtsp_server",
[(RS, "Some(id) if !self.session_issued || id != self.session_id => {", "Some(id) if !self.session_issued => {")])
mut("M34", "ANNOUNCE", "a known attribute given twice accepted (the first value kept)", "rtsp_server",
[(SRC + "rtsp/server/announce.rs", 'Some(Some(_)) => return Err(malformed("announce: an attribute given twice")),',
"Some(Some(_)) => {}")])
mut("M35", "DESCRIBE", "the refPicInvalidation line written exactly when not offered", "rtsp_server session",
[(SRC + "rtsp/server/describe.rs", "if offer.reference_frame_invalidation {",
"if !offer.reference_frame_invalidation {")])
EH = SRC + "enet/host.rs"
mut("M36", "ENet host ack", "pings acknowledged before the verify is acknowledged", "enet_host",
[(EH, " CommandBody::Ping | CommandBody::BandwidthLimit { .. } | CommandBody::ThrottleConfigure { .. } => {\n"
" if c.acknowledge && connected {",
" CommandBody::Ping | CommandBody::BandwidthLimit { .. } | CommandBody::ThrottleConfigure { .. } => {\n"
" if c.acknowledge {")])
mut("M37", "ENet host ack", "a datagram without sent time goes on after an acknowledged command", "enet_host",
[(EH, "if wants_ack && sent_time.is_none() {", "if false && wants_ack && sent_time.is_none() {")])
mut("M38", "ENet host session id", "host session ids taken from the wrong offered field", "enet_host",
[(EH, "let out_session = next_session(p.incoming_session_id, FRESH_SESSION);\n"
" let in_session = next_session(p.outgoing_session_id, FRESH_SESSION);",
"let out_session = next_session(p.outgoing_session_id, FRESH_SESSION);\n"
" let in_session = next_session(p.incoming_session_id, FRESH_SESSION);")])
mut("M39", "ENet host session id", "the slot's previous session id not skipped", "enet_host",
[(EH, " if s == current {\n", " if false && s == current {\n")])
mut("M40", "ENet client session id", "verify's session ids swapped again (the bug fixed for v0.2.0)", "enet",
[(SRC + "enet/mod.rs", "self.in_session = p.incoming_session_id & 0x3;\n self.out_session = p.outgoing_session_id & 0x3;",
"self.in_session = p.outgoing_session_id & 0x3;\n self.out_session = p.incoming_session_id & 0x3;")])
CH = SRC + "control/host.rs"
mut("M41", "control host replay", "a repeated client sequence number accepted (< instead of <=)", "control_host",
[(CH, "if self.last_client_sequence.is_some_and(|last| sequence <= last) {",
"if self.last_client_sequence.is_some_and(|last| sequence < last) {")])
mut("M42", "control host replay", "the client replay check removed", "control_host",
[(CH, "if self.last_client_sequence.is_some_and(|last| sequence <= last) {",
"if self.last_client_sequence.is_some_and(|last| sequence <= last && false) {")])
mut("M43", "control host message", "extended termination code written little-endian", "control_host session",
[(CH, "framed(MessageType::TerminationExtended, &code.to_be_bytes())",
"framed(MessageType::TerminationExtended, &code.to_le_bytes())")])
mut("M44", "control host stop", "a PERIODIC_PING does not move the stop deadline", "control_host session",
[(CH, "self.deadline = self.deadline.max(now.saturating_add(self.timeout));", "self.deadline = self.deadline.max(now);")])
VP = SRC + "video/packetizer.rs"
mut("M45", "video parity order", "parity computed after the parity headers are written (headers become parity)",
"video_packetizer session",
[(VP, " ReedSolomon::new(k, m)?.encode(&mut shards)?;\n", ""),
(VP, " parity_packets += m as u64;",
" ReedSolomon::new(k, m)?.encode(&mut shards)?;\n parity_packets += m as u64;")])
mut("M46", "video parity", "the client's minimum parity count ignored", "video_packetizer",
[(VP, "if m < usize::from(min) { usize::from(min) } else { m }", "if m < usize::from(min) { m } else { m }")])
mut("M47", "video parity", "parity shard index written one too high", "video_packetizer",
[(VP, "let h = next_header(0, block, u16::try_from(k + j).unwrap_or(u16::MAX), b);",
"let h = next_header(0, block, u16::try_from(k + j + 1).unwrap_or(u16::MAX), b);")])
mut("M48", "video nonce", "the GCM nonce counter does not advance per datagram (nonce reuse)", "video_packetizer",
[(VP, " nonce += 1;\n", " nonce += 0;\n")])
mut("M49", "audio IV", "the host encrypts with the IV of the next sequence number", "audio_packetizer session",
[(SRC + "audio/mod.rs", "plaintext.len())?;\n let iv = self.iv(sequence)?;",
"plaintext.len())?;\n let iv = self.iv(sequence.wrapping_add(1))?;")])
mut("M50", "audio IV", "IV counter written little-endian (both sides)", "media audio_packetizer",
[(SRC + "audio/mod.rs", "self.rikeyid.wrapping_add(u32::from(sequence)).to_be_bytes();",
"self.rikeyid.wrapping_add(u32::from(sequence)).to_le_bytes();")])
mut("M51", "audio block start", "a first sequence number that is not a block start accepted", "audio_packetizer",
[(SRC + "audio/packetizer.rs", "if !config.first_sequence.is_multiple_of(4) {", "if false {")])
def sh(args, **kw):
return subprocess.run(args, cwd=REPO, capture_output=True, text=True, encoding="utf-8", errors="replace", **kw)
@@ -170,7 +255,8 @@ def main():
continue
apply(m["edits"])
try:
cmd = f"cargo test -j 2 --offline --test {m['test']} -- --test-threads=2 2>&1 | Out-File -Encoding utf8 {QA}\\mut-{m['id']}.log"
tests = " ".join(f"--test {t}" for t in m["test"].split())
cmd = f"cargo test -j 2 --offline --no-fail-fast {tests} -- --test-threads=2 2>&1 | Out-File -Encoding utf8 {QA}\\mut-{m['id']}.log"
gated(cmd)
log = open(os.path.join(QA, f"mut-{m['id']}.log"), encoding="utf-8-sig", errors="replace").read()
finally: