//! 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 { 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(¶ms, UID).unwrap(); let want = LaunchRequest { app_id: 881_448_767, mode: DisplayMode { width: 3840, height: 2160, fps: 120 }, keys: keys(), hdr: Some(hdr), surround_audio_info: Some(audio.surround_audio_info()), }; assert_eq!(route(&r.path_and_query), Route::Launch(want)); } let r = http::launch::resume_request(&keys(), UID).unwrap(); assert_eq!( route(&r.path_and_query), Route::Resume(ResumeRequest { keys: keys(), app_id: None, mode: None, hdr: None, surround_audio_info: None }) ); } #[test] fn the_client_pairing_requests_parse_on_the_host() { let v = common::pairing_vectors(); let id = domistream::pairing::ClientIdentity::from_der(&v.bytes("client_cert_der"), &v.bytes("client_key_pkcs8_der")) .unwrap(); let mut rng = common::SeqRng::new(3); let pin = domistream::pairing::Pin::from_digits("4071").unwrap(); let (_, r) = domistream::pairing::PairingSession::start(&id, UID, "Living Room TV", pin, &mut rng).unwrap(); match route(&r.path_and_query) { Route::Pair(p) => { assert_eq!(p.unique_id, UID); assert_eq!(p.device_name.as_deref(), Some("Living Room TV")); match p.phase { PairPhase::GetServerCert { client_cert_pem, .. } => { assert_eq!(client_cert_pem, id.cert_pem().unwrap().into_bytes()); } other => panic!("{other:?}"), } } other => panic!("{other:?}"), } } #[test] fn pair_phases_from_the_query() { let salt = "00112233445566778899aabbccddeeff"; let cert = to_hex(CLIENT_CERT_PEM.as_bytes()); let pair = |q: &str| match route(&format!("/pair?uniqueid={UID}&devicename=tv&updateState=1&{q}")) { Route::Pair(p) => p.phase, other => panic!("{other:?}"), }; assert_eq!( pair(&format!("phrase=getservercert&salt={salt}&clientcert={cert}")), PairPhase::GetServerCert { salt: *b"\x00\x11\x22\x33\x44\x55\x66\x77\x88\x99\xaa\xbb\xcc\xdd\xee\xff", client_cert_pem: CLIENT_CERT_PEM.as_bytes().to_vec() } ); assert_eq!(pair("clientchallenge=0A0b"), PairPhase::ClientChallenge(vec![0x0A, 0x0B])); assert_eq!(pair("serverchallengeresp=ff"), PairPhase::ServerChallengeResp(vec![0xFF])); assert_eq!(pair("clientpairingsecret=0001"), PairPhase::ClientPairingSecret(vec![0, 1])); assert_eq!(pair("phrase=pairchallenge"), PairPhase::PairChallenge); // updateState is known to the client side but not used by the host: it is kept as an unknown parameter. let req = parse_target(&format!("/pair?uniqueid={UID}&updateState=1&phrase=pairchallenge")).unwrap(); assert_eq!(req.other_params, vec![("updateState".to_string(), "1".to_string())]); } #[test] fn pair_requests_refused() { let salt = "00112233445566778899aabbccddeeff"; let cert = to_hex(CLIENT_CERT_PEM.as_bytes()); for (q, why) in [ (format!("phrase=getservercert&salt={salt}&clientcert={cert}"), "no uniqueid"), (format!("uniqueid={UID}"), "no phase"), (format!("uniqueid={UID}&phrase=getservercert&clientcert={cert}"), "no salt"), (format!("uniqueid={UID}&phrase=getservercert&salt={salt}"), "no clientcert"), (format!("uniqueid={UID}&phrase=getservercert&salt=0011&clientcert={cert}"), "short salt"), (format!("uniqueid={UID}&phrase=getservercert&salt={salt}00&clientcert={cert}"), "long salt"), (format!("uniqueid={UID}&phrase=getservercert&salt={salt}&clientcert=abc"), "odd hex"), (format!("uniqueid={UID}&phrase=getservercert&salt={salt}&clientcert=zz"), "not hex"), (format!("uniqueid={UID}&phrase=other"), "unknown phrase"), (format!("uniqueid={UID}&phrase=pairchallenge&clientchallenge=00"), "two phases"), (format!("uniqueid={UID}&clientchallenge=00&serverchallengeresp=00"), "two phases"), (format!("uniqueid={UID}&clientchallenge="), "empty hex"), (format!("uniqueid={UID}&clientchallenge=0x00"), "0x prefix"), ("uniqueid=a%26b&phrase=pairchallenge".to_string(), "bad uniqueid"), (format!("uniqueid={}&phrase=pairchallenge", "a".repeat(65)), "long uniqueid"), (format!("uniqueid={UID}&uniqueid={UID}&phrase=pairchallenge"), "repeated uniqueid"), (format!("uniqueid={UID}&phrase=pairchallenge&phrase=getservercert"), "repeated phrase"), ] { assert!( matches!(parse_target(&format!("/pair?{q}")), Err(Error::Malformed { .. })), "{why}: {:?}", parse_target(&format!("/pair?{q}")) ); } let long_name = "d".repeat(MAX_DEVICE_NAME_BYTES); assert!(parse_target(&format!("/pair?uniqueid={UID}&devicename={long_name}&phrase=pairchallenge")).is_ok()); assert!(matches!( parse_target(&format!("/pair?uniqueid={UID}&devicename={long_name}d&phrase=pairchallenge")), Err(Error::TooLarge { max: MAX_DEVICE_NAME_BYTES, .. }) )); // Hex values other than the certificate have their own cap. let big = "00".repeat(domistream::host::http::MAX_HEX_VALUE_CHARS / 2); assert!(parse_target(&format!("/pair?uniqueid={UID}&clientpairingsecret={big}")).is_ok()); assert!(matches!( parse_target(&format!("/pair?uniqueid={UID}&clientpairingsecret={big}00")), Err(Error::TooLarge { .. }) )); // The certificate's cap is the PEM cap, in hex. let at_cap = "41".repeat(MAX_CERT_PEM_BYTES); assert!( parse_target(&format!("/pair?uniqueid={UID}&phrase=getservercert&salt={salt}&clientcert={at_cap}")).is_ok() ); assert!(matches!( parse_target(&format!("/pair?uniqueid={UID}&phrase=getservercert&salt={salt}&clientcert={at_cap}41")), Err(Error::TooLarge { .. }) )); } // ================================================================================================ routes #[test] fn routes_and_unknown_parameters() { let req = parse_request_head(&head(&format!("/serverinfo?uniqueid={UID}&uuid=5d1a-77"))).unwrap(); assert_eq!(req.route, Route::ServerInfo); assert_eq!(req.other_params, vec![("uuid".to_string(), "5d1a-77".to_string())]); assert_eq!(parse_target("/serverinfo").unwrap().unique_id, None, "uniqueid is optional outside /pair"); let req = parse_target(&format!("/appasset?uniqueid={UID}&appid=5&AssetType=2&AssetIdx=0")).unwrap(); assert_eq!(req.route, Route::AppAsset { app_id: 5 }); assert_eq!(req.other_params.len(), 2); assert!(matches!(parse_target("/appasset"), Err(Error::Malformed { .. })), "appid is required"); assert_eq!(route("/foo/../bar?x=1"), Route::Unknown { path: "/foo/../bar".into() }); assert_eq!(route("/"), Route::Unknown { path: "/".into() }); assert_eq!(route("/ServerInfo"), Route::Unknown { path: "/ServerInfo".into() }, "paths are case-sensitive"); assert_eq!(route("/serverinfo/"), Route::Unknown { path: "/serverinfo/".into() }); assert_eq!(route("/%73erverinfo"), Route::Unknown { path: "/%73erverinfo".into() }, "paths are never decoded"); assert_eq!(route("/applist?"), Route::AppList, "an empty query is no query"); } fn launch_q(extra: &str) -> String { format!( "/launch?uniqueid={UID}&appid=7&mode=1920x1080x60&rikey=00112233445566778899AABBCCDDEEFF&rikeyid=1234567{extra}" ) } #[test] fn launch_values() { let Route::Launch(l) = route(&launch_q("")) else { panic!() }; assert_eq!(l.app_id, 7); assert_eq!(l.mode, DisplayMode { width: 1920, height: 1080, fps: 60 }); assert_eq!(l.keys, keys()); assert_eq!((l.hdr, l.surround_audio_info), (None, None)); let Route::Launch(l) = route(&launch_q("&hdrMode=1&surroundAudioInfo=196610&localAudioPlayMode=0")) else { panic!() }; assert_eq!((l.hdr, l.surround_audio_info), (Some(true), Some(196_610))); // rikeyid: unsigned decimal; a negative 32-bit value is read as its two's complement (UNKNOWN: some clients // may print the id signed). let id = |v: &str| match parse_target(&launch_q("").replace("rikeyid=1234567", &format!("rikeyid={v}"))) { Ok(HostRequest { route: Route::Launch(l), .. }) => Ok(l.keys.rikeyid), Ok(other) => panic!("{other:?}"), Err(e) => Err(e), }; assert_eq!(id("0"), Ok(0)); assert_eq!(id("4294967295"), Ok(u32::MAX)); assert_eq!(id("-1"), Ok(u32::MAX)); assert_eq!(id("-2147483648"), Ok(0x8000_0000)); for bad in ["4294967296", "-2147483649", "-0", "-", "+1", "1.0", "0x10", "", " 1"] { assert!(matches!(id(bad), Err(Error::Malformed { .. })), "rikeyid {bad:?}: {:?}", id(bad)); } let max = format!("{MAX_MODE_DIMENSION}x{MAX_MODE_DIMENSION}x{MAX_MODE_FPS}"); let Route::Launch(l) = route(&launch_q("").replace("1920x1080x60", &max)) else { panic!() }; assert_eq!(l.mode.fps, MAX_MODE_FPS); } #[test] fn launch_refused() { let base = launch_q(""); for (bad, why) in [ (base.replace("&appid=7", ""), "no appid"), (base.replace("&mode=1920x1080x60", ""), "no mode"), (base.replace("&rikey=00112233445566778899AABBCCDDEEFF", ""), "no rikey"), (base.replace("&rikeyid=1234567", ""), "no rikeyid"), (base.replace("appid=7", "appid=-7"), "negative appid"), (base.replace("appid=7", "appid=4294967296"), "appid over u32"), (base.replace("1920x1080x60", "1920x1080"), "mode without fps"), (base.replace("1920x1080x60", "1920x1080x60x1"), "mode with four parts"), (base.replace("1920x1080x60", "0x1080x60"), "zero width"), (base.replace("1920x1080x60", "1920x0x60"), "zero height"), (base.replace("1920x1080x60", "1920x1080x0"), "zero fps"), (base.replace("1920x1080x60", &format!("{}x1080x60", MAX_MODE_DIMENSION + 1)), "too wide"), (base.replace("1920x1080x60", &format!("1920x1080x{}", MAX_MODE_FPS + 1)), "too fast"), (base.replace("1920x1080x60", "1920X1080X60"), "upper-case X"), (base.replace("1920x1080x60", "1920x1080x59.94"), "fractional fps"), (base.replace("1920x1080x60", "+1920x1080x60"), "sign"), (base.replace("00112233445566778899AABBCCDDEEFF", "00112233445566778899AABBCCDDEEF"), "short rikey"), (base.replace("00112233445566778899AABBCCDDEEFF", "00112233445566778899AABBCCDDEEFF00"), "long rikey"), (base.replace("00112233445566778899AABBCCDDEEFF", "00112233445566778899AABBCCDDEEFG"), "rikey not hex"), (launch_q("&hdrMode=2"), "hdrMode 2"), (launch_q("&hdrMode=true"), "hdrMode true"), (launch_q("&surroundAudioInfo=x"), "surroundAudioInfo not decimal"), (launch_q("&appid=8"), "repeated appid"), (launch_q("&rikey=00112233445566778899AABBCCDDEEFF"), "repeated rikey"), ] { let r = parse_target(&bad); assert!(matches!(r, Err(Error::Malformed { .. })), "{why}: {r:?}"); } } #[test] fn resume_values() { let q = format!("/resume?uniqueid={UID}&rikey=00112233445566778899aabbccddeeff&rikeyid=1234567"); let Route::Resume(r) = route(&q) else { panic!() }; assert_eq!(r.keys, keys()); let Route::Resume(r) = route(&format!("{q}&appid=3&mode=1280x720x30&hdrMode=0&surroundAudioInfo=1")) else { panic!() }; assert_eq!(r.app_id, Some(3)); assert_eq!(r.mode, Some(DisplayMode { width: 1280, height: 720, fps: 30 })); assert_eq!((r.hdr, r.surround_audio_info), (Some(false), Some(1))); assert!(matches!(parse_target(&format!("/resume?uniqueid={UID}&rikeyid=1")), Err(Error::Malformed { .. }))); assert!(matches!(parse_target(&format!("{q}&mode=1x1")), Err(Error::Malformed { .. }))); } // ================================================================================================ the head #[test] fn heads_that_are_fine() { for h in [ "GET /serverinfo HTTP/1.1\r\n\r\n".to_string(), "GET /serverinfo HTTP/1.0\r\n\r\n".to_string(), "GET /serverinfo HTTP/1.1\r\nHost: x\r\nContent-Length: 0\r\n\r\n".to_string(), "GET /serverinfo HTTP/1.1\r\nX-Odd:\tvalue with spaces \t\r\n\r\n".to_string(), "GET /serverinfo HTTP/1.1\r\nEmpty:\r\n\r\n".to_string(), "GET /serverinfo HTTP/1.1\r\ncontent-length: 0\r\n\r\n".to_string(), ] { assert_eq!(parse_request_head(h.as_bytes()).map(|r| r.route), Ok(Route::ServerInfo), "{h:?}"); } } #[test] fn heads_that_are_refused() { for (h, why) in [ (&b""[..], "empty"), (b"GET /serverinfo HTTP/1.1\r\n", "no empty line"), (b"GET /serverinfo HTTP/1.1\r\nHost: x\r\n", "no empty line after headers"), (b"GET /serverinfo HTTP/1.1\n\n", "bare LF"), (b"GET /serverinfo HTTP/1.1\r\nHost: x\n\r\n", "bare LF in a header"), (b"GET /serverinfo HTTP/1.1\r\n\r\nbody", "bytes after the head"), (b"GET /serverinfo HTTP/1.1\r\n\r\n\r\n", "two empty lines"), (b"GET /serverinfo HTTP/1.1\r\n\r\n", "two spaces"), (b"GET /serverinfo HTTP/1.1\r\n\r\n", "two spaces before the version"), (b"GET /serverinfo\r\n\r\n", "no version"), (b"GET /serverinfo HTTP/2\r\n\r\n", "HTTP/2"), (b"GET /serverinfo http/1.1\r\n\r\n", "lower-case version"), (b"GET /serverinfo HTTP/1.1 x\r\n\r\n", "four parts"), (b" GET /serverinfo HTTP/1.1\r\n\r\n", "leading space"), (b"\r\nGET /serverinfo HTTP/1.1\r\n\r\n", "leading empty line"), (b"GET http://x/serverinfo HTTP/1.1\r\n\r\n", "absolute form"), (b"GET * HTTP/1.1\r\n\r\n", "asterisk form"), (b"GET serverinfo HTTP/1.1\r\n\r\n", "no leading slash"), (b"GET /serverinfo#x HTTP/1.1\r\n\r\n", "fragment"), (b"GET /server\x00info HTTP/1.1\r\n\r\n", "NUL"), (b"GET /server\xc3\xa9 HTTP/1.1\r\n\r\n", "non-ASCII target"), (b"GET /serverinfo HTTP/1.1\r\nHost: \xff\r\n\r\n", "non-ASCII header"), (b"GET /serverinfo HTTP/1.1\r\nHost: a\x01b\r\n\r\n", "control in a header"), (b"GET /serverinfo HTTP/1.1\r\nHost: x\r\n folded\r\n\r\n", "folded header"), (b"GET /serverinfo HTTP/1.1\r\nHost x\r\n\r\n", "no colon"), (b"GET /serverinfo HTTP/1.1\r\n: x\r\n\r\n", "empty name"), (b"GET /serverinfo HTTP/1.1\r\nHost : x\r\n\r\n", "space before the colon"), (b"GET /serverinfo HTTP/1.1\r\nHo(st: x\r\n\r\n", "not a token"), (b"GET /serverinfo HTTP/1.1\r\nContent-Length: 5\r\n\r\n", "a body"), (b"GET /serverinfo HTTP/1.1\r\nContent-Length: 0\r\nContent-Length: 0\r\n\r\n", "two lengths"), (b"GET /serverinfo HTTP/1.1\r\nContent-Length: +0\r\n\r\n", "signed length"), (b"GET /serverinfo HTTP/1.1\r\nTransfer-Encoding: chunked\r\n\r\n", "chunked"), (b"GET /serverinfo HTTP/1.1\r\nHost: x\rY: z\r\n\r\n", "bare CR"), ] { let r = parse_request_head(h); assert!(matches!(r, Err(Error::Malformed { .. })), "{why}: {r:?}"); } for m in ["POST", "HEAD", "PUT", "get", "OPTIONS", "CONNECT"] { let h = format!("{m} /serverinfo HTTP/1.1\r\n\r\n"); assert!(matches!(parse_request_head(h.as_bytes()), Err(Error::Unsupported { .. })), "{m}"); } } #[test] fn head_caps() { // A head of exactly the cap, padded with one long header line. let at = |total: usize| { let start = "GET /serverinfo HTTP/1.1\r\nX: "; let end = "\r\n\r\n"; format!("{start}{}{end}", "a".repeat(total - start.len() - end.len())).into_bytes() }; assert_eq!(parse_request_head(&at(MAX_HEAD_BYTES)).map(|r| r.route), Ok(Route::ServerInfo)); assert_too_large!(parse_request_head(&at(MAX_HEAD_BYTES + 1)), MAX_HEAD_BYTES, MAX_HEAD_BYTES + 1); assert_too_large!(parse_request_head(&vec![b'G'; 1 << 22]), MAX_HEAD_BYTES, 1 << 22); let headers = |n: usize| { let mut s = String::from("GET /serverinfo HTTP/1.1\r\n"); for i in 0..n { s.push_str(&format!("X-{i}: v\r\n")); } s.push_str("\r\n"); s.into_bytes() }; assert!(parse_request_head(&headers(MAX_HEADERS)).is_ok()); assert!(matches!(parse_request_head(&headers(MAX_HEADERS + 1)), Err(Error::TooLarge { max: MAX_HEADERS, .. }))); let path = |n: usize| format!("/{}", "p".repeat(n - 1)); assert_eq!(route(&path(MAX_PATH_BYTES)), Route::Unknown { path: path(MAX_PATH_BYTES) }); assert!(matches!(parse_target(&path(MAX_PATH_BYTES + 1)), Err(Error::TooLarge { max: MAX_PATH_BYTES, .. }))); } #[test] fn find_head_end_cuts_the_stream() { let h = head("/serverinfo"); for cut in 0..h.len() { assert_eq!(find_head_end(&h[..cut]), Ok(None), "{cut} bytes"); } assert_eq!(find_head_end(&h), Ok(Some(h.len()))); let mut two = h.clone(); two.extend_from_slice(&h); assert_eq!(find_head_end(&two), Ok(Some(h.len())), "pipelined: the first head"); assert_eq!(find_head_end(b"\r\n\r\n"), Ok(Some(4))); let mut at_cap = vec![b'a'; MAX_HEAD_BYTES - 4]; at_cap.extend_from_slice(b"\r\n\r\n"); assert_eq!(find_head_end(&at_cap), Ok(Some(MAX_HEAD_BYTES))); assert_eq!(find_head_end(&vec![b'a'; MAX_HEAD_BYTES - 1]), Ok(None), "could still end within the cap"); let mut almost = vec![b'a'; MAX_HEAD_BYTES - 4]; almost.extend_from_slice(b"\r\n\r"); assert_eq!(find_head_end(&almost), Ok(None), "one more LF ends it exactly at the cap"); for len in [MAX_HEAD_BYTES, MAX_HEAD_BYTES + 1, 1 << 22] { assert!(matches!(find_head_end(&vec![b'a'; len]), Err(Error::TooLarge { max: MAX_HEAD_BYTES, .. })), "{len}"); } let mut late = vec![b'a'; MAX_HEAD_BYTES - 3]; late.extend_from_slice(b"\r\n\r\n"); assert!(matches!(find_head_end(&late), Err(Error::TooLarge { .. })), "ends one byte past the cap"); } // ================================================================================================ the query #[test] fn query_decoding() { let q = |s: &str| parse_query(s); assert_eq!(q(""), Ok(vec![])); assert_eq!(q("a=1&b=2"), Ok(vec![("a".into(), "1".into()), ("b".into(), "2".into())])); assert_eq!(q("a=%41%62%2b%2B"), Ok(vec![("a".into(), "Ab++".into())])); assert_eq!(q("a=x+y"), Ok(vec![("a".into(), "x y".into())])); assert_eq!(q("a=%C3%A9"), Ok(vec![("a".into(), "é".into())])); assert_eq!(q("a=%26b%3Dc"), Ok(vec![("a".into(), "&b=c".into())]), "encoded & and = stay in the value"); assert_eq!(q("a"), Ok(vec![("a".into(), String::new())])); assert_eq!(q("a="), Ok(vec![("a".into(), String::new())])); assert_eq!(q("a=1&&b=2&"), Ok(vec![("a".into(), "1".into()), ("b".into(), "2".into())])); assert_eq!(q("a=b=c"), Ok(vec![("a".into(), "b=c".into())])); assert_eq!(q("x.y-z_1=0"), Ok(vec![("x.y-z_1".into(), "0".into())])); for (bad, why) in [ ("=1", "empty name"), ("a=%", "cut escape"), ("a=%4", "cut escape"), ("a=%zz", "bad escape"), ("a=%00", "NUL"), ("a=%0A", "LF"), ("a=%7F", "DEL"), ("a=%FF", "not UTF-8"), ("a=%C3", "cut UTF-8"), ("a%41=1", "escape in a name"), ("a b=1", "space in a name"), ("a=1&a=2", "repeated name"), ("a=1&a", "repeated name"), ("a=\u{e9}", "raw non-ASCII"), ] { assert!(matches!(q(bad), Err(Error::Malformed { .. })), "{why}: {:?}", q(bad)); } } #[test] fn query_caps() { let params = |n: usize| (0..n).map(|i| format!("p{i}=1")).collect::>().join("&"); assert_eq!(parse_query(¶ms(MAX_PARAMS)).unwrap().len(), MAX_PARAMS); assert!(matches!(parse_query(¶ms(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 { "[a-zA-Z_][a-zA-Z0-9_.-]{0,12}" } fn value_strategy() -> impl Strategy { // Any characters but controls (refused on purpose). proptest::collection::vec(any::().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::(), 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::(), hdr in proptest::option::of(any::()), audio in proptest::option::of(any::())) { 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::(), 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::(), 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 & \"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 & \"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 \"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 = (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 = (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 = 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 & ").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 & ")); 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 { .. }))); }