diff --git a/crates/horizon-client/src/front.rs b/crates/horizon-client/src/front.rs index cc6237ead..75e6547e1 100644 --- a/crates/horizon-client/src/front.rs +++ b/crates/horizon-client/src/front.rs @@ -33,6 +33,7 @@ const MAKE: u64 = id("create.make", 0); const SERVER: u64 = id("mp.row", 0); const JOIN: u64 = id("mp.join", 0); const DIRECT: u64 = id("mp.direct", 0); +const FRIEND: u64 = id("mp.friend", 0); const ADD: u64 = id("mp.add", 0); const EDIT: u64 = id("mp.edit", 0); const DELETE: u64 = id("mp.delete", 0); @@ -435,6 +436,7 @@ impl Title { let id = match hit { JOIN => Some(40), DIRECT => Some(41), + FRIEND => Some(47), ADD => Some(42), EDIT => Some(43), DELETE => Some(44), @@ -443,11 +445,13 @@ impl Title { Screen::List { .. } => 46, Screen::Edit { .. } => 51, Screen::Direct { .. } => 53, + Screen::Friend { .. } => 57, Screen::Disconnected { .. } => 54, }), CANCEL_RETRY => Some(55), DONE => Some(match screen { Screen::Direct { .. } => 52, + Screen::Friend { .. } => 56, _ => 50, }), FIELD_A | FIELD_B => { @@ -803,6 +807,7 @@ fn multiplayer_page(ui: &mut Ui, x: f32, w: f32, screen: &Screen, caret: bool) { let saved = selected.is_some_and(|i| i < servers.len()); let mut items = vec![ (JOIN, "Join", Kind::Primary, has), + (FRIEND, "Join a friend", Kind::Secondary, true), (ADD, "Add server", Kind::Secondary, true), (DIRECT, "Direct connect", Kind::Secondary, true), (REFRESH, "Refresh", Kind::Ghost, true), @@ -955,6 +960,48 @@ fn multiplayer_page(ui: &mut Ui, x: f32, w: f32, screen: &Screen, caret: bool) { ); ui.divider(x, y + rh, w); } + Screen::Friend { code } => { + let y = header( + ui, + x, + "Join a friend", + "Paste the invite code your friend sees in their pause menu.", + ); + let available = horizon_friends::relay_url().is_some(); + let ok = available && horizon_friends::Code::parse(code).is_some(); + actions_right( + ui, + x + w, + y - 24.0 - 58.0, + &[ + (DONE, "Join", Kind::Primary, ok), + (BACK, "Cancel", Kind::Ghost, true), + ], + ); + ui.divider(x, y, w); + let rh = 12.0 + CONTROL + 12.0; + ui.text_line(Face::Regular, BODY, rh, x, y, color::MUTED, "Invite code"); + let fx = x + t::ROW_LABEL + 16.0; + ui.field( + FIELD_A, + [fx, y + 12.0, (w - t::ROW_LABEL - 16.0).min(240.0), CONTROL], + code, + "K7QM-3XPD", + true, + caret, + ); + ui.divider(x, y + rh, w); + if !available { + ui.text( + Face::Regular, + SMALL, + x, + y + rh + 12.0, + color::FAINT, + "Joining friends isn't available yet in this build.", + ); + } + } Screen::Disconnected { reason, retry } => { let mut y = header( ui, diff --git a/crates/horizon-client/src/game/extras.rs b/crates/horizon-client/src/game/extras.rs index b934f8279..9fd42d5ff 100644 --- a/crates/horizon-client/src/game/extras.rs +++ b/crates/horizon-client/src/game/extras.rs @@ -123,7 +123,7 @@ impl Game<'_> { { log::info!( "Horizon: reconnecting to {} in {} s", - retry.address, + horizon_client::net::shown_address(&retry.address), retry.seconds_left(std::time::Instant::now()) ); *slot = Some(retry); diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 24a2d0e3a..ad624d67e 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -158,7 +158,7 @@ impl Game<'_> { .ok_or("registries.json not found next to the resources; run the data generator reports (horizon-prepare)")?; let lang = Arc::new(horizon_client::net::load_language(&root)); let view = self.settings.render_distance.clamp(2, 32) as i8; - horizon_client::crash::set_detail("Server", address.to_owned()); + horizon_client::crash::set_detail("Server", horizon_client::net::shown_address(address)); // A signed-in account always plays under its own name. let auth = horizon_client::auth::current(); let name = auth.as_ref().map_or(name, |a| a.name.as_str()); @@ -2597,10 +2597,8 @@ impl Game<'_> { let atlas = &self.res.atlas; let (w, h) = (batch.width, batch.height); batch.fill(atlas, 0.0, 0.0, w, h, rgba(20, 20, 20, 255)); - for (i, line) in [r.status.as_str(), r.session.address.as_str()] - .iter() - .enumerate() - { + let shown = horizon_client::net::shown_address(&r.session.address); + for (i, line) in [r.status.as_str(), shown.as_str()].iter().enumerate() { let tw = HudBatch::text_width(atlas, line); batch.text( atlas, @@ -2682,7 +2680,7 @@ impl Game<'_> { pub(super) fn remote_status(&self) -> Option { let r = self.remote.as_ref()?; Some(serde_json::json!({ - "address": r.session.address, + "address": horizon_client::net::shown_address(&r.session.address), "name": r.session.name, "joined": r.joined, "status": r.status, @@ -2695,6 +2693,13 @@ impl Game<'_> { m }), "players": r.players.values().collect::>(), + // Where the other players' entities are (harnesses check movement). + "player_positions": r + .entities + .values() + .filter(|t| t.kind == "minecraft:player") + .map(|t| t.position) + .collect::>(), "health": r.health.0, "food": r.health.1, "decode_errors": r.decode_errors, diff --git a/crates/horizon-client/src/multiplayer.rs b/crates/horizon-client/src/multiplayer.rs index be1ddf2b2..0c4019568 100644 --- a/crates/horizon-client/src/multiplayer.rs +++ b/crates/horizon-client/src/multiplayer.rs @@ -45,6 +45,11 @@ pub enum Screen { Direct { address: String, }, + /// Join a friend's world with its invite code (Horizon's own, reached + /// from Horizon's multiplayer page). + Friend { + code: String, + }, Disconnected { reason: String, /// Auto-reconnect's next attempt, until it is cancelled. @@ -207,6 +212,24 @@ impl Screen { 53, ), ], + Self::Friend { code } => vec![ + b( + w / 2.0 - 100.0, + h / 4.0 + 96.0 + 12.0, + 200.0, + "Join", + horizon_friends::Code::parse(code).is_some(), + 56, + ), + b( + w / 2.0 - 100.0, + h / 4.0 + 120.0 + 12.0, + 200.0, + "Cancel", + true, + 57, + ), + ], Self::Disconnected { retry, .. } => { let mut v = vec![b( w / 2.0 - 100.0, @@ -442,6 +465,10 @@ impl Screen { blink, ); } + Self::Friend { code } => { + centered(batch, "Join a Friend", 20.0, u32::MAX); + Self::field(atlas, batch, "Invite Code", code, 100.0 - 11.0, true, blink); + } Self::Disconnected { reason, retry } => { centered( batch, @@ -487,6 +514,11 @@ impl Screen { address: String::new(), } } + (Self::List { .. }, Some(47)) => { + *self = Self::Friend { + code: String::new(), + } + } (Self::List { .. }, Some(42)) => { *self = Self::Edit { index: None, @@ -568,13 +600,21 @@ impl Screen { *self = Self::list(saves); } ( - Self::Edit { .. } | Self::Direct { .. } | Self::Disconnected { .. }, - Some(51 | 53 | 54), + Self::Edit { .. } + | Self::Direct { .. } + | Self::Friend { .. } + | Self::Disconnected { .. }, + Some(51 | 53 | 54 | 57), ) => *self = Self::list(saves), (Self::Disconnected { retry, .. }, Some(55)) => *retry = None, (Self::Direct { address }, Some(52)) => { return Outcome::Connect(address.trim().to_owned()); } + (Self::Friend { code }, Some(56)) => { + if let Some(code) = horizon_friends::Code::parse(code) { + return Outcome::Connect(format!("{}{code}", crate::net::FRIEND)); + } + } (Self::Edit { focus, .. }, None) => { for (i, fy) in [(0u8, 53.0 + 11.0), (1, 94.0 + 11.0)] { if y >= fy && y < fy + 20.0 && (x - w / 2.0).abs() < 100.0 { @@ -595,6 +635,7 @@ impl Screen { .. } => Some(if *focus == 0 { name } else { address }), Self::Direct { address } => Some(address), + Self::Friend { code } => Some(code), _ => None, } } @@ -614,6 +655,7 @@ impl Screen { Self::Edit { focus: 0, .. } => ("server.name", 0), Self::Edit { .. } => ("server.address", 0), Self::Direct { .. } => ("server.direct", 0), + Self::Friend { .. } => ("friend.code", 0), _ => return None, }; self.focused_field().map(|f| (id, f, 128)) diff --git a/crates/horizon-client/src/net.rs b/crates/horizon-client/src/net.rs index ef1938ead..8af10f66a 100644 --- a/crates/horizon-client/src/net.rs +++ b/crates/horizon-client/src/net.rs @@ -145,6 +145,54 @@ impl Drop for Session { } } +/// An address of the form `friend:K7QM-3XPD` joins a friend's world through +/// its invite code (horizon-friends): the session goes through a tunnel the +/// client reaches on a loopback port, so everything after is a plain join. +pub const FRIEND: &str = horizon_friends::ADDRESS_PREFIX; + +/// An address as players and logs see it: a friend's invite code without +/// its secret half. +pub fn shown_address(address: &str) -> String { + match address.strip_prefix(FRIEND) { + Some(code) => match horizon_friends::Code::parse(code) { + Some(code) => format!("Friend's world ({}-****)", code.nameplate), + None => "Friend's world".to_owned(), + }, + None => address.to_owned(), + } +} + +/// Find the friend's world behind the code and open the tunnel: the loopback +/// address to connect to. +fn join_friend(code: &str, send: &Sender) -> Result<(String, u16), String> { + use horizon_friends::{ + Code, JoinError, PathMode, + guest::{self, GuestConfig}, + }; + let code = Code::parse(code) + .ok_or("That isn't an invite code: codes are eight letters and digits, like K7QM-3XPD.")?; + let relay = horizon_friends::relay_url().ok_or_else(|| JoinError::NotAvailable.to_string())?; + status(send, "Finding your friend's world..."); + let tunnel = guest::join(&GuestConfig { + relay, + code, + protocol: PROTOCOL_VERSION, + game: horizon_protocol::GAME_VERSION.to_owned(), + path: PathMode::from_env(), + }) + .map_err(|e| e.to_string())?; + status( + send, + if tunnel.direct { + "Connected straight to your friend..." + } else { + "Connected to your friend through the relay..." + }, + ); + let (port, _) = tunnel.serve_loopback().map_err(|e| e.to_string())?; + Ok(("127.0.0.1".to_owned(), port)) +} + fn status(send: &Sender, text: &str) { let _ = send.send(Event::Status(text.to_owned())); } @@ -169,10 +217,16 @@ fn run( shared_writer: &Mutex>, shared_counters: &Mutex>>, ) -> Result { - let Some((host, port)) = parse_address(address) else { - return Ok(format!("Invalid server address: {address}")); + let (host, port) = match address.strip_prefix(FRIEND) { + Some(code) => join_friend(code, send)?, + None => { + let Some(target) = parse_address(address) else { + return Ok(format!("Invalid server address: {address}")); + }; + status(send, "Connecting to the server..."); + target + } }; - status(send, "Connecting to the server..."); let mut c = Connection::connect(&host, port, Duration::from_secs(10)).map_err(|e| e.to_string())?; *shared_counters.lock().unwrap() = Some(c.reader.counters.clone()); diff --git a/crates/horizon-friends/Cargo.toml b/crates/horizon-friends/Cargo.toml index afe5dbe62..d53b9435f 100644 --- a/crates/horizon-friends/Cargo.toml +++ b/crates/horizon-friends/Cargo.toml @@ -1,9 +1,8 @@ [package] name = "horizon-friends" version = "0.1.0" -edition.workspace = true -license.workspace = true -rust-version.workspace = true +edition = "2024" +license = "MIT" description = "Play with friends: invite codes, the relay protocol, the end-to-end encrypted tunnel between a host's integrated server and its guests" [dependencies] diff --git a/crates/horizon-friends/src/lib.rs b/crates/horizon-friends/src/lib.rs index ac0e037ab..0a0c2d10c 100644 --- a/crates/horizon-friends/src/lib.rs +++ b/crates/horizon-friends/src/lib.rs @@ -32,6 +32,11 @@ use std::{ time::Duration, }; +/// The game's server address for a friend's world: `friend:K7QM-3XPD` +/// (`horizon-client --server friend:…`, what the launcher's Join a friend +/// starts). +pub const ADDRESS_PREFIX: &str = "friend:"; + /// Fill `buf` from the OS random generator. pub(crate) fn fill_random(buf: &mut [u8]) -> io::Result<()> { getrandom::fill(buf).map_err(|e| io::Error::other(e.to_string())) diff --git a/launcher/Cargo.lock b/launcher/Cargo.lock index 893272f99..262ee3628 100644 --- a/launcher/Cargo.lock +++ b/launcher/Cargo.lock @@ -8,6 +8,16 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" +[[package]] +name = "aead" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0" +dependencies = [ + "crypto-common 0.1.7", + "generic-array", +] + [[package]] name = "aes" version = "0.8.4" @@ -859,6 +869,17 @@ dependencies = [ "libc", ] +[[package]] +name = "chacha20" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3613f74bd2eac03dad61bd53dbe620703d4371614fe0bc3b9f04dd36fe4e818" +dependencies = [ + "cfg-if", + "cipher", + "cpufeatures 0.2.17", +] + [[package]] name = "chacha20" version = "0.10.2" @@ -870,6 +891,19 @@ dependencies = [ "rand_core 0.10.1", ] +[[package]] +name = "chacha20poly1305" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10cd79432192d1c0f4e1a0fef9527696cc039165d729fb41b3f4f4f354c2dc35" +dependencies = [ + "aead", + "chacha20 0.9.1", + "cipher", + "poly1305", + "zeroize", +] + [[package]] name = "cipher" version = "0.4.4" @@ -1351,6 +1385,32 @@ version = "0.0.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e2931af7e13dc045d8e9d26afccc6fa115d64e115c9c84b1166288b46f6782c2" +[[package]] +name = "curve25519-dalek" +version = "4.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97fb8b7c4503de7d6ae7b42ab72a5a59857b4c937ec27a3d4539dba95b5ab2be" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "curve25519-dalek-derive", + "fiat-crypto", + "rand_core 0.6.4", + "rustc_version", + "subtle", +] + +[[package]] +name = "curve25519-dalek-derive" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "data-url" version = "0.3.2" @@ -1731,6 +1791,12 @@ dependencies = [ "simd-adler32", ] +[[package]] +name = "fiat-crypto" +version = "0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d" + [[package]] name = "filedescriptor" version = "0.8.3" @@ -2563,6 +2629,20 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "horizon-friends" +version = "0.1.0" +dependencies = [ + "chacha20poly1305", + "getrandom 0.3.4", + "hkdf", + "serde", + "serde_json", + "sha2 0.10.9", + "socket2 0.5.10", + "spake2", +] + [[package]] name = "horizon-launcher" version = "0.1.5" @@ -2573,6 +2653,7 @@ dependencies = [ "futures-lite 2.6.1", "getrandom 0.3.4", "gpui", + "horizon-friends", "horizon-prepare", "horizon-theme", "keyring", @@ -2701,7 +2782,7 @@ dependencies = [ "hyper", "libc", "pin-project-lite", - "socket2", + "socket2 0.6.5", "tokio", "tower-service", "tracing", @@ -3766,6 +3847,12 @@ dependencies = [ "zvariant", ] +[[package]] +name = "opaque-debug" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" + [[package]] name = "open" version = "5.4.4" @@ -3975,6 +4062,17 @@ version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5da3b0203fd7ee5720aa0b5e790b591aa5d3f41c3ed2c34a3a393382198af2f7" +[[package]] +name = "poly1305" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8159bd90725d2df49889a078b54f4f79e87f1f8a8444194cdca81d38f5393abf" +dependencies = [ + "cpufeatures 0.2.17", + "opaque-debug", + "universal-hash", +] + [[package]] name = "postage" version = "0.5.0" @@ -4166,7 +4264,7 @@ dependencies = [ "quinn-udp", "rustc-hash 2.1.3", "rustls", - "socket2", + "socket2 0.6.5", "thiserror 2.0.21", "tokio", "tracing", @@ -4204,7 +4302,7 @@ dependencies = [ "cfg_aliases", "libc", "once_cell", - "socket2", + "socket2 0.6.5", "tracing", "windows-sys 0.61.2", ] @@ -4257,7 +4355,7 @@ version = "0.10.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af" dependencies = [ - "chacha20", + "chacha20 0.10.2", "getrandom 0.4.3", "rand_core 0.10.1", ] @@ -5157,6 +5255,16 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dd538fb6910ac1099850255cf94a94df6551fbdd602454387d0adb2d1ca6dead" +[[package]] +name = "socket2" +version = "0.5.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e22376abed350d73dd1cd119b57ffccad95b4e585a7cda43e286245ce23c0678" +dependencies = [ + "libc", + "windows-sys 0.52.0", +] + [[package]] name = "socket2" version = "0.6.5" @@ -5167,6 +5275,18 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "spake2" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c5482afe85a0b6ce956c945401598dbc527593c77ba51d0a87a586938b1b893a" +dependencies = [ + "curve25519-dalek", + "hkdf", + "rand_core 0.6.4", + "sha2 0.10.9", +] + [[package]] name = "spin" version = "0.9.9" @@ -5686,7 +5806,7 @@ dependencies = [ "libc", "mio", "pin-project-lite", - "socket2", + "socket2 0.6.5", "windows-sys 0.61.2", ] @@ -6004,6 +6124,16 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254" +[[package]] +name = "universal-hash" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea" +dependencies = [ + "crypto-common 0.1.7", + "subtle", +] + [[package]] name = "untrusted" version = "0.9.0" diff --git a/launcher/Cargo.toml b/launcher/Cargo.toml index 267b6707e..f2c24f429 100644 --- a/launcher/Cargo.toml +++ b/launcher/Cargo.toml @@ -21,6 +21,8 @@ self-replace = "1" clap = { version = "4", features = ["derive"] } horizon-theme = { path = "../crates/horizon-theme" } horizon-prepare = { path = "../crates/horizon-prepare" } +# Join a friend: invite codes (the game does the joining). +horizon-friends = { path = "../crates/horizon-friends" } # The session file's random name. getrandom = "0.3" diff --git a/launcher/src/backend.rs b/launcher/src/backend.rs index b695b4ae2..08c679a88 100644 --- a/launcher/src/backend.rs +++ b/launcher/src/backend.rs @@ -1055,6 +1055,15 @@ pub fn client(tag: &str) -> Result { Ok(cmd) } +/// Start the game straight into a friend's world: `--server friend:CODE`. +pub fn join_friend(cmd: &mut Command, code: &str) -> Result<(), String> { + let code = horizon_friends::Code::parse(code) + .ok_or("That isn't an invite code: codes are eight letters and digits, like K7QM-3XPD.")?; + cmd.arg("--server") + .arg(format!("{}{code}", horizon_friends::ADDRESS_PREFIX)); + Ok(()) +} + /// The dedicated server's command in `folder`, once prepared and the EULA is agreed to. pub fn server(tag: &str, folder: &Path, accept_eula: bool) -> Result { need_prepared(tag)?; diff --git a/launcher/src/cli.rs b/launcher/src/cli.rs index 095d25c4a..600b6eaf8 100644 --- a/launcher/src/cli.rs +++ b/launcher/src/cli.rs @@ -63,6 +63,9 @@ enum Cmd { Play { #[arg(long)] version: Option, + /// Join a friend's world with its invite code + #[arg(long)] + join: Option, }, /// Run a dedicated server here; type commands into its console Server { @@ -255,9 +258,13 @@ fn execute(command: Cmd, as_json: bool) -> Result<(), String> { } println!("{tag} is prepared."); } - Cmd::Play { version } => attached(backend::client(&backend::resolve_version( - version.as_deref(), - )?)?)?, + Cmd::Play { version, join } => { + let mut cmd = backend::client(&backend::resolve_version(version.as_deref())?)?; + if let Some(code) = join { + backend::join_friend(&mut cmd, &code)?; + } + attached(cmd)? + } Cmd::Server { dir, version, diff --git a/launcher/src/main.rs b/launcher/src/main.rs index dc7ffd7a0..6ee37b95c 100644 --- a/launcher/src/main.rs +++ b/launcher/src/main.rs @@ -138,6 +138,12 @@ struct Launcher { input: String, input_focused: bool, focus: FocusHandle, + /// Join a friend: the code typed on the Play page, and the one the game + /// starting now joins. + friend_code: String, + friend_focused: bool, + friend_focus: FocusHandle, + joining: Option, console_scroll: ScrollHandle, tx: Sender, rx: Receiver, @@ -233,6 +239,10 @@ impl Launcher { input: String::new(), input_focused: false, focus: cx.focus_handle(), + friend_code: String::new(), + friend_focused: false, + friend_focus: cx.focus_handle(), + joining: None, console_scroll: ScrollHandle::new(), tx, rx, @@ -358,6 +368,11 @@ impl Launcher { Err(e) => self.client_error = Some(format!("Playing offline: {e}")), } self.accounts = Accounts::load(); + if let Some(code) = self.joining.take() { + if let Err(e) = backend::join_friend(&mut cmd, &code) { + self.client_error = Some(e); + } + } match backend::spawn(Job::Client, cmd, self.tx.clone()) { Ok(r) => self.client = Some(r), Err(e) => self.client_error = Some(e), @@ -1404,8 +1419,9 @@ impl Launcher { Some(a) => format!("{} (Microsoft account)", a.name), None => "Offline: online servers need a Microsoft account.".to_string(), }; + rows = rows.child(self.join_friend_row(prepared && !running, cx)); rows = rows.child(index_row( - 3, + 4, "Playing as", Some(div().child(who).into_any_element()), Some( @@ -2120,6 +2136,108 @@ impl Launcher { (rows, n) } + /// Join a friend: a code field and Join, which starts the game straight + /// into the friend's world (errors show in the game). + fn join_friend_row(&self, can_play: bool, cx: &mut Context) -> Div { + let t = self.theme; + let focused = self.friend_focused; + let field = div() + .id("friend-code") + .track_focus(&self.friend_focus) + .flex() + .items_center() + .w(px(260.)) + .h(px(30.)) + .px(px(12.)) + .overflow_hidden() + .rounded(px(6.)) + .border_1() + .border_color(if focused { t.accent } else { t.rule }) + .bg(t.surface) + .font_family(theme::MONO) + .text_size(px(12.)) + .cursor_text() + .child(if self.friend_code.is_empty() && !focused { + div().text_color(t.muted).child("Paste an invite code") + } else { + // The end of a long code stays in view while typing. + let shown: String = { + let chars: Vec = self.friend_code.chars().collect(); + chars[chars.len().saturating_sub(30)..].iter().collect() + }; + div().text_color(t.ink).child(shown) + }) + .when(focused, |d| d.child(div().w(px(1.)).h(px(14.)).bg(t.ink))) + .on_click(cx.listener(|this, _: &ClickEvent, window, cx| { + window.focus(&this.friend_focus); + cx.notify(); + })) + .on_key_down(cx.listener(|this, ev: &KeyDownEvent, _, cx| { + let k = &ev.keystroke; + let paste = k.key == "v" && (k.modifiers.control || k.modifiers.platform); + match k.key.as_str() { + "enter" => this.join_friend(), + "backspace" => { + this.friend_code.pop(); + } + _ if paste => { + if let Some(text) = cx.read_from_clipboard().and_then(|c| c.text()) { + this.friend_code.push_str(text.trim()); + } + } + _ if !k.modifiers.control && !k.modifiers.platform => { + if let Some(ch) = &k.key_char { + this.friend_code.push_str(ch); + } + } + _ => return, + } + this.friend_code.truncate(256); + cx.stop_propagation(); + cx.notify(); + })); + let valid = horizon_friends::invite::parse(&self.friend_code).is_some(); + let mut join = button("join-friend", "Join", Kind::Secondary, &t); + if can_play && valid { + join = join.on_click(cx.listener(|this, _: &ClickEvent, _, cx| { + this.join_friend(); + cx.notify(); + })); + } else { + join = disabled(join); + } + index_row( + 3, + "Join a friend", + Some( + div() + .child("Paste the code a friend shows when they invite you.") + .into_any_element(), + ), + Some( + div() + .flex() + .items_center() + .gap(px(8.)) + .child(field) + .child(join) + .into_any_element(), + ), + &t, + ) + } + + fn join_friend(&mut self) { + if self.mode != Mode::Client || horizon_friends::invite::parse(&self.friend_code).is_none() { + return; + } + self.joining = Some(self.friend_code.clone()); + self.play(); + if self.starting_client.is_none() { + self.joining = None; + } + } + fn console(&self, cx: &mut Context) -> Div { let t = self.theme; let running = self.server.is_some(); @@ -2585,6 +2703,7 @@ impl Render for Launcher { fn render(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement { let t = self.theme; self.input_focused = self.focus.is_focused(window); + self.friend_focused = self.friend_focus.is_focused(window); let content = match self.page { Page::Play => self.play_page(cx), Page::Versions => self.versions_page(cx), diff --git a/tools/test_friends.py b/tools/test_friends.py new file mode 100644 index 000000000..482aea2de --- /dev/null +++ b/tools/test_friends.py @@ -0,0 +1,327 @@ +#!/usr/bin/env python3 +"""Play with friends end to end, without the internet. + +A relay (`horizon-relay`) on a free local port; a host Horizon that opens a +world and shares it behind an invite code (`friends host`); a guest Horizon +that joins with the code (`connect friend:CODE`). The guest joins twice: +first on the direct path, then started with HORIZON_FRIENDS_PATH=relay so +the session goes through the relay. Each time both sides must see the +other's chat line, the other moving, a block the host places and the block +the guest breaks; the host's counts say which path each session took, and +the relay's relayed bytes must stay small for the direct session and grow +with the relayed one. Last, the host stops sharing and a guest using the +old code is told the invite has ended. + + python3 tools/test_friends.py --client target/fast/horizon-client --relay target/fast/horizon-relay + +`--relay-url HOST:PORT` uses a relay already running elsewhere (two +machines); `--role host|guest` then runs one side only and prints or takes +the code (`--code`). Needs a display on Linux (xvfb-run -a). +""" +import argparse +import json +import math +import os +from pathlib import Path +import socket +import subprocess +import tempfile +import time +import urllib.request + +ROOT = Path(__file__).resolve().parents[1] + + +def command(endpoint, line, check=True): + with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as connection: + connection.settimeout(60) + connection.connect(str(endpoint)) + connection.sendall((line + '\n').encode()) + with connection.makefile('r') as reply: + result = json.loads(reply.readline()) + if check: + assert 'error' not in result, (line, result) + return result + + +def wait_for(endpoint, line, predicate, timeout=60, what=None): + deadline = time.monotonic() + timeout + last = None + while time.monotonic() < deadline: + try: + last = command(endpoint, line, check=False) + except (FileNotFoundError, ConnectionRefusedError): + time.sleep(0.1) + continue + try: + if predicate(last): + return last + except (KeyError, TypeError, IndexError): + pass + time.sleep(0.1) + raise AssertionError(f'timed out waiting for {what or line}: {last}') + + +def free_port(): + with socket.socket() as s: + s.bind(('127.0.0.1', 0)) + return s.getsockname()[1] + + +def health(relay_url): + with urllib.request.urlopen(f'http://{relay_url}/health', timeout=5) as r: + return json.loads(r.read()) + + +class Game: + """A Horizon client with a control socket in its own home.""" + + def __init__(self, client, resources, work, name, env): + self.home = work / name + self.home.mkdir() + self.endpoint = self.home / 'c.sock' + self.log = (self.home / 'client.log').open('w+') + self.process = subprocess.Popen([ + str(client), '--resources', str(resources), '--render-distance', '2', '--test-terrain', + '--control-socket', str(self.endpoint), '--timeout-seconds', '600', + ], cwd=self.home, env=dict(os.environ, HORIZON_HOME=str(self.home), HORIZON_NO_AUDIO='1', **env), + stdout=self.log, stderr=subprocess.STDOUT) + wait_for(self.endpoint, 'screen', lambda v: v['screen'] == 'title', 120, f'{name} title') + + def __call__(self, line, check=True): + return command(self.endpoint, line, check) + + def wait(self, line, predicate, timeout=60, what=None): + return wait_for(self.endpoint, line, predicate, timeout, what) + + def stop(self): + if self.process.poll() is None: + try: + self('quit', check=False) + self.process.wait(timeout=20) + except Exception: + self.process.terminate() + try: + self.process.wait(timeout=10) + except subprocess.TimeoutExpired: + self.process.kill() + self.log.seek(0) + return self.log.read() + + +def host_world(host): + host('open Friends 0 creative') + host.wait('status', lambda v: v['player'] is not None and v['pending_chunks'] == 0, 120, 'host world') + assert host('friends status')['available'], 'HORIZON_RELAY_URL did not reach the host' + host('friends host') + return host.wait('friends status', lambda v: v['code'], 30, 'invite code')['code'] + + +def guest_pos(host, name): + guests = host('lan status')['guests'] + return next(g['position'] for g in guests if g['name'] == name) + + +def play_together(host, guest, name, round_index): + """Chat, movement and blocks seen from both sides.""" + host.wait('lan status', lambda v: any(g['name'] == name and g['placed'] for g in v['guests']), 60, + 'the guest in the host world') + guest.wait('status', lambda v: v['server']['joined'] and v['player'] is not None, 60, 'guest joined') + # Chat both ways. + guest(f'chat hello from {name} {round_index}') + host.wait('chat-log 20', lambda v: any(f'hello from {name} {round_index}' in l for l in v['chat']), 30, + 'guest chat on the host') + host(f'chat hello from the host {round_index}') + guest.wait('status', lambda v: any(f'hello from the host {round_index}' in l for l in v['server']['chat']), 30, + 'host chat on the guest') + # The guest walks; the host sees it move. + before = guest_pos(host, name) + guest('look 0 0') + guest('key w down') + time.sleep(1.5) + guest('key w up') + host.wait('lan status', lambda v: math.dist(before, next(g['position'] for g in v['guests'] if g['name'] == name)) > 1.0, + 20, 'guest movement on the host') + # The host moves; the guest sees the host's player there. + hp = host('status')['player']['position'] + target = [hp[0] + 3.0, hp[1], hp[2] + 1.0] + host(f'tp {target[0]} {target[1]} {target[2]}') + guest.wait('status', lambda v: any(math.dist(p, target) < 0.6 for p in v['server']['player_positions']), 20, + 'host movement on the guest') + # A block the host places, which the guest sees and then breaks. + gp = guest('status')['player']['position'] + feet = [math.floor(gp[0]), math.floor(gp[1]), math.floor(gp[2])] + block = [feet[0] + 2, feet[1] + 1, feet[2]] + # Clear the line of sight (the test terrain has hills), then the block at eye level. + host(f'fill {feet[0] + 1} {feet[1]} {feet[2]} {feet[0] + 1} {feet[1] + 2} {feet[2]} minecraft:air') + host(f'setblock {block[0]} {block[1]} {block[2]} minecraft:gold_block') + guest.wait(f'getblock {block[0]} {block[1]} {block[2]}', lambda v: v['block'] == 'minecraft:gold_block', 20, + 'the host block on the guest') + eye = [gp[0], gp[1] + 1.62, gp[2]] + dx, dy, dz = block[0] + 0.5 - eye[0], block[1] + 0.5 - eye[1], block[2] + 0.5 - eye[2] + yaw = math.degrees(math.atan2(-dx, dz)) + pitch = -math.degrees(math.atan2(dy, math.hypot(dx, dz))) + guest(f'look {yaw:.3f} {pitch:.3f}') + guest.wait('status', lambda v: v['target']['pos'] == block, 10, 'the guest aiming at the block') + # Held for a few ticks, as a player clicks (creative breaks at once). + guest('mouse left down') + time.sleep(0.25) + guest('mouse left up') + host.wait(f'getblock {block[0]} {block[1]} {block[2]}', lambda v: v['block'] == 'minecraft:air', 20, + 'the guest breaking the block, on the host') + guest.wait(f'getblock {block[0]} {block[1]} {block[2]}', lambda v: v['block'] == 'minecraft:air', 20, + 'the broken block on the guest') + + +def join(guest, code, name): + guest(f'connect friend:{code} {name}') + + +def leave(host, guest, name): + guest('disconnect') + host.wait('lan status', lambda v: all(g['name'] != name for g in v['guests']), 30, 'the guest leaving') + + +def full(args, work, relay_url): + env = {'HORIZON_RELAY_URL': relay_url} + host = Game(args.client, args.resources, work, 'host', env) + games = [host] + try: + code = host_world(host) + print(f'host shares the world: {code[:4]}-****') + if args.baseline: + # The same checks over plain LAN, without the tunnel: the behaviour + # the tunnel must reproduce. + guest = Game(args.client, args.resources, work, 'guest-lan', env) + games.append(guest) + guest(f'connect 127.0.0.1:{host("lan status")["port"]} Plain') + play_together(host, guest, 'Plain', 0) + print('plain LAN: chat, movement and blocks both ways') + leave(host, guest, 'Plain') + guest.stop() + # Direct path. + guest = Game(args.client, args.resources, work, 'guest-direct', env) + games.append(guest) + before = health(relay_url)['relayed_bytes'] + join(guest, code, 'Guest') + play_together(host, guest, 'Guest', 1) + direct_bytes = health(relay_url)['relayed_bytes'] - before + assert host('friends status')['direct'] == 1, host('friends status') + assert direct_bytes < 64 * 1024, f'the direct session went through the relay ({direct_bytes} bytes)' + print(f'direct path: chat, movement and blocks both ways; relay carried {direct_bytes} bytes') + leave(host, guest, 'Guest') + guest.stop() + # Forced relay path. + guest = Game(args.client, args.resources, work, 'guest-relay', + dict(env, HORIZON_FRIENDS_PATH='relay')) + games.append(guest) + before = health(relay_url)['relayed_bytes'] + join(guest, code, 'Relayed') + play_together(host, guest, 'Relayed', 2) + relayed_bytes = health(relay_url)['relayed_bytes'] - before + status = host('friends status') + assert status['relayed'] == 1, status + # Render distance 2: the join is some tens of kB of compressed chunks. + assert relayed_bytes > max(32 * 1024, 4 * direct_bytes), \ + f'the relayed session carried only {relayed_bytes} bytes (direct: {direct_bytes})' + print(f'relay path: chat, movement and blocks both ways; relay carried {relayed_bytes} bytes') + leave(host, guest, 'Relayed') + # The code ends with sharing. + host('friends stop') + assert host('friends status')['code'] is None + join(guest, code, 'Late') + reason = guest.wait('screen', lambda v: v['menu']['disconnected'], 30, 'the ended invite')['menu']['disconnected'] + assert 'invite has ended' in reason, reason + print(f'after stopping: "{reason}"') + assert host('lan status') == {'open': False}, 'sharing opened LAN, so stopping closes it' + return code + except Exception: + for g in games: + print(f'--- {g.home.name} log tail ---') + print('\n'.join(g.stop().splitlines()[-25:])) + raise + finally: + for g in games: + g.stop() + + +def one_side(args, work): + env = {'HORIZON_RELAY_URL': args.relay_url} + if args.path: + env['HORIZON_FRIENDS_PATH'] = args.path + game = Game(args.client, args.resources, work, args.role, env) + try: + if args.role == 'host': + code = host_world(game) + print(f'CODE {code}', flush=True) + game.wait('lan status', lambda v: v['guests'], args.wait, 'a guest') + game.wait('lan status', lambda v: not v['guests'], args.wait, 'the guest leaving') + print(f'host: {game("friends status")}') + else: + join(game, args.code, 'Remote') + v = game.wait('status', lambda v: v['server']['joined'] and v['player'] is not None, 60, 'joined') + game('chat hello across machines') + game.wait('status', lambda v: v['server']['chunks'] > 0, 30, 'chunks') + print(f'guest joined: {v["server"]["address"]}, {v["server"]["chunks"]} chunks') + game('key w down') + time.sleep(1.0) + game('key w up') + game('disconnect') + finally: + game.stop() + + +def main(): + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument('--client', type=Path, required=True) + parser.add_argument('--relay', type=Path, help='horizon-relay binary (started on a free local port)') + parser.add_argument('--relay-url', help='an already running relay, HOST:PORT') + parser.add_argument('--resources', type=Path, default=ROOT / '.local/horizon-client/26.3') + parser.add_argument('--role', choices=['host', 'guest']) + parser.add_argument('--code') + parser.add_argument('--path', choices=['relay', 'direct']) + parser.add_argument('--wait', type=float, default=600) + parser.add_argument('--baseline', action='store_true', help='first run the same checks over plain LAN') + args = parser.parse_args() + args.client, args.resources = args.client.resolve(), args.resources.resolve() + # Short: Unix socket paths are limited to about 100 bytes. + with tempfile.TemporaryDirectory(prefix='hzf-', dir='/tmp') as directory: + work = Path(directory) + if args.role: + assert args.relay_url, '--role needs --relay-url' + return one_side(args, work) + relay = None + relay_url = args.relay_url + if not relay_url: + assert args.relay, 'give --relay or --relay-url' + port = free_port() + relay_url = f'127.0.0.1:{port}' + relay_log = (work / 'relay.log').open('w+') + relay = subprocess.Popen([str(args.relay.resolve())], env=dict(os.environ, PORT=str(port)), + stdout=relay_log, stderr=subprocess.STDOUT) + deadline = time.monotonic() + 10 + while True: + try: + health(relay_url) + break + except OSError: + assert time.monotonic() < deadline, 'the relay did not start' + time.sleep(0.1) + try: + code = full(args, work, relay_url) + finally: + if relay: + relay.terminate() + relay.wait(timeout=10) + relay_log.seek(0) + text = relay_log.read() + print(f'relay log: {text.splitlines()}') + if relay: + # Counts only: no code, no address, no name. + for secret in [code[:4], '127.0.0.1', 'Guest', 'Relayed']: + assert secret not in text, f'the relay logged {secret!r}' + print('Play with friends passed: direct and relayed sessions, chat, movement and blocks both ways') + + +if __name__ == '__main__': + main()