diff --git a/crates/horizon-client/src/bin/horizon-ctl.rs b/crates/horizon-client/src/bin/horizon-ctl/main.rs similarity index 100% rename from crates/horizon-client/src/bin/horizon-ctl.rs rename to crates/horizon-client/src/bin/horizon-ctl/main.rs diff --git a/crates/horizon-client/src/control.rs b/crates/horizon-client/src/control.rs index 893ffe222..9a670b90b 100644 --- a/crates/horizon-client/src/control.rs +++ b/crates/horizon-client/src/control.rs @@ -3,8 +3,15 @@ //! Each connection sends commands as text lines and receives one JSON line per //! command. Commands are executed on the game thread between frames; replies //! that depend on a later frame (screenshots, benchmarks) arrive when ready. +//! +//! Two transports carry the same lines. On Linux and macOS the endpoint is a +//! Unix domain socket. Where those don't exist (Windows), or when the endpoint +//! path ends in `.json`, the game listens on a random localhost TCP port and +//! writes `{"transport":"tcp","port":N,"token":"..."}` to the path, readable +//! only by its user; a client's first line must then be `auth TOKEN`. use std::{ - io::{BufRead, BufReader, Write}, + io::{self, BufRead, BufReader, Read, Write}, + net::{Ipv4Addr, TcpListener, TcpStream}, path::{Path, PathBuf}, sync::mpsc, thread, @@ -12,54 +19,128 @@ use std::{ #[cfg(unix)] pub use std::os::unix::net::{UnixListener, UnixStream}; -#[cfg(not(unix))] -pub use unsupported::{UnixListener, UnixStream}; -/// Windows' standard library has no Unix domain sockets: there the control -/// socket reports itself unavailable and the game runs without it. -#[cfg(not(unix))] -mod unsupported { - use std::{io, path::Path}; +/// A connection to the control endpoint, over either transport. +pub enum Stream { + #[cfg(unix)] + Unix(UnixStream), + Tcp(TcpStream), +} - fn unavailable() -> io::Error { - io::Error::new( - io::ErrorKind::Unsupported, - "the control socket needs Unix domain sockets (Linux or macOS)", - ) +impl Stream { + pub fn try_clone(&self) -> io::Result { + Ok(match self { + #[cfg(unix)] + Self::Unix(s) => Self::Unix(s.try_clone()?), + Self::Tcp(s) => Self::Tcp(s.try_clone()?), + }) } - pub struct UnixStream; - impl UnixStream { - pub fn connect>(_: P) -> io::Result { - Err(unavailable()) - } - pub fn try_clone(&self) -> io::Result { - Err(unavailable()) + /// A read timeout (None waits forever). + pub fn set_read_timeout(&self, timeout: Option) -> io::Result<()> { + match self { + #[cfg(unix)] + Self::Unix(s) => s.set_read_timeout(timeout), + Self::Tcp(s) => s.set_read_timeout(timeout), } } - impl io::Read for UnixStream { - fn read(&mut self, _: &mut [u8]) -> io::Result { - Err(unavailable()) +} +impl Read for Stream { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + match self { + #[cfg(unix)] + Self::Unix(s) => s.read(buf), + Self::Tcp(s) => s.read(buf), } } - impl io::Write for UnixStream { - fn write(&mut self, _: &[u8]) -> io::Result { - Err(unavailable()) - } - fn flush(&mut self) -> io::Result<()> { - Ok(()) +} +impl Write for Stream { + fn write(&mut self, buf: &[u8]) -> io::Result { + match self { + #[cfg(unix)] + Self::Unix(s) => s.write(buf), + Self::Tcp(s) => s.write(buf), } } - pub struct UnixListener; - impl UnixListener { - pub fn bind>(_: P) -> io::Result { - Err(unavailable()) - } - pub fn incoming(&self) -> std::iter::Empty> { - std::iter::empty() + fn flush(&mut self) -> io::Result<()> { + match self { + #[cfg(unix)] + Self::Unix(s) => s.flush(), + Self::Tcp(s) => s.flush(), } } } +/// Whether the endpoint at `path` is a TCP port described by a JSON file. +pub fn uses_tcp(path: &Path) -> bool { + !cfg!(unix) || path.extension().is_some_and(|e| e == "json") +} + +/// The TCP endpoint file: (port, token). +fn read_endpoint(path: &Path) -> io::Result<(u16, String)> { + let text = std::fs::read_to_string(path)?; + let bad = || io::Error::new(io::ErrorKind::InvalidData, "not a control endpoint file"); + let v: serde_json::Value = serde_json::from_str(&text).map_err(|_| bad())?; + let port = v["port"] + .as_u64() + .and_then(|p| u16::try_from(p).ok()) + .ok_or_else(bad)?; + let token = v["token"].as_str().ok_or_else(bad)?.to_owned(); + Ok((port, token)) +} + +/// Connect to a running game's control endpoint (and authenticate over TCP). +pub fn connect(path: &Path) -> io::Result { + #[cfg(unix)] + if !uses_tcp(path) { + return UnixStream::connect(path).map(Stream::Unix); + } + let (port, token) = read_endpoint(path)?; + let mut stream = TcpStream::connect((Ipv4Addr::LOCALHOST, port))?; + stream.set_nodelay(true)?; + writeln!(stream, "auth {token}")?; + let mut reply = String::new(); + BufReader::new(stream.try_clone()?).read_line(&mut reply)?; + if !reply.contains("\"ok\"") { + return Err(io::Error::new( + io::ErrorKind::PermissionDenied, + format!("the game refused the token: {}", reply.trim()), + )); + } + Ok(Stream::Tcp(stream)) +} + +/// 128 random bits as hex, from the standard library's OS-seeded hasher keys. +fn random_token() -> String { + use std::hash::{BuildHasher, Hasher}; + (0..2) + .map(|i| { + let mut h = std::collections::hash_map::RandomState::new().build_hasher(); + h.write_u64(i); + h.write_u128( + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_nanos()), + ); + h.write_u32(std::process::id()); + format!("{:016x}", h.finish()) + }) + .collect() +} + +/// Write the endpoint file so that only this user can read it. +fn write_private(path: &Path, text: &str) -> io::Result<()> { + let mut options = std::fs::OpenOptions::new(); + options.write(true).create(true).truncate(true); + #[cfg(unix)] + std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600); + options.open(path)?.write_all(text.as_bytes()) +} + +/// Constant-time comparison of the presented token. +fn same_token(a: &str, b: &str) -> bool { + a.len() == b.len() && a.bytes().zip(b.bytes()).fold(0u8, |d, (x, y)| d | (x ^ y)) == 0 +} + /// One command line from a client, with the channel for its JSON reply. pub struct Request { pub line: String, @@ -71,33 +152,55 @@ pub struct Server { requests: mpsc::Receiver, } -/// `$HORIZON_CONTROL`, else `horizon-control.sock` in the user's runtime directory. +/// `$HORIZON_CONTROL`, else `horizon-control.sock` in the user's runtime +/// directory (`horizon-control.json` in the temporary directory on Windows). pub fn default_path() -> PathBuf { if let Some(path) = std::env::var_os("HORIZON_CONTROL") { return path.into(); } + if !cfg!(unix) { + return std::env::temp_dir().join("horizon-control.json"); + } let dir = std::env::var_os("XDG_RUNTIME_DIR").map_or_else(std::env::temp_dir, PathBuf::from); dir.join("horizon-control.sock") } impl Server { - pub fn start(path: &Path) -> std::io::Result { - // A socket left by a crashed game refuses connections; replace it. - if path.exists() && UnixStream::connect(path).is_err() { + pub fn start(path: &Path) -> io::Result { + // An endpoint left by a crashed game refuses connections; replace it. + if path.exists() && connect(path).is_err() { std::fs::remove_file(path)?; } - let listener = UnixListener::bind(path)?; let (sender, requests) = mpsc::channel(); - thread::Builder::new() - .name("horizon-control".into()) - .spawn(move || { - for stream in listener.incoming().flatten() { - let sender = sender.clone(); - let _ = thread::Builder::new() - .name("horizon-control-client".into()) - .spawn(move || serve(stream, &sender)); - } - })?; + if uses_tcp(path) { + let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0))?; + let token = random_token(); + let port = listener.local_addr()?.port(); + write_private( + path, + &serde_json::json!({ "transport": "tcp", "port": port, "token": token }) + .to_string(), + )?; + spawn_listener( + move || listener.accept().map(|(s, _)| s), + sender, + move |stream: TcpStream| { + let _ = stream.set_nodelay(true); + let mut stream = Stream::Tcp(stream); + authenticate(&mut stream, &token).then_some(stream) + }, + )?; + } else { + #[cfg(unix)] + { + let listener = UnixListener::bind(path)?; + spawn_listener( + move || listener.accept().map(|(s, _)| s), + sender, + |s| Some(Stream::Unix(s)), + )?; + } + } Ok(Self { path: path.to_owned(), requests, @@ -111,13 +214,68 @@ impl Server { } } +/// Accept connections on a thread, one more thread per client. +fn spawn_listener( + mut accept_next: impl FnMut() -> io::Result + Send + 'static, + sender: mpsc::Sender, + accept: impl Fn(S) -> Option + Send + Sync + 'static, +) -> io::Result<()> { + let accept = std::sync::Arc::new(accept); + thread::Builder::new() + .name("horizon-control".into()) + .spawn(move || { + loop { + let Ok(stream) = accept_next() else { + thread::sleep(std::time::Duration::from_millis(10)); + continue; + }; + let sender = sender.clone(); + let accept = accept.clone(); + let _ = thread::Builder::new() + .name("horizon-control-client".into()) + .spawn(move || { + if let Some(stream) = accept(stream) { + serve(stream, &sender); + } + }); + } + })?; + Ok(()) +} + +/// The first line of a TCP client must be `auth TOKEN`. +fn authenticate(stream: &mut Stream, token: &str) -> bool { + let mut line = Vec::new(); + let mut byte = [0u8; 1]; + // Read the line byte by byte so nothing after it is buffered away. + while line.len() < 256 { + match stream.read(&mut byte) { + Ok(1) if byte[0] == b'\n' => break, + Ok(1) => line.push(byte[0]), + _ => return false, + } + } + let line = String::from_utf8_lossy(&line); + let ok = line + .trim() + .strip_prefix("auth ") + .is_some_and(|t| same_token(t.trim(), token)); + let reply = if ok { + r#"{"ok":true}"# + } else { + r#"{"error":"bad or missing token: the first line must be auth TOKEN"}"# + }; + let _ = writeln!(stream, "{reply}"); + ok +} + impl Drop for Server { fn drop(&mut self) { let _ = std::fs::remove_file(&self.path); } } -fn serve(stream: UnixStream, sender: &mpsc::Sender) { +fn serve(stream: Stream, sender: &mpsc::Sender) { let Ok(mut writer) = stream.try_clone() else { return; }; @@ -140,6 +298,55 @@ fn serve(stream: UnixStream, sender: &mpsc::Sender) { } } +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn tcp_endpoint_round_trip() { + let path = + std::env::temp_dir().join(format!("horizon-ctl-test-{}.json", std::process::id())); + let server = Server::start(&path).unwrap(); + let text = std::fs::read_to_string(&path).unwrap(); + assert!(text.contains("\"tcp\"")); + let mut client = connect(&path).unwrap(); + writeln!(client, "status").unwrap(); + let request = loop { + if let Some(r) = server.try_recv() { + break r; + } + thread::sleep(std::time::Duration::from_millis(5)); + }; + assert_eq!(request.line, "status"); + request.reply.send(r#"{"ok":true}"#.into()).unwrap(); + let mut reply = String::new(); + BufReader::new(client).read_line(&mut reply).unwrap(); + assert_eq!(reply.trim(), r#"{"ok":true}"#); + drop(server); + assert!(!path.exists()); + } + + #[test] + fn tcp_refuses_a_wrong_token() { + let path = + std::env::temp_dir().join(format!("horizon-ctl-bad-{}.json", std::process::id())); + let _server = Server::start(&path).unwrap(); + let (port, _) = read_endpoint(&path).unwrap(); + let mut stream = TcpStream::connect((Ipv4Addr::LOCALHOST, port)).unwrap(); + writeln!(stream, "auth nope").unwrap(); + let mut reply = String::new(); + BufReader::new(stream).read_line(&mut reply).unwrap(); + assert!(reply.contains("error")); + } + + #[test] + fn tokens_differ() { + assert_ne!(random_token(), random_token()); + assert_eq!(random_token().len(), 32); + assert!(same_token("abc", "abc") && !same_token("abc", "abd") && !same_token("a", "ab")); + } +} + /// Frame durations since the last reset, summarized like the Java recorder, /// with the CPU part of each frame and GPU times from timestamp queries. #[derive(Default)]