diff --git a/crates/domistream/src/host/http/answer.rs b/crates/domistream/src/host/http/answer.rs
index c34b597..0829b72 100644
--- a/crates/domistream/src/host/http/answer.rs
+++ b/crates/domistream/src/host/http/answer.rs
@@ -2,9 +2,16 @@
//! 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::{Error, Result};
+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)]
@@ -36,35 +43,173 @@ pub struct HostInfo {
pub state_prefix: String,
}
+/// Maximum length of an error's `status_message`, in bytes.
+pub const MAX_STATUS_MESSAGE_BYTES: usize = 256;
+
+/// Most apps one `applist` answer carries: the client's [`crate::http::applist::MAX_APPS`], lowered so the
+/// document stays within the client's [`crate::http::xml::MAX_XML_ELEMENTS`] (the root plus four elements per app).
+pub const MAX_WRITTEN_APPS: usize = {
+ let by_elements = (MAX_XML_ELEMENTS - 1) / 4;
+ if MAX_APPS < by_elements { MAX_APPS } else { by_elements }
+};
+
+/// The declaration every answer starts with.
+const DECLARATION: &str = "\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("&"),
+ '<' => out.push_str("<"),
+ '>' => out.push_str(">"),
+ '"' => out.push_str("""),
+ '\'' => out.push_str("'"),
+ _ => out.push(c),
+ }
+ }
+}
+
+/// `escaped text`.
+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, ``, `inner`, ``.
+fn ok_document(inner: &str) -> Vec {
+ format!("{DECLARATION}{inner}\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).
+/// (`client_paired`); over plain HTTP it is always 0 (`docs/PROTOCOL.md` 1.2). `SupportedDisplayMode` is written
+/// empty (its content is not documented).
///
/// # 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`].
+/// [`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> {
- let _ = (info, scheme, client_paired);
- Err(Error::Unimplemented)
+ 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::>().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 `` 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.
+/// [`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> {
- let _ = apps;
- Err(Error::Unimplemented)
+ // `42949672950` 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("");
+ 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("");
+ }
+ 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> {
+ 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://:` (`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`].
+/// [`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> {
- let _ = (rtsp_host, rtsp_port);
- Err(Error::Unimplemented)
+ session_xml(rtsp_host, rtsp_port)
}
/// `resume`: the same body as [`launch_xml`] (the client reads both with one parser).
@@ -72,42 +217,60 @@ pub fn launch_xml(rtsp_host: &str, rtsp_port: u16) -> Result> {
/// # Errors
/// As [`launch_xml`].
pub fn resume_xml(rtsp_host: &str, rtsp_port: u16) -> Result> {
- let _ = (rtsp_host, rtsp_port);
- Err(Error::Unimplemented)
+ session_xml(rtsp_host, rtsp_port)
}
/// A bare ``: the answer to `cancel` and `unpair`.
#[must_use]
pub fn ok_xml() -> Vec {
- Vec::new()
+ ok_document("")
}
/// 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`]).
+/// [`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> {
- let _ = answer;
- Err(Error::Unimplemented)
+ 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: `` (`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`].
+/// [`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> {
- let _ = (status_code, message);
- Err(Error::Unimplemented)
+ 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}\n").into_bytes())
}
-
-/// 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 }
-};
diff --git a/crates/domistream/src/host/http/mod.rs b/crates/domistream/src/host/http/mod.rs
index 92523db..b2fa763 100644
--- a/crates/domistream/src/host/http/mod.rs
+++ b/crates/domistream/src/host/http/mod.rs
@@ -11,7 +11,11 @@
//! [`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::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;
@@ -125,34 +129,315 @@ pub struct HostRequest {
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`].
+/// [`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