//! gs-probe (`probe`): a desktop GameStream client that drives DomiStream's state machines over real sockets //! against ONE host address, and writes a structured log of every step for the live interop sitting //! (`docs/LIVE-INTEROP.md`). A dev tool, never shipped: it prints the pairing PIN for the operator to submit through //! Sunshine's API. //! //! Exit codes: 0 done, 1 error, 2 bad command line, 3 stop and report (something unexpected; see the log). mod args; mod commands; mod dump; mod fec; mod http; mod log; mod redact; mod rng; mod rtsp; mod state; mod stream; mod tls; use std::fs; use std::net::{IpAddr, SocketAddr}; use std::path::{Path, PathBuf}; use std::process::ExitCode; use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; use domistream::http::{HttpRequest, Scheme}; use domistream::pairing::ServerCert; use args::{Command, Options}; use log::{J, Kind, Log}; /// Everything a network command needs. pub struct Ctx { pub opts: Options, /// `--host`: the one host. pub host: IpAddr, /// Where sockets connect: `--relay` when given, else `--host`. pub connect: IpAddr, pub out: PathBuf, pub run_dir: PathBuf, pub log: Log, pub rng: rng::OsRandom, pub id: state::Identity, pub host_cert: Option, pub epoch: Instant, } /// An HTTP body for the log: text (secret XML elements redacted) or hex. pub fn body_j(body: &[u8]) -> J { match std::str::from_utf8(body) { Ok(s) => log::text(redact::xml(s).as_bytes()), Err(_) => log::bytes(body), } } impl Ctx { /// Sends one DomiStream-built request and logs both directions (redacted). HTTPS pins `pinned` (pairing step 5) /// or the stored host certificate. pub fn http( &mut self, step: &str, us: &[&str], req: &HttpRequest, pinned: Option<&ServerCert>, ) -> Result { let (port, tls) = match req.scheme { Scheme::Http => (self.opts.http_port, None), Scheme::Https => { let cert = pinned.or(self.host_cert.as_ref()).ok_or("not paired yet: run `probe pair` first")?; (self.opts.https_port, Some(tls::client_config(&self.id.client, cert)?)) } }; let addr = SocketAddr::new(self.connect, port); let timeout = req.timeout.unwrap_or(Duration::from_secs(10)); self.log.record( step, Kind::Send, us, J::O(vec![ ("scheme", J::dbg(&req.scheme)), ("to", J::s(addr.to_string())), ("path", J::s(redact::query(&req.path_and_query))), ("timeout_ms", J::U(u64::try_from(timeout.as_millis()).unwrap_or(u64::MAX))), ]), ); match http::get(addr, &req.path_and_query, timeout, tls) { Ok(x) => { let r = &x.response; self.log.record( step, Kind::Recv, us, J::O(vec![ ("status", J::U(u64::from(r.status))), ("reason", J::s(r.reason.clone())), ("elapsed_ms", J::F(x.elapsed.as_secs_f64() * 1000.0)), ("framing", J::dbg(&r.framing)), ( "headers", J::A(r.headers.iter().map(|(n, v)| J::A(vec![J::s(n.clone()), J::s(v.clone())])).collect()), ), ( "tls", x.tls.as_ref().map_or(J::Null, |t| { J::O(vec![("version", J::s(t.version.clone())), ("suite", J::s(t.suite.clone()))]) }), ), ("body", body_j(&r.body)), ]), ); Ok(x) } Err(e) => { let m = format!("{} {addr}: {e}", req.path_and_query.split('?').next().unwrap_or("")); self.log.stop(step, us, m.clone(), J::Null); Err(m) } } } } /// U16 from a dump file, as a log value. pub fn solve_audio_file(path: &Path) -> Result { let len = fs::metadata(path).map_err(|e| format!("{}: {e}", path.display()))?.len(); if len > dump::MAX_DUMP_BYTES as u64 { return Err(format!("{}: larger than {} bytes", path.display(), dump::MAX_DUMP_BYTES)); } let data = fs::read(path).map_err(|e| format!("{}: {e}", path.display()))?; let records = dump::decode(&data)?; let datagrams: Vec> = records.into_iter().map(|(_, b)| b).collect(); let r = fec::solve_audio(&datagrams); Ok(J::O(vec![ ("report", J::dbg(&r)), ("matrix", r.matrix().map_or(J::Null, |m| J::s(log::hex(&m)))), ("matrix_is_mds", r.matrix_is_mds().map_or(J::Null, J::Bool)), ])) } fn run(cmd: &Command, opts: Options) -> Result { if let Command::SolveAudioFec { dump } = cmd { let j = solve_audio_file(dump)?; let mut s = String::new(); j.write(&mut s); println!("{s}"); return Ok(0); } let (Some(host), Some(out)) = (opts.host, opts.out.clone()) else { return Err("--host and --out are required".into()); }; let connect = opts.connect_ip().unwrap_or(host); let epoch = Instant::now(); let now = SystemTime::now().duration_since(UNIX_EPOCH).map_err(|_| "the clock is before 1970")?.as_secs(); let run_dir = out.join("runs").join(format!("{}-{}", log::utc_stamp(now), cmd.name())); fs::create_dir_all(&run_dir).map_err(|e| format!("{}: {e}", run_dir.display()))?; let mut log = Log::create(&run_dir.join("log.jsonl"), epoch).map_err(|e| format!("log: {e}"))?; println!( "probe {}: host {host}{}; log {}", cmd.name(), opts.relay.map_or(String::new(), |r| format!(" via relay {r}")), log.path.display() ); log.record( "start", Kind::Note, &[], J::O(vec![ ("probe", J::s(env!("CARGO_PKG_VERSION"))), ("command", J::dbg(cmd)), ("host", J::s(host.to_string())), ("connect", J::s(connect.to_string())), ("options", J::dbg(&opts)), ]), ); let mut rng = rng::OsRandom::new(); let id = state::load_or_create(&out, &opts.name, &mut rng)?; log.note( "identity", &["U2"], format!( "{} client identity: uniqueid {}, certificate sha256 {} (test-only key in {}, never logged)", if id.created { "generated a new" } else { "loaded the" }, id.unique_id, rng::sha256_hex(id.client.cert_der()), state::identity_dir(&out).display() ), ); let host_cert = match state::load_host_cert(&out)? { Some((cert, paired_at)) => { if paired_at != host.to_string() { log.note( "identity", &[], format!("the pinned host certificate was paired at '{paired_at}', not {host}"), ); } Some(cert) } None => None, }; let mut ctx = Ctx { opts, host, connect, out, run_dir, log, rng, id, host_cert, epoch }; let result = match cmd { Command::ServerInfo => commands::serverinfo(&mut ctx), Command::Pair => commands::pair(&mut ctx), Command::Apps => commands::apps(&mut ctx), Command::Launch { app_id } => stream::launch(&mut ctx, *app_id), Command::Quit => commands::quit(&mut ctx), Command::Unpair => commands::unpair(&mut ctx), Command::SolveAudioFec { .. } => Ok(()), }; let stops = ctx.log.stops; ctx.log.record( "end", Kind::Note, &[], J::O(vec![ ("ok", J::Bool(result.is_ok())), ("error", result.as_ref().err().map_or(J::Null, |e| J::s(e.clone()))), ("stops", J::U(u64::from(stops))), ("parse_errors", J::U(u64::from(ctx.log.parse_errors))), ]), ); println!("log: {}", ctx.log.path.display()); match result { _ if stops > 0 => Ok(3), Ok(()) => Ok(0), Err(e) => Err(e), } } fn main() -> ExitCode { let argv: Vec = std::env::args().skip(1).collect(); let inv = match args::parse(&argv) { Ok(i) => i, Err(e) => { eprintln!("probe: {e}\n\n{}", args::USAGE); return ExitCode::from(2); } }; match run(&inv.command, inv.options) { Ok(code) => ExitCode::from(code), Err(e) => { eprintln!("probe: {e}"); ExitCode::from(1) } } }