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