d62aa8f581
xml_depth_bomb_does_not_recurse: the closed half was 300 000 tag pairs
(2.1 MB), over MAX_XML_BYTES, so its `s.len() < MAX_XML_BYTES * 2` assert
failed and the depth check under it never ran (the protocol engineer was
right). Now 100 000 opens + 100 000 closes (about 0.7 MB): within the size
cap, it must be refused as TooLarge { max: MAX_XML_DEPTH }, without
recursion. The open-tags half is unchanged.
690 lines
29 KiB
Rust
690 lines
29 KiB
Rust
//! Hostile input for the HTTP side (`docs/PROTOCOL.md` 1.1-1.4): the XML reader, serverinfo, applist, launch and
|
|
//! status answers, and the request builders. Every case asserts a specific result.
|
|
|
|
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::indexing_slicing, missing_docs)]
|
|
|
|
mod common;
|
|
|
|
use common::{param, parse_query, xml_padded_to, xml_root};
|
|
use domistream::Error;
|
|
use domistream::http::xml::{
|
|
self, MAX_XML_ATTRIBUTES, MAX_XML_BYTES, MAX_XML_DEPTH, MAX_XML_ELEMENTS, MAX_XML_TEXT_BYTES,
|
|
};
|
|
use domistream::http::{self, Scheme};
|
|
use proptest::prelude::*;
|
|
|
|
/// Asserts `Err(TooLarge { max, .. })` for caps where `actual` is a count the parser chooses how to report.
|
|
macro_rules! assert_cap {
|
|
($e:expr, $max:expr) => {
|
|
match $e {
|
|
Err(Error::TooLarge { max, .. }) => assert_eq!(max, $max, "TooLarge.max"),
|
|
other => panic!("expected Err(TooLarge {{ max: {} }}), got {:?}", $max, other),
|
|
}
|
|
};
|
|
}
|
|
|
|
// ================================================================================================ XML
|
|
|
|
#[test]
|
|
fn xml_minimal_documents() {
|
|
let d = xml::parse(br#"<root status_code="200"/>"#).unwrap();
|
|
assert_eq!(d.status_code, 200);
|
|
assert_eq!(d.status_message, None);
|
|
assert_eq!(d.root.name, "root");
|
|
assert!(d.root.children.is_empty());
|
|
|
|
let d = xml::parse(br#"<?xml version="1.0" encoding="utf-8"?><root status_code="200"></root>"#).unwrap();
|
|
assert_eq!(d.status_code, 200);
|
|
|
|
let d = xml::parse(br#"<root status_code="401" status_message="The client is not authorized"/>"#).unwrap();
|
|
assert_eq!(d.status_code, 401, "xml::parse reports the status; refusing it is the callers' job");
|
|
assert_eq!(d.status_message.as_deref(), Some("The client is not authorized"));
|
|
}
|
|
|
|
#[test]
|
|
fn xml_tree_text_and_attributes() {
|
|
let d = xml::parse(br#"<root status_code="200" a="1"><x k="v&w">t1<y/>t2</x><z><>&"'AB</z></root>"#)
|
|
.unwrap();
|
|
assert_eq!(d.root.attributes, vec![("status_code".into(), "200".into()), ("a".into(), "1".into())]);
|
|
let x = &d.root.children[0];
|
|
assert_eq!(x.name, "x");
|
|
assert_eq!(x.attributes, vec![("k".into(), "v&w".into())]);
|
|
assert_eq!(x.text, "t1t2", "text is concatenated around child elements");
|
|
assert_eq!(x.children[0].name, "y");
|
|
assert_eq!(d.root.children[1].text, "<>&\"'AB");
|
|
}
|
|
|
|
#[test]
|
|
fn xml_text_is_not_trimmed() {
|
|
let d = xml::parse(b"<root status_code=\"200\"><a> x \n</a></root>").unwrap();
|
|
assert_eq!(d.root.children[0].text, " x \n");
|
|
}
|
|
|
|
#[test]
|
|
fn xml_empty_and_tiny_inputs() {
|
|
assert_err!(xml::parse(b""), Error::Malformed { .. });
|
|
assert_err!(xml::parse(b"<"), Error::Malformed { .. });
|
|
assert_err!(xml::parse(b"x"), Error::Malformed { .. });
|
|
assert_err!(xml::parse(b"<root"), Error::Malformed { .. });
|
|
assert_err!(xml::parse(b"<root status_code=\"200\">"), Error::Malformed { .. }, "unclosed root");
|
|
}
|
|
|
|
#[test]
|
|
fn xml_refuses_non_documents() {
|
|
for (bad, why) in [
|
|
(&br#"<other status_code="200"/>"#[..], "root must be `root`"),
|
|
(br#"<root/>"#, "no status_code"),
|
|
(br#"<root status_code="abc"/>"#, "status_code not decimal"),
|
|
(br#"<root status_code=""/>"#, "empty status_code"),
|
|
(br#"<root status_code="99999999999"/>"#, "status_code over u32"),
|
|
(br#"<root status_code="-200"/>"#, "negative status_code"),
|
|
(br#"<root status_code=200/>"#, "unquoted attribute"),
|
|
(br#"<root status_code="200" status_code="200"/>"#, "duplicate attribute"),
|
|
(br#"<root status_code="200"><a></b></root>"#, "mismatched end tag"),
|
|
(br#"<root status_code="200"><a></root>"#, "unclosed child"),
|
|
(br#"<root status_code="200"/><root status_code="200"/>"#, "two roots"),
|
|
(br#"<root status_code="200"/>garbage"#, "text after the root"),
|
|
(br#"<root status_code="200">&unknown;</root>"#, "unknown entity"),
|
|
(br#"<root status_code="200">&</root>"#, "entity without ;"),
|
|
(br#"<root status_code="200">a & b</root>"#, "bare &"),
|
|
(br#"<root status_code="200">�</root>"#, "NUL character reference"),
|
|
(br#"<root status_code="200">�</root>"#, "surrogate character reference"),
|
|
(br#"<root status_code="200">�</root>"#, "character reference past Unicode"),
|
|
(br#"<root status_code="200">�</root>"#, "overflowing character reference"),
|
|
(br#"<root status_code="200">&#xZZ;</root>"#, "bad hex reference"),
|
|
(br#"<root status_code="200"><a b="<"/></root>"#, "< in attribute value"),
|
|
(br#"<!DOCTYPE root><root status_code="200"/>"#, "DTD"),
|
|
(
|
|
br#"<?xml version="1.0"?><!DOCTYPE r [<!ENTITY a "aaaa">]><root status_code="200">&a;</root>"#,
|
|
"entity declaration",
|
|
),
|
|
(br#"<root status_code="200"><?pi data?></root>"#, "processing instruction in the body"),
|
|
(br#" <?xml version="1.0"?><root status_code="200"/>"#, "XML declaration not at the start"),
|
|
(br#"<root xmlns:a="urn:x" status_code="200"><a:b/></root>"#, "namespaces"),
|
|
(b"<root status_code=\"200\">\xff\xfe</root>", "not UTF-8"),
|
|
(b"<root status_code=\"200\">\xc3</root>", "truncated UTF-8"),
|
|
(br#"<1root status_code="200"/>"#, "bad name"),
|
|
] {
|
|
assert_err!(xml::parse(bad), Error::Malformed { .. }, "{why}");
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn xml_billion_laughs_is_refused_without_expansion() {
|
|
let mut doc = String::from("<?xml version=\"1.0\"?><!DOCTYPE lolz [<!ENTITY lol \"lol\">");
|
|
for i in 1..10 {
|
|
doc.push_str(&format!("<!ENTITY lol{i} \"{}\">", format!("&lol{};", i - 1).repeat(10)));
|
|
}
|
|
doc.push_str("]><root status_code=\"200\">&lol9;</root>");
|
|
assert_err!(xml::parse(doc.as_bytes()), Error::Malformed { .. });
|
|
}
|
|
|
|
#[test]
|
|
fn xml_size_boundaries() {
|
|
// max-1 and max are fine (a valid document of exactly that size), max+1 is refused before parsing.
|
|
for len in [MAX_XML_BYTES - 1, MAX_XML_BYTES] {
|
|
let d = xml::parse(&xml_padded_to("", len)).unwrap_or_else(|e| panic!("{len} bytes: {e:?}"));
|
|
assert_eq!(d.status_code, 200);
|
|
}
|
|
let over = xml_padded_to("", MAX_XML_BYTES + 1);
|
|
assert_too_large!(xml::parse(&over), MAX_XML_BYTES, MAX_XML_BYTES + 1);
|
|
// Huge: refused on size alone, whatever the content.
|
|
let huge = vec![b'<'; 4 * MAX_XML_BYTES];
|
|
assert_too_large!(xml::parse(&huge), MAX_XML_BYTES, 4 * MAX_XML_BYTES);
|
|
}
|
|
|
|
fn nested(depth: usize) -> Vec<u8> {
|
|
// root is depth 1
|
|
let mut s = String::from("<root status_code=\"200\">");
|
|
for _ in 1..depth {
|
|
s.push_str("<a>");
|
|
}
|
|
for _ in 1..depth {
|
|
s.push_str("</a>");
|
|
}
|
|
s.push_str("</root>");
|
|
s.into_bytes()
|
|
}
|
|
|
|
#[test]
|
|
fn xml_depth_cap() {
|
|
let d = xml::parse(&nested(MAX_XML_DEPTH)).unwrap();
|
|
let mut e = &d.root;
|
|
let mut depth = 1;
|
|
while let Some(c) = e.children.first() {
|
|
e = c;
|
|
depth += 1;
|
|
}
|
|
assert_eq!(depth, MAX_XML_DEPTH);
|
|
assert_cap!(xml::parse(&nested(MAX_XML_DEPTH + 1)), MAX_XML_DEPTH);
|
|
}
|
|
|
|
#[test]
|
|
fn xml_depth_bomb_does_not_recurse() {
|
|
// 300 000 open tags in under 1 MiB: a recursive parser overflows the stack; a strict one stops at depth 9.
|
|
let mut s = String::from("<root status_code=\"200\">");
|
|
s.push_str(&"<a>".repeat(300_000));
|
|
assert!(s.len() < MAX_XML_BYTES);
|
|
assert_cap!(xml::parse(s.as_bytes()), MAX_XML_DEPTH);
|
|
// A closed, well-formed bomb that fits under the size cap (100 000 opens + 100 000 closes, about 0.7 MB): still
|
|
// refused at depth 9, never parsed by recursion. (The earlier 300 000-pair version was 2.1 MB, over the size
|
|
// cap, so its depth check never ran: ruled wrong 2026-11-26.)
|
|
let mut closed = String::from("<root status_code=\"200\">");
|
|
closed.push_str(&"<a>".repeat(100_000));
|
|
closed.push_str(&"</a>".repeat(100_000));
|
|
closed.push_str("</root>");
|
|
assert!(closed.len() <= MAX_XML_BYTES, "{} bytes must fit the size cap", closed.len());
|
|
assert_cap!(xml::parse(closed.as_bytes()), MAX_XML_DEPTH);
|
|
}
|
|
|
|
#[test]
|
|
fn xml_element_cap() {
|
|
let ok = xml_root(200, &"<a/>".repeat(MAX_XML_ELEMENTS - 1));
|
|
assert_eq!(xml::parse(&ok).unwrap().root.children.len(), MAX_XML_ELEMENTS - 1);
|
|
let over = xml_root(200, &"<a/>".repeat(MAX_XML_ELEMENTS));
|
|
assert_cap!(xml::parse(&over), MAX_XML_ELEMENTS);
|
|
}
|
|
|
|
#[test]
|
|
fn xml_attribute_cap() {
|
|
let attrs = |n: usize| (1..n).map(|i| format!(" a{i}=\"{i}\"")).collect::<String>();
|
|
let ok = format!("<root status_code=\"200\"{}/>", attrs(MAX_XML_ATTRIBUTES));
|
|
assert_eq!(xml::parse(ok.as_bytes()).unwrap().root.attributes.len(), MAX_XML_ATTRIBUTES);
|
|
let over = format!("<root status_code=\"200\"{}/>", attrs(MAX_XML_ATTRIBUTES + 1));
|
|
assert_cap!(xml::parse(over.as_bytes()), MAX_XML_ATTRIBUTES);
|
|
}
|
|
|
|
#[test]
|
|
fn xml_text_cap_counts_unescaped_bytes() {
|
|
let ok = xml_root(200, &format!("<t>{}</t>", "a".repeat(MAX_XML_TEXT_BYTES)));
|
|
assert_eq!(xml::parse(&ok).unwrap().root.children[0].text.len(), MAX_XML_TEXT_BYTES);
|
|
let over = xml_root(200, &format!("<t>{}</t>", "a".repeat(MAX_XML_TEXT_BYTES + 1)));
|
|
assert_cap!(xml::parse(&over), MAX_XML_TEXT_BYTES);
|
|
// 5 raw bytes per unescaped byte: the cap is on the result, not the input.
|
|
let ok = xml_root(200, &format!("<t>{}</t>", "&".repeat(MAX_XML_TEXT_BYTES)));
|
|
assert_eq!(xml::parse(&ok).unwrap().root.children[0].text.len(), MAX_XML_TEXT_BYTES);
|
|
let over = xml_root(200, &format!("<t>{}</t>", "&".repeat(MAX_XML_TEXT_BYTES + 1)));
|
|
assert_cap!(xml::parse(&over), MAX_XML_TEXT_BYTES);
|
|
}
|
|
|
|
// ------------------------------------------------------------------------------------------------ XML properties
|
|
|
|
#[derive(Clone, Debug)]
|
|
struct Tree {
|
|
name: String,
|
|
attrs: Vec<(String, String)>,
|
|
text: String,
|
|
children: Vec<Tree>,
|
|
}
|
|
|
|
fn escape(s: &str) -> String {
|
|
s.replace('&', "&").replace('<', "<").replace('>', ">").replace('"', """).replace('\'', "'")
|
|
}
|
|
|
|
fn serialize(t: &Tree, out: &mut String) {
|
|
out.push('<');
|
|
out.push_str(&t.name);
|
|
for (k, v) in &t.attrs {
|
|
out.push_str(&format!(" {k}=\"{}\"", escape(v)));
|
|
}
|
|
out.push('>');
|
|
out.push_str(&escape(&t.text));
|
|
for c in &t.children {
|
|
serialize(c, out);
|
|
}
|
|
out.push_str(&format!("</{}>", t.name));
|
|
}
|
|
|
|
fn same(e: &xml::Element, t: &Tree) -> bool {
|
|
e.name == t.name
|
|
&& e.attributes == t.attrs
|
|
&& e.text == t.text
|
|
&& e.children.len() == t.children.len()
|
|
&& e.children.iter().zip(&t.children).all(|(a, b)| same(a, b))
|
|
}
|
|
|
|
fn tree(depth: u32) -> impl Strategy<Value = Tree> {
|
|
// No leading x/X: names starting with "xml" are reserved, and `xmlns` would be a namespace declaration.
|
|
let name = "[a-wA-W][a-zA-Z0-9_]{0,6}";
|
|
let text = "[ -~&<>\"'é]{0,12}";
|
|
let attrs = proptest::collection::btree_map("[a-w][a-z0-9]{0,4}", text, 0..3)
|
|
.prop_map(|m| m.into_iter().filter(|(k, _)| k != "status_code").collect::<Vec<_>>());
|
|
let leaf = (name, attrs.clone(), text).prop_map(|(name, attrs, text)| Tree {
|
|
name: name.to_string(),
|
|
attrs,
|
|
text,
|
|
children: vec![],
|
|
});
|
|
leaf.prop_recursive(depth, 24, 4, move |inner| {
|
|
("[a-wA-W][a-zA-Z0-9_]{0,6}", attrs.clone(), "[ -~]{0,8}", proptest::collection::vec(inner, 0..4))
|
|
.prop_map(|(name, attrs, text, children)| Tree { name, attrs, text, children })
|
|
})
|
|
}
|
|
|
|
proptest! {
|
|
#![proptest_config(ProptestConfig { cases: 256, ..ProptestConfig::default() })]
|
|
|
|
/// Serialize a random tree (depth <= MAX_XML_DEPTH - 1 under root), parse it back, get the same tree.
|
|
#[test]
|
|
fn xml_round_trips_generated_trees(children in proptest::collection::vec(tree(5), 0..4), code in 100u32..600) {
|
|
let root = Tree {
|
|
name: "root".into(),
|
|
attrs: vec![("status_code".into(), code.to_string())],
|
|
text: String::new(),
|
|
children,
|
|
};
|
|
let mut s = String::new();
|
|
serialize(&root, &mut s);
|
|
let d = xml::parse(s.as_bytes()).map_err(|e| TestCaseError::fail(format!("{e:?} for {s}")))?;
|
|
prop_assert_eq!(d.status_code, code);
|
|
prop_assert!(same(&d.root, &root), "tree differs for {}", s);
|
|
}
|
|
|
|
/// Arbitrary bytes: never panics; any success respects every cap.
|
|
#[test]
|
|
fn xml_never_panics_and_respects_caps(data in proptest::collection::vec(any::<u8>(), 0..2048)) {
|
|
let parsed = xml::parse(&data);
|
|
prop_assert!(common::implemented(&parsed));
|
|
if let Ok(d) = parsed {
|
|
fn walk(e: &xml::Element, depth: usize, count: &mut usize) -> bool {
|
|
*count += 1;
|
|
depth <= MAX_XML_DEPTH
|
|
&& e.attributes.len() <= MAX_XML_ATTRIBUTES
|
|
&& e.text.len() <= MAX_XML_TEXT_BYTES
|
|
&& e.children.iter().all(|c| walk(c, depth + 1, count))
|
|
}
|
|
let mut count = 0;
|
|
prop_assert!(walk(&d.root, 1, &mut count));
|
|
prop_assert!(count <= MAX_XML_ELEMENTS);
|
|
prop_assert_eq!(d.root.name.as_str(), "root");
|
|
}
|
|
}
|
|
|
|
/// Mutating a valid document (one byte flipped, truncated) never panics, and truncation is always an error.
|
|
#[test]
|
|
fn xml_truncation_is_an_error(cut in 0usize..60) {
|
|
let doc = br#"<root status_code="200"><a k="v">text&</a><b/></root>"#;
|
|
let cut = cut.min(doc.len() - 1);
|
|
let r = xml::parse(&doc[..cut]);
|
|
prop_assert!(matches!(r, Err(Error::Malformed { .. } | Error::Truncated { .. })), "{:?}", r);
|
|
}
|
|
}
|
|
|
|
// ================================================================================================ serverinfo
|
|
|
|
const SERVERINFO: &str = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<root status_code=\"200\">\n\
|
|
<hostname>LAB-PC</hostname>\n<appversion>7.1.431.-1</appversion>\n<GfeVersion>3.23.0.74</GfeVersion>\n\
|
|
<uniqueid>0123456789ABCDEF0123456789ABCDEF</uniqueid>\n<HttpsPort>47984</HttpsPort>\n\
|
|
<ExternalPort>47989</ExternalPort>\n<mac>00:11:22:aa:BB:ff</mac>\n<LocalIP>192.0.2.10</LocalIP>\n\
|
|
<MaxLumaPixelsHEVC>1869449984</MaxLumaPixelsHEVC>\n<ServerCodecModeSupport>259</ServerCodecModeSupport>\n\
|
|
<SupportedDisplayMode></SupportedDisplayMode>\n<PairStatus>0</PairStatus>\n<currentgame>0</currentgame>\n\
|
|
<state>SUNSHINE_SERVER_FREE</state>\n</root>\n";
|
|
|
|
fn serverinfo_with(field: &str, value: Option<&str>) -> Vec<u8> {
|
|
let open = format!("<{field}>");
|
|
let close = format!("</{field}>");
|
|
let start = SERVERINFO.find(&open).unwrap_or_else(|| panic!("{field} in sample"));
|
|
let end = SERVERINFO[start..].find(&close).unwrap() + start + close.len();
|
|
let replacement = value.map(|v| format!("{open}{v}{close}")).unwrap_or_default();
|
|
format!("{}{}{}", &SERVERINFO[..start], replacement, &SERVERINFO[end..]).into_bytes()
|
|
}
|
|
|
|
#[test]
|
|
fn serverinfo_sample() {
|
|
let s = http::parse_server_info(SERVERINFO.as_bytes()).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, "SUNSHINE_SERVER_FREE");
|
|
assert!(!s.is_busy().unwrap());
|
|
}
|
|
|
|
#[test]
|
|
fn serverinfo_optional_fields() {
|
|
let s = http::parse_server_info(&serverinfo_with("mac", Some(""))).unwrap();
|
|
assert_eq!(s.mac, None, "empty mac is None");
|
|
let s = http::parse_server_info(&serverinfo_with("GfeVersion", None)).unwrap();
|
|
assert_eq!(s.gfe_version, None);
|
|
let s = http::parse_server_info(&serverinfo_with("ExternalPort", None)).unwrap();
|
|
assert_eq!(s.http_port, None);
|
|
let s = http::parse_server_info(&serverinfo_with("PairStatus", Some("1"))).unwrap();
|
|
assert!(s.paired);
|
|
}
|
|
|
|
#[test]
|
|
fn serverinfo_busy() {
|
|
let s = http::parse_server_info(&serverinfo_with("state", Some("SUNSHINE_SERVER_BUSY"))).unwrap();
|
|
assert!(s.is_busy().unwrap());
|
|
let s = http::parse_server_info(&serverinfo_with("currentgame", Some("881448767"))).unwrap();
|
|
assert_eq!(s.current_game, 881_448_767);
|
|
assert!(s.is_busy().unwrap());
|
|
}
|
|
|
|
#[test]
|
|
fn serverinfo_refuses_bad_fields() {
|
|
for field in ["hostname", "uniqueid", "HttpsPort"] {
|
|
assert_err!(http::parse_server_info(&serverinfo_with(field, None)), Error::Malformed { .. }, "missing {field}");
|
|
}
|
|
for (field, value) in [
|
|
("HttpsPort", "70000"),
|
|
("HttpsPort", "-1"),
|
|
("HttpsPort", ""),
|
|
("HttpsPort", "0x1F"),
|
|
("HttpsPort", " 47984"),
|
|
("ExternalPort", "65536"),
|
|
("currentgame", "abc"),
|
|
("currentgame", "4294967296"),
|
|
("MaxLumaPixelsHEVC", "1e9"),
|
|
("ServerCodecModeSupport", "-3"),
|
|
("mac", "00:11:22:33:44"),
|
|
("mac", "00:11:22:33:44:55:66"),
|
|
("mac", "zz:11:22:33:44:55"),
|
|
] {
|
|
assert_err!(
|
|
http::parse_server_info(&serverinfo_with(field, Some(value))),
|
|
Error::Malformed { .. },
|
|
"{field}={value:?}"
|
|
);
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn serverinfo_field_cap() {
|
|
use domistream::http::serverinfo::MAX_SERVERINFO_FIELD_BYTES as MAX;
|
|
let ok = "h".repeat(MAX);
|
|
assert_eq!(http::parse_server_info(&serverinfo_with("hostname", Some(&ok))).unwrap().hostname, ok);
|
|
assert_cap!(http::parse_server_info(&serverinfo_with("hostname", Some(&"h".repeat(MAX + 1)))), MAX);
|
|
assert_cap!(http::parse_server_info(&serverinfo_with("state", Some(&"s".repeat(MAX + 1)))), MAX);
|
|
}
|
|
|
|
#[test]
|
|
fn serverinfo_status_and_sizes() {
|
|
use domistream::http::serverinfo::MAX_SERVERINFO_BYTES as MAX;
|
|
assert_err!(http::parse_server_info(&xml_root(503, "")), Error::HostStatus { code: 503 });
|
|
assert_err!(http::parse_server_info(b""), Error::Malformed { .. });
|
|
assert_err!(http::parse_server_info(b"<"), Error::Malformed { .. });
|
|
let inner = SERVERINFO
|
|
.trim_start_matches("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<root status_code=\"200\">")
|
|
.trim_end_matches("</root>\n");
|
|
for len in [MAX - 1, MAX] {
|
|
let s = http::parse_server_info(&xml_padded_to(inner, len)).unwrap_or_else(|e| panic!("{len}: {e:?}"));
|
|
assert_eq!(s.hostname, "LAB-PC");
|
|
}
|
|
assert_too_large!(http::parse_server_info(&xml_padded_to(inner, MAX + 1)), MAX, MAX + 1);
|
|
assert_too_large!(http::parse_server_info(&vec![b' '; 64 * MAX]), MAX, 64 * MAX);
|
|
}
|
|
|
|
// ================================================================================================ applist
|
|
|
|
#[test]
|
|
fn applist_sample() {
|
|
let body = xml_root(
|
|
200,
|
|
"<App><IsHdrSupported>1</IsHdrSupported><AppTitle>Desktop</AppTitle><ID>881448767</ID></App>\
|
|
<App><AppTitle>Steam & Friends</AppTitle><ID>2</ID><IsHdrSupported>0</IsHdrSupported></App>\
|
|
<App><AppTitle>No HDR field</AppTitle><ID>3</ID></App>",
|
|
);
|
|
let apps = http::parse_app_list(&body).unwrap();
|
|
assert_eq!(
|
|
apps,
|
|
vec![
|
|
http::App { id: 881_448_767, title: "Desktop".into(), hdr_supported: true },
|
|
http::App { id: 2, title: "Steam & Friends".into(), hdr_supported: false },
|
|
http::App { id: 3, title: "No HDR field".into(), hdr_supported: false },
|
|
]
|
|
);
|
|
assert_eq!(http::parse_app_list(&xml_root(200, "")).unwrap(), vec![]);
|
|
}
|
|
|
|
#[test]
|
|
fn applist_refuses_bad_apps() {
|
|
for (inner, why) in [
|
|
("<App><AppTitle>A</AppTitle></App>", "no ID"),
|
|
("<App><ID>1</ID></App>", "no AppTitle"),
|
|
("<App><AppTitle>A</AppTitle><ID>-1</ID></App>", "negative ID"),
|
|
("<App><AppTitle>A</AppTitle><ID>abc</ID></App>", "ID not decimal"),
|
|
("<App><AppTitle>A</AppTitle><ID>4294967296</ID></App>", "ID over u32"),
|
|
("<App><AppTitle>A</AppTitle><ID>1</ID></App><App><AppTitle>B</AppTitle><ID>1</ID></App>", "duplicate ID"),
|
|
] {
|
|
assert_err!(http::parse_app_list(&xml_root(200, inner)), Error::Malformed { .. }, "{why}");
|
|
}
|
|
assert_err!(http::parse_app_list(&xml_root(401, "")), Error::HostStatus { code: 401 });
|
|
}
|
|
|
|
#[test]
|
|
fn applist_caps() {
|
|
use domistream::http::applist::{MAX_APP_TITLE_BYTES, MAX_APPLIST_BYTES, MAX_APPS};
|
|
let app = |i: usize, title: &str| format!("<App><AppTitle>{title}</AppTitle><ID>{i}</ID></App>");
|
|
let t = "t".repeat(MAX_APP_TITLE_BYTES);
|
|
assert_eq!(http::parse_app_list(&xml_root(200, &app(1, &t))).unwrap()[0].title, t);
|
|
assert_cap!(
|
|
http::parse_app_list(&xml_root(200, &app(1, &"t".repeat(MAX_APP_TITLE_BYTES + 1)))),
|
|
MAX_APP_TITLE_BYTES
|
|
);
|
|
// Multi-byte titles: the cap is in bytes.
|
|
assert_cap!(
|
|
http::parse_app_list(&xml_root(200, &app(1, &"é".repeat(MAX_APP_TITLE_BYTES / 2 + 1)))),
|
|
MAX_APP_TITLE_BYTES
|
|
);
|
|
|
|
let list = |n: usize| (0..n).map(|i| app(i, "g")).collect::<String>();
|
|
assert_eq!(http::parse_app_list(&xml_root(200, &list(MAX_APPS))).unwrap().len(), MAX_APPS);
|
|
assert_cap!(http::parse_app_list(&xml_root(200, &list(MAX_APPS + 1))), MAX_APPS);
|
|
|
|
let inner = app(1, "Desktop");
|
|
for len in [MAX_APPLIST_BYTES - 1, MAX_APPLIST_BYTES] {
|
|
let apps = http::parse_app_list(&xml_padded_to(&inner, len)).unwrap_or_else(|e| panic!("{len}: {e:?}"));
|
|
assert_eq!(apps.len(), 1, "unknown elements are ignored");
|
|
}
|
|
assert_too_large!(
|
|
http::parse_app_list(&xml_padded_to(&inner, MAX_APPLIST_BYTES + 1)),
|
|
MAX_APPLIST_BYTES,
|
|
MAX_APPLIST_BYTES + 1
|
|
);
|
|
assert_too_large!(
|
|
http::parse_app_list(&vec![b'<'; 3 * MAX_APPLIST_BYTES]),
|
|
MAX_APPLIST_BYTES,
|
|
3 * MAX_APPLIST_BYTES
|
|
);
|
|
}
|
|
|
|
// ================================================================================================ launch
|
|
|
|
#[test]
|
|
fn launch_response_sample() {
|
|
let r = http::parse_launch_response(&xml_root(
|
|
200,
|
|
"<sessionUrl0>rtsp://192.0.2.10:48010</sessionUrl0><gamesession>1</gamesession>",
|
|
))
|
|
.unwrap();
|
|
assert!(r.game_session);
|
|
assert_eq!(r.session_url.as_deref(), Some("rtsp://192.0.2.10:48010"));
|
|
|
|
let r = http::parse_launch_response(&xml_root(200, "<gamesession>1</gamesession>")).unwrap();
|
|
assert_eq!(r.session_url, None, "missing sessionUrl0 is None (UNKNOWN U4)");
|
|
let r = http::parse_launch_response(&xml_root(200, "<gamesession>0</gamesession>")).unwrap();
|
|
assert!(!r.game_session);
|
|
}
|
|
|
|
#[test]
|
|
fn launch_response_refuses_bad_urls() {
|
|
for url in [
|
|
"http://192.0.2.10:48010",
|
|
"rtsp://192.0.2.10",
|
|
"rtsp://192.0.2.10:",
|
|
"rtsp://192.0.2.10:99999",
|
|
"rtsp://192.0.2.10:-1",
|
|
"rtsp://:48010",
|
|
"rtsp://192.0.2.10:48010\r\nCSeq: 9",
|
|
"rtsp://192.0.2.10:48a",
|
|
"",
|
|
] {
|
|
let body = xml_root(200, &format!("<sessionUrl0>{url}</sessionUrl0><gamesession>1</gamesession>"));
|
|
assert_err!(http::parse_launch_response(&body), Error::Malformed { .. }, "{url:?}");
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn launch_response_caps() {
|
|
use domistream::http::launch::{MAX_LAUNCH_RESPONSE_BYTES as MAX, MAX_SESSION_URL_BYTES as URL};
|
|
let prefix = "rtsp://";
|
|
let suffix = ":48010";
|
|
// A host name of DNS labels of 9 letters, so only the length is unusual.
|
|
let host = |n: usize| {
|
|
let len = n - prefix.len() - suffix.len();
|
|
(0..len).map(|i| if i % 10 == 9 && i + 1 < len { '.' } else { 'h' }).collect::<String>()
|
|
};
|
|
let ok = format!("{prefix}{}{suffix}", host(URL));
|
|
let r = http::parse_launch_response(&xml_root(200, &format!("<sessionUrl0>{ok}</sessionUrl0>"))).unwrap();
|
|
assert_eq!(r.session_url.as_deref(), Some(ok.as_str()));
|
|
let over = format!("{prefix}{}{suffix}", host(URL + 1));
|
|
assert_cap!(http::parse_launch_response(&xml_root(200, &format!("<sessionUrl0>{over}</sessionUrl0>"))), URL);
|
|
|
|
let inner = "<gamesession>1</gamesession>";
|
|
for len in [MAX - 1, MAX] {
|
|
assert!(http::parse_launch_response(&xml_padded_to(inner, len)).unwrap().game_session);
|
|
}
|
|
assert_too_large!(http::parse_launch_response(&xml_padded_to(inner, MAX + 1)), MAX, MAX + 1);
|
|
assert_too_large!(http::parse_launch_response(&vec![0u8; 1 << 20]), MAX, 1 << 20);
|
|
assert_err!(http::parse_launch_response(&xml_root(503, "")), Error::HostStatus { code: 503 });
|
|
assert_err!(http::parse_launch_response(b""), Error::Malformed { .. });
|
|
}
|
|
|
|
#[test]
|
|
fn status_response() {
|
|
assert_eq!(http::parse_status_response(&xml_root(200, "")), Ok(()));
|
|
assert_err!(http::parse_status_response(&xml_root(404, "")), Error::HostStatus { code: 404 });
|
|
assert_err!(http::parse_status_response(b"OK"), Error::Malformed { .. });
|
|
assert_err!(http::parse_status_response(b""), Error::Malformed { .. });
|
|
assert_too_large!(http::parse_status_response(&vec![b' '; MAX_XML_BYTES + 1]), MAX_XML_BYTES, MAX_XML_BYTES + 1);
|
|
}
|
|
|
|
// ================================================================================================ requests
|
|
|
|
const UID: &str = "0123456789ABCDEF";
|
|
|
|
#[test]
|
|
fn simple_requests() {
|
|
let r = http::server_info_request(Scheme::Http, UID).unwrap();
|
|
assert_eq!(r.scheme, Scheme::Http);
|
|
let (path, q) = parse_query(&r.path_and_query);
|
|
assert_eq!(path, "/serverinfo");
|
|
assert_eq!(param(&q, "uniqueid"), UID);
|
|
assert_eq!(http::server_info_request(Scheme::Https, UID).unwrap().scheme, Scheme::Https);
|
|
|
|
for (r, want) in [
|
|
(http::app_list_request(UID).unwrap(), "/applist"),
|
|
(http::cancel_request(UID).unwrap(), "/cancel"),
|
|
(http::unpair_request(UID).unwrap(), "/unpair"),
|
|
] {
|
|
assert_eq!(r.scheme, Scheme::Https, "{want} goes over HTTPS");
|
|
let (path, q) = parse_query(&r.path_and_query);
|
|
assert_eq!(path, want);
|
|
assert_eq!(param(&q, "uniqueid"), UID);
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn requests_refuse_bad_unique_ids() {
|
|
use domistream::http::MAX_UNIQUE_ID_BYTES as MAX;
|
|
for bad in [String::new(), "a".repeat(MAX + 1)] {
|
|
assert_err!(http::server_info_request(Scheme::Http, &bad), Error::Malformed { .. });
|
|
assert_err!(http::app_list_request(&bad), Error::Malformed { .. });
|
|
assert_err!(http::cancel_request(&bad), Error::Malformed { .. });
|
|
assert_err!(http::unpair_request(&bad), Error::Malformed { .. });
|
|
}
|
|
assert!(http::server_info_request(Scheme::Http, &"a".repeat(MAX)).is_ok());
|
|
}
|
|
|
|
#[test]
|
|
fn requests_cannot_be_injected() {
|
|
// A unique id with query syntax is refused or encoded; it never adds a parameter.
|
|
for evil in ["a&uniqueid=b", "a#frag", "a b", "a\r\nX: y", "a=b", "%26"] {
|
|
match http::server_info_request(Scheme::Http, evil) {
|
|
Err(Error::Malformed { .. }) => {}
|
|
Ok(r) => {
|
|
let (path, q) = parse_query(&r.path_and_query);
|
|
assert_eq!(path, "/serverinfo");
|
|
assert_eq!(param(&q, "uniqueid"), evil);
|
|
assert!(!r.path_and_query.contains(['\r', '\n', ' ', '#']), "{:?}", r.path_and_query);
|
|
}
|
|
other => panic!("{evil:?}: {other:?}"),
|
|
}
|
|
}
|
|
}
|
|
|
|
fn launch_params() -> http::LaunchParams {
|
|
http::LaunchParams {
|
|
app_id: 881_448_767,
|
|
width: 1920,
|
|
height: 1080,
|
|
fps: 60,
|
|
keys: domistream::SessionKeys {
|
|
rikey: *b"\x00\x11\x22\x33\x44\x55\x66\x77\x88\x99\xaa\xbb\xcc\xdd\xee\xff",
|
|
rikeyid: 1_234_567,
|
|
},
|
|
hdr: false,
|
|
audio: http::launch::AudioLayout::Stereo,
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn launch_request_parameters() {
|
|
let r = http::launch::launch_request(&launch_params(), UID).unwrap();
|
|
assert_eq!(r.scheme, Scheme::Https);
|
|
let (path, q) = parse_query(&r.path_and_query);
|
|
assert_eq!(path, "/launch");
|
|
assert_eq!(param(&q, "uniqueid"), UID);
|
|
assert_eq!(param(&q, "appid"), "881448767");
|
|
assert_eq!(param(&q, "mode"), "1920x1080x60");
|
|
assert_eq!(param(&q, "rikey").to_lowercase(), "00112233445566778899aabbccddeeff");
|
|
assert_eq!(param(&q, "rikeyid"), "1234567");
|
|
assert_eq!(param(&q, "hdrMode"), "0");
|
|
assert_eq!(param(&q, "surroundAudioInfo"), "196610", "stereo = 0x30002");
|
|
|
|
let mut p = launch_params();
|
|
p.hdr = true;
|
|
let (_, q) = parse_query(&http::launch::launch_request(&p, UID).unwrap().path_and_query);
|
|
assert_eq!(param(&q, "hdrMode"), "1");
|
|
|
|
for broken in [
|
|
http::LaunchParams { width: 0, ..launch_params() },
|
|
http::LaunchParams { height: 0, ..launch_params() },
|
|
http::LaunchParams { fps: 0, ..launch_params() },
|
|
] {
|
|
assert_err!(http::launch::launch_request(&broken, UID), Error::Malformed { .. });
|
|
}
|
|
assert_err!(http::launch::launch_request(&launch_params(), ""), Error::Malformed { .. });
|
|
}
|
|
|
|
#[test]
|
|
fn resume_request_parameters() {
|
|
let keys = launch_params().keys;
|
|
let r = http::launch::resume_request(&keys, UID).unwrap();
|
|
assert_eq!(r.scheme, Scheme::Https);
|
|
let (path, q) = parse_query(&r.path_and_query);
|
|
assert_eq!(path, "/resume");
|
|
assert_eq!(param(&q, "rikey").to_lowercase(), "00112233445566778899aabbccddeeff");
|
|
assert_eq!(param(&q, "rikeyid"), "1234567");
|
|
assert_err!(http::launch::resume_request(&keys, ""), Error::Malformed { .. });
|
|
}
|
|
|
|
#[test]
|
|
fn session_keys_are_fresh() {
|
|
let a = domistream::SessionKeys::generate(&mut common::SeqRng::new(1)).unwrap();
|
|
let b = domistream::SessionKeys::generate(&mut common::SeqRng::new(2)).unwrap();
|
|
let a2 = domistream::SessionKeys::generate(&mut common::SeqRng::new(1)).unwrap();
|
|
assert_eq!(a, a2, "keys come only from the caller's randomness");
|
|
assert_ne!(a.rikey, b.rikey);
|
|
assert_ne!(a.rikey, [0; 16]);
|
|
}
|