[domistream] Host HTTP: tests first (request head and query parsing, caps, XML answers read back by the client parsers); API stubs return Unimplemented

This commit is contained in:
2026-12-04 12:24:42 +01:00
parent 514565dbd7
commit 43bb6843c8
7 changed files with 1545 additions and 0 deletions
+113
View File
@@ -0,0 +1,113 @@
//! 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::host::pairing::PairAnswer;
use crate::http::{App, Scheme};
use crate::{Error, Result};
/// 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,
}
/// `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).
///
/// # Errors
/// [`Error::Malformed`] for an empty `hostname` or `unique_id`, a bad `state_prefix`, or control characters;
/// [`Error::TooLarge`] for a field over [`crate::http::serverinfo::MAX_SERVERINFO_FIELD_BYTES`].
pub fn server_info_xml(info: &HostInfo, scheme: Scheme, client_paired: bool) -> Result<Vec<u8>> {
let _ = (info, scheme, client_paired);
Err(Error::Unimplemented)
}
/// `applist`: one `<App>` per app with `AppTitle`, `ID` and `IsHdrSupported`, in the given order.
///
/// # Errors
/// [`Error::TooLarge`] over [`crate::http::applist::MAX_APPS`] apps or a title over
/// [`crate::http::applist::MAX_APP_TITLE_BYTES`]; [`Error::Malformed`] for a duplicate id or control characters.
pub fn app_list_xml(apps: &[App]) -> Result<Vec<u8>> {
let _ = apps;
Err(Error::Unimplemented)
}
/// `launch`: `gamesession=1` and `sessionUrl0=rtsp://<rtsp_host>:<rtsp_port>` (`docs/PROTOCOL.md` 1.4).
///
/// # Errors
/// [`Error::Malformed`] unless `rtsp_host` is a host name, an IPv4 address or a bracketed IPv6 literal and the
/// port is not 0; [`Error::TooLarge`] for a URL over [`crate::http::launch::MAX_SESSION_URL_BYTES`].
pub fn launch_xml(rtsp_host: &str, rtsp_port: u16) -> Result<Vec<u8>> {
let _ = (rtsp_host, rtsp_port);
Err(Error::Unimplemented)
}
/// `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>> {
let _ = (rtsp_host, rtsp_port);
Err(Error::Unimplemented)
}
/// A bare `<root status_code="200"/>`: the answer to `cancel` and `unpair`.
#[must_use]
pub fn ok_xml() -> Vec<u8> {
Vec::new()
}
/// One pairing answer: `paired` and the phase's element, hex-encoded (`docs/PROTOCOL.md` 1.5).
///
/// # Errors
/// [`Error::TooLarge`] for a value over the client's caps (a certificate over
/// [`crate::pairing::identity::MAX_CERT_PEM_BYTES`], a body over [`crate::pairing::MAX_PAIR_RESPONSE_BYTES`]).
pub fn pair_answer_xml(answer: &PairAnswer) -> Result<Vec<u8>> {
let _ = answer;
Err(Error::Unimplemented)
}
/// The error root: `<root status_code="<code>" status_message="<message>"/>` (`docs/PROTOCOL.md` 1.1).
///
/// # Errors
/// [`Error::Malformed`] for code 200 or a code outside 100..=999, or control characters in `message`;
/// [`Error::TooLarge`] for a message over [`MAX_STATUS_MESSAGE_BYTES`].
pub fn error_xml(status_code: u32, message: &str) -> Result<Vec<u8>> {
let _ = (status_code, message);
Err(Error::Unimplemented)
}
/// Maximum length of an error's `status_message`, in bytes.
pub const MAX_STATUS_MESSAGE_BYTES: usize = 256;
/// Most apps one `applist` answer carries: the client's [`crate::http::applist::MAX_APPS`], lowered so the
/// document stays within the client's [`crate::http::xml::MAX_XML_ELEMENTS`] (the root plus four elements per app).
pub const MAX_WRITTEN_APPS: usize = {
let by_elements = (crate::http::xml::MAX_XML_ELEMENTS - 1) / 4;
if crate::http::applist::MAX_APPS < by_elements { crate::http::applist::MAX_APPS } else { by_elements }
};
+176
View File
@@ -0,0 +1,176 @@
//! 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::PairRequest;
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)>,
}
/// 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`].
pub fn find_head_end(buf: &[u8]) -> Result<Option<usize>> {
let _ = buf;
Err(Error::Unimplemented)
}
/// Parses one complete request head (`GET <target> HTTP/1.1`, headers, the empty line, nothing after it).
///
/// # Errors
/// [`Error::TooLarge`] over a 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> {
let _ = head;
Err(Error::Unimplemented)
}
/// Parses a request target (`/path?query`) into a typed request.
///
/// # Errors
/// [`Error::TooLarge`] over a 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 _ = target;
Err(Error::Unimplemented)
}
/// 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)>> {
let _ = query;
Err(Error::Unimplemented)
}
/// 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 _ = params;
String::new()
}
+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};
+425
View File
@@ -0,0 +1,425 @@
//! 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;
use crate::pairing::{CHALLENGE_LEN, HASH_LEN, Pin, SALT_LEN, SECRET_LEN};
use crate::{Error, Instant, RandomSource, Result};
/// 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: crate::pairing::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> {
let _ = (rng, common_name, not_before_unix);
Err(Error::Unimplemented)
}
/// 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> {
let _ = (cert_der, key_pkcs8_der);
Err(Error::Unimplemented)
}
/// 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> {
let _ = cert_der;
Err(Error::Unimplemented)
}
/// 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> {
let _ = presented_der;
Err(Error::Unimplemented)
}
}
/// 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>,
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,
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,
}
}
/// Handles one `/pair` request. Draws randomness in phase 2 (host challenge and host secret).
///
/// # 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> {
let _ = (identity, request, transport, now, rng);
Err(Error::Unimplemented)
}
/// The owner typed the PIN: derives the key and returns the held answer to phase 1.
///
/// # Errors
/// [`Error::State`] unless the state is [`HostPairingState::AwaitPin`] (state unchanged); [`Error::TimedOut`]
/// past the PIN deadline (state becomes Failed); [`Error::Malformed`] for a different identity.
pub fn supply_pin(&mut self, identity: &HostIdentity, pin: Pin, now: Instant) -> Result<PairAnswer> {
let _ = (identity, pin, now);
Err(Error::Unimplemented)
}
/// 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) {}
/// When the session times out, if it is still in progress.
#[must_use]
pub fn poll_timeout(&self) -> Option<Instant> {
None
}
/// 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 {
let _ = now;
false
}
/// Where the handshake is.
#[must_use]
pub const fn state(&self) -> HostPairingState {
self.state
}
/// The client of phase 1 (for the owner's prompt and the grant check), once phase 1 has arrived.
#[must_use]
pub const fn pending_client(&self) -> Option<&PendingClient> {
self.pending.as_ref()
}
/// The paired client, once [`HostPairingState::Paired`].
#[must_use]
pub const fn paired_client(&self) -> Option<&PairedClient> {
self.paired.as_ref()
}
}
impl fmt::Debug for HostPairingSession {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("HostPairingSession")
.field("state", &self.state)
.field("deadline", &self.deadline)
.finish_non_exhaustive()
}
}
+2
View File
@@ -28,6 +28,7 @@
//! | [`fec`] | Reed-Solomon erasure coding over GF(2^8) | //! | [`fec`] | Reed-Solomon erasure coding over GF(2^8) |
//! | [`video`] | video depacketizer with FEC recovery and decryption (section 5) | //! | [`video`] | video depacketizer with FEC recovery and decryption (section 5) |
//! | [`audio`] | audio depacketizer with FEC recovery and decryption (section 6) | //! | [`audio`] | audio depacketizer with FEC recovery and decryption (section 6) |
//! | [`host`] | the host side, for Lumen: request parsing, XML answers and the host's pairing machine (sections 1, 1.5) |
//! //!
//! Opus and video decoding are not here: they belong to the platform layer (ArenaTV). //! Opus and video decoding are not here: they belong to the platform layer (ArenaTV).
@@ -40,6 +41,7 @@ pub mod enet;
pub mod entropy; pub mod entropy;
pub mod error; pub mod error;
pub mod fec; pub mod fec;
pub mod host;
pub mod http; pub mod http;
pub mod input; pub mod input;
pub mod keys; pub mod keys;
+18
View File
@@ -126,6 +126,20 @@ fn lying_inputs() -> Vec<Case> {
v.push(("pairing secret", vec![0; 17], |b| { v.push(("pairing secret", vec![0; 17], |b| {
common::implemented(&domistream::pairing::crypto::split_pairing_secret(b)) common::implemented(&domistream::pairing::crypto::split_pairing_secret(b))
})); }));
// Host HTTP: a request head claiming a 4 GiB body, and a query of empty segments and many short parameters.
v.push((
"host request head",
b"GET /launch?appid=1 HTTP/1.1\r\nContent-Length: 4294967295\r\n\r\n".to_vec(),
|b| common::implemented(&domistream::host::http::parse_request_head(b)),
));
let mut q = b"/serverinfo?".to_vec();
q.extend_from_slice(&b"&".repeat(4000));
q.extend_from_slice(&b"a=%41&".repeat(32));
v.push(("host target", q, |b| {
common::implemented(&domistream::host::http::parse_target(&String::from_utf8_lossy(b)))
}));
v.push(("host head end", vec![b'a'; 70_000], |b| common::implemented(&domistream::host::http::find_head_end(b))));
v v
} }
@@ -233,6 +247,10 @@ fn parsers_never_allocate_past_their_caps() {
("video", |b| common::implemented(&domistream::video::parse_video_packet(b))), ("video", |b| common::implemented(&domistream::video::parse_video_packet(b))),
("audio", |b| common::implemented(&domistream::audio::parse_audio_packet(b))), ("audio", |b| common::implemented(&domistream::audio::parse_audio_packet(b))),
("video decrypt", |b| common::implemented(&domistream::video::VideoCipher::new([2; 16]).decrypt(b))), ("video decrypt", |b| common::implemented(&domistream::video::VideoCipher::new([2; 16]).decrypt(b))),
("host request head", |b| common::implemented(&domistream::host::http::parse_request_head(b))),
("host target", |b| common::implemented(&domistream::host::http::parse_target(&String::from_utf8_lossy(b)))),
("host query", |b| common::implemented(&domistream::host::http::parse_query(&String::from_utf8_lossy(b)))),
("host head end", |b| common::implemented(&domistream::host::http::find_head_end(b))),
("audio decrypt", |b| { ("audio decrypt", |b| {
common::implemented( common::implemented(
&domistream::audio::AudioCipher::new(&SessionKeys { rikey: [2; 16], rikeyid: 0 }).decrypt(0, b), &domistream::audio::AudioCipher::new(&SessionKeys { rikey: [2; 16], rikeyid: 0 }).decrypt(0, b),
+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"),
(format!("uniqueid=a%26b&phrase=pairchallenge"), "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 - 3];
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 { .. })));
}