From dc42425c0197c5918ba3739d5aa20b8678af6199 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 17 Oct 2026 01:33:24 +0200 Subject: [PATCH] Integrated server: Open to LAN Single player on its server thread could not be opened to the LAN: the window is a client of that server, and Open to LAN, /publish and `horizon-ctl lan` tried to start a second hub on the window's side. The server thread now publishes itself, as IntegratedServer.publishServer does: - The window asks its server with `Integrated::call` (executeBlocking): a task run between two ticks, while paused too, with its answer. - Publishing binds the port at once (a busy port fails right away), then the hub starts listening and announcing the world (LanServerPinger) with the MOTD " - ". Until then only the owner may log in; afterwards anyone may, and status pings are answered. - Unpublishing stops the listener and sends every player but the owner away (multiplayer.disconnect.server_shutdown). - /publish and /unpublish run on the server for the player who types them, and the integrated server's command tree (with publish, without the dedicated-only commands) is what its players get. - The owner's level follows Allow Commands; other players get game master commands only when guests may use commands and the world allows them (IntegratedServer.getCustomPermissionLevel). Every player's command runs at their own level. - The world options screen reads and applies its settings on the server: difficulty, default and personal game mode, Allow Commands and the LAN settings; the window shows the outcome. - A published world does not pause (Minecraft.pause needs !isPublished), and F3+Escape follows the same rule. - Memory connections are never compressed, whatever the threshold (Connection.isMemoryConnection), so network players get the usual 256. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/examples/lan_flat.rs | 1 + crates/horizon-client/src/game.rs | 5 +- .../horizon-client/src/game/commands/extra.rs | 26 +- crates/horizon-client/src/game/debug_keys.rs | 2 +- crates/horizon-client/src/game/dedicated.rs | 1 + crates/horizon-client/src/game/integrated.rs | 285 ++++++++++++++++-- crates/horizon-client/src/game/lan.rs | 122 +++++--- crates/horizon-client/src/game/lan_actions.rs | 25 ++ crates/horizon-client/src/game/lan_screen.rs | 86 ++++-- crates/horizon-client/src/lan/conn.rs | 3 +- crates/horizon-client/src/lan/hub.rs | 15 +- crates/horizon-client/src/lan/mod.rs | 113 ++++--- crates/horizon-client/tests/lan_bot.rs | 1 + crates/horizon-protocol/src/connection.rs | 4 + 14 files changed, 571 insertions(+), 118 deletions(-) diff --git a/crates/horizon-client/examples/lan_flat.rs b/crates/horizon-client/examples/lan_flat.rs index 63ea9f136..16fc36b95 100644 --- a/crates/horizon-client/examples/lan_flat.rs +++ b/crates/horizon-client/examples/lan_flat.rs @@ -88,6 +88,7 @@ fn main() -> Result<(), Box> { seed: 0, max_players: 8, dedicated: false, + integrated: false, }, ); let mut next_entity = 100u32; diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index e03c71a48..b63c29c29 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -1085,6 +1085,8 @@ struct Game<'a> { lan: Option, /// Single player's server thread, which `remote` is connected to. integrated: Option, + /// This game is that server thread's (game/integrated.rs). + serving: Option, /// The open world is shared behind an invite code (game/friends.rs). friends: Option, world_options: Option, @@ -3644,7 +3646,7 @@ impl Game<'_> { /// `Minecraft.pause`: a single-player game with a pausing screen open. fn pauses_game(&self) -> bool { self.has_singleplayer_server() - && self.lan.is_none() + && !self.is_published() && self.title.is_none() && (matches!( self.screen, @@ -10073,6 +10075,7 @@ impl<'a> Game<'a> { remote: None, lan: None, integrated: None, + serving: None, world_options: None, options_to_world_options: false, command_block_screen: None, diff --git a/crates/horizon-client/src/game/commands/extra.rs b/crates/horizon-client/src/game/commands/extra.rs index ab41596ee..a90648043 100644 --- a/crates/horizon-client/src/game/commands/extra.rs +++ b/crates/horizon-client/src/game/commands/extra.rs @@ -758,18 +758,25 @@ impl Game<'_> { .and_then(|l| l.local_addr()) .map_or(25564, |a| i32::from(a.port())), }; - if let Some(lan) = &self.lan { - return Err(err( - "commands.publish.alreadyPublished.lan", - &[&lan.settings.port], - )); + let published = if self.serving() { + self.published_port() + } else { + self.lan.as_ref().map(|l| l.settings.port) + }; + if let Some(port) = published { + return Err(err("commands.publish.alreadyPublished.lan", &[&port])); } let settings = super::super::lan::LanSettings { port: port as u16, guest_commands: allow, force_game_mode: false, }; - if self.lan_start(settings).is_err() { + let started = if self.serving() { + self.publish(settings).is_ok() + } else { + self.lan_start(settings).is_ok() + }; + if !started { return Err(err("commands.publish.failed", &[])); } let port_text = port.to_string(); @@ -785,6 +792,13 @@ impl Game<'_> { Ok(port) } pub(super) fn cmd_unpublish(&mut self) -> R { + if self.serving() { + if !self.unpublish() { + return Err(err("commands.unpublish.notPublished", &[])); + } + self.feedback(Text::translate("commands.unpublish.success", &[])); + return Ok(1); + } if self.lan.is_none() { return Err(err("commands.unpublish.notPublished", &[])); } diff --git a/crates/horizon-client/src/game/debug_keys.rs b/crates/horizon-client/src/game/debug_keys.rs index 4008c33d9..94fd59f61 100644 --- a/crates/horizon-client/src/game/debug_keys.rs +++ b/crates/horizon-client/src/game/debug_keys.rs @@ -38,7 +38,7 @@ impl DebugHost for Host<'_, '_> { // the menu as it always has (key_pressed). let g = &mut *self.game; if without_menu && g.screen == Screen::Playing { - g.pause_menu = !(g.has_singleplayer_server() && g.lan.is_none()); + g.pause_menu = !(g.has_singleplayer_server() && !g.is_published()); g.screen = Screen::Paused; g.capture(false); g.mining = None; diff --git a/crates/horizon-client/src/game/dedicated.rs b/crates/horizon-client/src/game/dedicated.rs index 01728b351..062bb71c8 100644 --- a/crates/horizon-client/src/game/dedicated.rs +++ b/crates/horizon-client/src/game/dedicated.rs @@ -441,6 +441,7 @@ impl Game<'_> { seed: self.level.seed, max_players: props.max_players.max(0) as usize, dedicated: true, + integrated: false, }; let settings = LanSettings { port, diff --git a/crates/horizon-client/src/game/integrated.rs b/crates/horizon-client/src/game/integrated.rs index 0366627e3..ac2121e2e 100644 --- a/crates/horizon-client/src/game/integrated.rs +++ b/crates/horizon-client/src/game/integrated.rs @@ -2,6 +2,10 @@ //! its own "Server thread", as vanilla's does, and the window joins it as a //! player through memory, so a world tick never holds up a frame. //! +//! The window asks its server for what only the server knows (Open to LAN, +//! the world's options) with [`Integrated::call`], as vanilla's client calls +//! into its `IntegratedServer`. +//! //! Opt-in for now (`--server-thread` or `HORIZON_SERVER_THREAD=1`): the //! player joins as a network player, and the server side of a network player //! does not do everything single player does yet. Worlds whose player is @@ -15,7 +19,7 @@ use horizon_client::{ Result, audio::Audio, hud::HudAtlas, - lan::{MAX_PLAYERS, NetConfig, hub::HubConfig}, + lan::{Lan, MAX_PLAYERS, NetConfig, hub::HubConfig}, save::Level, settings::Settings, title::WorldOptions, @@ -23,11 +27,12 @@ use horizon_client::{ use horizon_protocol::connection::Pipe; use horizon_protocol::{crypto::offline_uuid, text::translatable}; use std::{ + net::TcpListener, path::Path, sync::{ Arc, - atomic::{AtomicBool, Ordering}, - mpsc::{Sender, channel}, + atomic::{AtomicBool, AtomicU16, Ordering}, + mpsc::{Receiver, Sender, channel, sync_channel}, }, thread::JoinHandle, time::{Duration, Instant}, @@ -39,12 +44,19 @@ struct Flags { /// `Minecraft.pause`: a single-player pause screen is open. paused: AtomicBool, stop: AtomicBool, + /// `IntegratedServer.getPort`: the port it is open to the LAN on, 0 + /// while it is not. + published: AtomicU16, } +/// Work the window hands its server thread (`MinecraftServer.execute`). +type Task = Box) + Send>; + /// The window's handle on its server thread. pub(super) struct Integrated { flags: Arc, thread: Option>, + tasks: Sender, /// The world's name (`level.dat`'s `LevelName`), for the pause menu. pub world_name: String, } @@ -53,6 +65,24 @@ impl Integrated { pub fn set_paused(&self, paused: bool) { self.flags.paused.store(paused, Ordering::Relaxed); } + /// `IntegratedServer.getPort` while `isPublished`. + pub fn published(&self) -> Option { + Some(self.flags.published.load(Ordering::Relaxed)).filter(|&p| p != 0) + } + /// `executeBlocking`: run `f` on the server thread between two ticks and + /// wait for its answer; `None` once the server has stopped. + pub fn call( + &self, + f: impl FnOnce(&mut Game<'_>) -> T + Send + 'static, + ) -> Option { + let (tx, rx) = sync_channel(1); + self.tasks + .send(Box::new(move |g| { + let _ = tx.send(f(g)); + })) + .ok()?; + rx.recv_timeout(Duration::from_secs(10)).ok() + } /// `IntegratedServer.halt(true)`: returns once the world is saved and let go. pub fn stop(mut self) { self.halt(); @@ -70,6 +100,21 @@ impl Drop for Integrated { } } +/// The server thread's side of the window's handle (`Game::serving`). +pub(super) struct Serving { + flags: Arc, + tasks: Receiver, + /// The window's profile. + owner: u128, + /// Open to LAN or closed from inside a player's command, while the hub + /// is out of its place: applied after the tick. + pending: Option, +} +enum Publish { + Open(TcpListener, LanSettings), + Close, +} + /// What the server thread hands the window once the world is open: its end /// of the connection and the world's name, or why it failed. type Ready = std::result::Result<(Pipe, String), String>; @@ -81,8 +126,11 @@ struct Launch { seed: Option, creative: bool, create: Option, - /// The window's profile: the only one let in, and the world's player. + /// The window's profile: the only one let in until the world is open to + /// the LAN, and the world's player. owner: u128, + /// Its name, for the LAN's MOTD. + player: String, } /// Whether this world opens on a server thread: asked for, and its player @@ -99,6 +147,14 @@ impl Game<'_> { pub(super) fn has_singleplayer_server(&self) -> bool { self.remote.is_none() || self.integrated.is_some() } + /// `IntegratedServer.isPublished`: the world is open to the network. + pub(super) fn is_published(&self) -> bool { + self.lan.is_some() + || self + .integrated + .as_ref() + .is_some_and(|s| s.published().is_some()) + } /// `Minecraft.doWorldLoad`: start the server thread on the world, wait /// until it can be joined, then join it through memory. pub(super) fn open_integrated( @@ -121,6 +177,7 @@ impl Game<'_> { create: create.cloned(), // An offline-mode server names its players by their offline profile. owner: offline_uuid(&player), + player: player.clone(), }; let mut options = self.options.clone(); // A server without a console: no local player, no window, no control socket. @@ -138,6 +195,7 @@ impl Game<'_> { let (res, pack, settings) = (self.res.clone(), self.pack.clone(), self.settings.clone()); let flags = Arc::new(Flags::default()); let (ready_tx, ready) = channel(); + let (tasks, server_tasks) = channel(); let server_flags = flags.clone(); let thread = std::thread::Builder::new() .name("Server thread".into()) @@ -148,7 +206,8 @@ impl Game<'_> { options, settings, launch, - &server_flags, + server_flags, + server_tasks, &ready_tx, ); if let Err(e) = result { @@ -159,6 +218,7 @@ impl Game<'_> { let mut handle = Integrated { flags, thread: Some(thread), + tasks, world_name: String::new(), }; let pipe = match ready.recv() { @@ -179,7 +239,8 @@ impl Game<'_> { fn run_integrated( &mut self, launch: Launch, - flags: &Flags, + flags: Arc, + tasks: Receiver, ready: &Sender, ) -> Result<()> { self.open_world( @@ -193,7 +254,8 @@ impl Game<'_> { let view_distance = self.settings.render_distance.clamp(2, 32); let config = HubConfig { default_game_mode: self.level.mode(), - guest_commands: true, + // Only the owner until it is opened to the LAN. + guest_commands: false, force_game_mode: false, hardcore: self.level.hardcore, view_distance, @@ -203,23 +265,28 @@ impl Game<'_> { max_players: MAX_PLAYERS, // No player of its own: the hub runs without a host. dedicated: true, + integrated: true, }; let owner = launch.owner; + let published = flags.clone(); let net = NetConfig { - // No network until it is opened to the LAN. + // No network until it is opened to the LAN; the memory connection + // is not compressed (`Connection.isMemoryConnection`). listen: false, - // A memory connection is not compressed (`Connection.isMemoryConnection`). - compression_threshold: -1, - enable_status: false, - announce: false, gate: Some(Arc::new(move |_, uuid, _| { - (uuid != owner).then(|| translatable("multiplayer.disconnect.not_whitelisted", &[])) + (uuid != owner && published.published.load(Ordering::Relaxed) == 0) + .then(|| translatable("multiplayer.disconnect.not_whitelisted", &[])) })), - ..NetConfig::lan(0, self.level.name.clone(), MAX_PLAYERS) + // IntegratedServer.initServer: the MOTD names the owner and the world. + ..NetConfig::lan( + 0, + format!("{} - {}", launch.player, self.level.name), + MAX_PLAYERS, + ) }; let settings = LanSettings { port: 0, - guest_commands: true, + guest_commands: false, force_game_mode: false, }; self.lan_host(settings, net, config, None)?; @@ -238,10 +305,17 @@ impl Game<'_> { }); host.hub.lan.connect_local()? }; + self.serving = Some(Serving { + flags: flags.clone(), + tasks, + owner, + pending: None, + }); let _ = ready.send(Ok((pipe, self.level.name.clone()))); self.settle_spawn()?; let mut next = Instant::now(); while !flags.stop.load(Ordering::Relaxed) { + self.run_tasks(); self.update_dedicated_streaming(); self.update_world(); if flags.paused.load(Ordering::Relaxed) { @@ -250,6 +324,7 @@ impl Game<'_> { } else { self.tick()?; } + self.apply_publish(); let rate = self.clock.rate().max(1.0); next += Duration::from_secs_f64(1.0 / f64::from(rate)); let now = Instant::now(); @@ -265,6 +340,10 @@ impl Game<'_> { /// `MinecraftServer.stopServer`: the players are saved and sent away, /// then the world is saved. fn stop_integrated(&mut self) -> Result<()> { + // IntegratedServer.stopServer: teardownPublishedState. + if let Some(s) = self.serving.take() { + s.flags.published.store(0, Ordering::Relaxed); + } if let Some(mut host) = self.lan.take() { for g in &host.hub.guests { self.save_guest(&host, g); @@ -287,19 +366,191 @@ impl Game<'_> { } } +/// What the world options screen shows of an integrated server. +#[derive(Clone, Copy, Debug)] +pub(super) struct ServerOptions { + pub default_mode: i32, + /// The owner's own game mode. + pub personal_mode: i32, + pub cheats: bool, + pub difficulty: u8, + pub hardcore: bool, + pub difficulty_locked: bool, + pub port: Option, + pub guest_commands: bool, + pub force: bool, +} + +/// The server thread's side. +impl Game<'_> { + /// Whether this game is an integrated server's. + pub(super) fn serving(&self) -> bool { + self.serving.is_some() + } + /// The window's requests, between two ticks. + fn run_tasks(&mut self) { + let tasks: Vec = match &self.serving { + Some(s) => s.tasks.try_iter().collect(), + None => return, + }; + for task in tasks { + task(self); + self.apply_publish(); + } + } + /// `IntegratedServer.getPort` while published. + pub(super) fn published_port(&self) -> Option { + let s = self.serving.as_ref()?; + Some(s.flags.published.load(Ordering::Relaxed)).filter(|&p| p != 0) + } + /// `IntegratedServer.publishServer`: listen on `settings.port` (0 picks + /// one) and announce the world. The socket is bound at once so a busy + /// port fails here; the hub starts listening once it is at hand. + pub(super) fn publish(&mut self, settings: LanSettings) -> std::result::Result { + let Some(s) = self.serving.as_mut() else { + return Err("not an integrated server".into()); + }; + if s.flags.published.load(Ordering::Relaxed) != 0 { + return Err("already published".into()); + } + let listener = Lan::bind(None, settings.port).map_err(|e| e.to_string())?; + let port = listener.local_addr().map_err(|e| e.to_string())?.port(); + log::info!("Published LAN server on port {port}"); + s.flags.published.store(port, Ordering::Relaxed); + s.pending = Some(Publish::Open(listener, LanSettings { port, ..settings })); + self.apply_publish(); + Ok(port) + } + /// `IntegratedServer.unpublishServer`: stop listening and send every + /// player but the owner away. False when it was not published. + pub(super) fn unpublish(&mut self) -> bool { + let Some(s) = self.serving.as_mut() else { + return false; + }; + if s.flags.published.swap(0, Ordering::Relaxed) == 0 { + return false; + } + s.pending = Some(Publish::Close); + self.apply_publish(); + true + } + /// Publish or unpublish for real, once the hub is in its place (a + /// player's `/publish` runs while it is out). + fn apply_publish(&mut self) { + if self.lan.is_none() { + return; + } + let Some(s) = self.serving.as_mut() else { + return; + }; + let (Some(pending), owner) = (s.pending.take(), s.owner) else { + return; + }; + let allow_commands = self.allow_commands(); + let Some(host) = self.lan.as_mut() else { + return; + }; + match pending { + Publish::Open(listener, settings) => { + if let Err(e) = host.hub.lan.listen_on(listener, true) { + log::error!("Horizon: Open to LAN: {e}"); + } + host.settings = settings; + host.hub.config.force_game_mode = settings.force_game_mode; + // IntegratedServer.setGuestCommandAccess, then updatePermissions. + host.hub.config.guest_commands = settings.guest_commands && allow_commands; + host.hub.resend_commands(); + } + Publish::Close => { + host.hub.lan.stop_listening(); + log::info!( + "Unpublishing integrated server (was on port {})", + host.settings.port + ); + let others: Vec = host + .hub + .guests + .iter() + .filter(|g| g.uuid != owner) + .map(|g| g.conn) + .collect(); + for conn in others { + host.hub.kick( + conn, + translatable("multiplayer.disconnect.server_shutdown", &[]), + ); + } + } + } + } + /// The world options screen's state, read on the server. + pub(super) fn server_options(&self) -> ServerOptions { + let owner = self.serving.as_ref().map(|s| s.owner); + let host = self.lan.as_ref(); + let personal_mode = host + .and_then(|h| h.hub.guests.iter().find(|g| Some(g.uuid) == owner)) + .map_or(self.level.mode(), |g| g.game_mode); + let published = self.published_port(); + ServerOptions { + default_mode: self.level.mode(), + personal_mode, + cheats: self.allow_commands(), + difficulty: self.ui.difficulty, + hardcore: self.level.hardcore, + difficulty_locked: self.level.difficulty_locked, + port: published, + guest_commands: published.is_some() && host.is_some_and(|h| h.settings.guest_commands), + force: published.is_none() || host.is_some_and(|h| h.settings.force_game_mode), + } + } + /// `IntegratedServer.setPersonalGameType`: the owner's game mode. + pub(super) fn set_owner_mode(&mut self, mode: i32) { + let Some(owner) = self.serving.as_ref().map(|s| s.owner) else { + return; + }; + if let Some(host) = self.lan.as_mut() + && let Some(conn) = host + .hub + .guests + .iter() + .find(|g| g.uuid == owner) + .map(|g| g.conn) + { + host.hub.set_game_mode(conn, mode); + } + } + /// `IntegratedServer.setWorldAllowCommands`: the owner is an operator + /// while the world allows commands; everyone's level is sent again. + pub(super) fn owner_allow_commands(&mut self, allow: bool) { + let Some(owner) = self.serving.as_ref().map(|s| s.owner) else { + return; + }; + let published = self.published_port().is_some(); + if let Some(host) = self.lan.as_mut() { + host.hub.ops.insert(owner, if allow { 4 } else { 0 }); + if published { + host.hub.config.guest_commands = allow && host.settings.guest_commands; + } + host.hub.resend_commands(); + } + } +} + /// The server thread: a game of its own over the shared resources. +#[allow(clippy::too_many_arguments)] fn serve( res: &Arc, pack: PackResources, options: Options, settings: Settings, launch: Launch, - flags: &Flags, + flags: Arc, + tasks: Receiver, ready: &Sender, ) -> Result<()> { // It draws nothing: only the font, which books and chat measure with. let atlas = HudAtlas::fonts(&options.resources)?; let audio = Audio::silent(&options.resources); let mut server = Game::new(res, pack, atlas, options, settings, audio)?; - server.run_integrated(launch, flags, ready) + server.run_integrated(launch, flags, tasks, ready) } diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index c416c202f..1d00134e4 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -31,7 +31,7 @@ use std::{ static SYNC: OnceLock, String>> = OnceLock::new(); /// The settings of the open world (WorldOptionsScreen's multiplayer section). -#[derive(Clone, Debug)] +#[derive(Clone, Copy, Debug)] pub struct LanSettings { pub port: u16, pub guest_commands: bool, @@ -316,6 +316,15 @@ impl Game<'_> { if words[0] != "lan" { return Ok(None); } + if let Some(server) = &self.integrated + && words.get(1) == Some(&"status") + { + // The hub is the server thread's. + let status = server + .call(|g| g.lan_status()) + .ok_or("the integrated server stopped")?; + return Ok(Some(status)); + } match words.get(1).copied() { Some("open") => { if self.title.is_some() { @@ -337,43 +346,58 @@ impl Game<'_> { self.lan_close(true); Ok(Some(json!({ "ok": true }))) } - Some("status") => Ok(Some(match &self.lan { - Some(h) => json!({ - "open": true, - "host": h.host_name, - "port": h.settings.port, - "guests": h.hub.guests.iter().map(|g| json!({ - "name": g.name, - "position": g.position, - "placed": g.placed, - "loaded": g.loaded, - "game_mode": g.game_mode, - "sneaking": g.sneaking, - "health": g.health, - // FoodData: food level, saturation and exhaustion. - "food": [ - f64::from(g.food), - f64::from(g.saturation), - g.motion.as_ref().map_or(0.0, |m| f64::from(m.health.food.exhaustion)), - ], - "chunks": g.sent_chunks.len(), - "tracked": g.tracker.len(), - // The armour the host draws on this guest, head to feet. - "model_armor": h.models.get(&g.conn).map(|m| { - [&m.extra.head, &m.extra.chest, &m.extra.legs, &m.extra.feet] - .map(|s| s.as_deref()) - }), - })).collect::>(), - }), - None => json!({ "open": false }), - })), + Some("status") => Ok(Some(self.lan_status())), _ => Err("lan open|close|status".into()), } } + /// `horizon-ctl lan status`. + fn lan_status(&self) -> serde_json::Value { + use serde_json::json; + match &self.lan { + Some(h) if !self.serving() || self.published_port().is_some() => json!({ + "open": true, + "host": h.host_name, + "port": h.settings.port, + "guests": h.hub.guests.iter().map(|g| json!({ + "name": g.name, + "position": g.position, + "placed": g.placed, + "loaded": g.loaded, + "game_mode": g.game_mode, + "sneaking": g.sneaking, + "health": g.health, + // FoodData: food level, saturation and exhaustion. + "food": [ + f64::from(g.food), + f64::from(g.saturation), + g.motion.as_ref().map_or(0.0, |m| f64::from(m.health.food.exhaustion)), + ], + "chunks": g.sent_chunks.len(), + "tracked": g.tracker.len(), + // The armour the host draws on this guest, head to feet. + "model_armor": h.models.get(&g.conn).map(|m| { + [&m.extra.head, &m.extra.chest, &m.extra.legs, &m.extra.feet] + .map(|s| s.as_deref()) + }), + })).collect::>(), + }), + _ => json!({ "open": false }), + } + } + pub(super) fn lan_open(&mut self, settings: LanSettings) -> Result<()> { - self.lan_start(settings)?; - let port = self.lan.as_ref().map_or(0, |l| l.settings.port); + let port = if let Some(server) = &self.integrated { + // ShareToLanScreen: IntegratedServer.publishServer. + server + .call(move |g| g.publish(settings)) + .ok_or("the integrated server stopped")?? + } else if self.serving() { + return self.publish(settings).map(drop).map_err(Into::into); + } else { + self.lan_start(settings)?; + self.lan.as_ref().map_or(0, |l| l.settings.port) + }; self.system_message(Text::translate( "menu.multiplayerOptions.publish.started.lan", &[Text::literal(port.to_string())], @@ -408,6 +432,7 @@ impl Game<'_> { seed: self.level.seed, max_players: MAX_PLAYERS, dedicated: false, + integrated: false, }; let net = NetConfig::lan(settings.port, motd, MAX_PLAYERS); self.lan_host(settings, net, config, Some(host_uuid)) @@ -484,6 +509,22 @@ impl Game<'_> { /// IntegratedServer.unpublishServer: the guests are sent away. pub(super) fn lan_close(&mut self, announce: bool) { + if self.integrated.is_some() || self.serving() { + let closed = match &self.integrated { + Some(server) => server.call(|g| g.unpublish()).unwrap_or(false), + None => self.unpublish(), + }; + if closed { + self.friends_lan_closed(); + } + if closed && announce && self.integrated.is_some() { + self.system_message(Text::translate( + "menu.multiplayerOptions.publish.stopped", + &[], + )); + } + return; + } self.friends_lan_closed(); let Some(mut host) = self.lan.take() else { return; @@ -541,16 +582,29 @@ impl Game<'_> { /// New command access and game mode forcing settings of the open world. pub(super) fn lan_apply_settings(&mut self, guest_commands: bool, force: bool) { + if let Some(server) = &self.integrated { + server.call(move |g| g.lan_apply_settings(guest_commands, force)); + return; + } + // An integrated server gives guests commands only where the world + // allows them (IntegratedServer.getCustomPermissionLevel). + let effective = guest_commands && (!self.serving() || self.allow_commands()); if let Some(host) = self.lan.as_mut() { host.settings.guest_commands = guest_commands; host.settings.force_game_mode = force; - host.hub.config.guest_commands = guest_commands; + host.hub.config.guest_commands = effective; host.hub.config.force_game_mode = force; host.hub.resend_commands(); } } pub(super) fn lan_port(&self) -> Option { + if let Some(server) = &self.integrated { + return server.published(); + } + if self.serving() { + return self.published_port(); + } self.lan.as_ref().map(|h| h.settings.port) } diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 1f6921e0c..176108372 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -676,6 +676,31 @@ impl Game<'_> { ); return; } + // An integrated server runs every player's commands at their own + // permission level (`CommandSourceStack.permissions`). + if host.hub.config.integrated { + let Some(level) = host.hub.guest(conn).map(|g| g.permission) else { + return; + }; + let command = command.trim_start_matches('/').to_owned(); + let lines = self.as_guest(host, conn, |g| { + let console = std::mem::replace(&mut g.ui.registries.permission, level); + g.chat_capture = Some(Vec::new()); + g.run_command(&command); + g.ui.registries.permission = console; + g.chat_capture.take().unwrap_or_default() + }); + for line in lines.unwrap_or_default() { + host.hub.send_to( + conn, + &C::SystemChat(play::SystemChat { + content: horizon_client::lan::data::component_nbt(&line.component()), + overlay: false, + }), + ); + } + return; + } // A LAN world follows its Allow Commands; a dedicated server leaves // it to the ops list (the guest's permission level). let allowed = self.options.dedicated.is_some() || self.allow_commands(); diff --git a/crates/horizon-client/src/game/lan_screen.rs b/crates/horizon-client/src/game/lan_screen.rs index 2402a5286..7c4533a16 100644 --- a/crates/horizon-client/src/game/lan_screen.rs +++ b/crates/horizon-client/src/game/lan_screen.rs @@ -7,6 +7,7 @@ use super::{ Game, Screen, game_rules_screen::{Exit, RulesScreen}, + integrated::ServerOptions, lan::LanSettings, }; use horizon_client::{ @@ -50,7 +51,7 @@ enum View { Restrictions, GameRules, } -#[derive(Clone, PartialEq)] +#[derive(Clone, Copy, PartialEq)] struct Snapshot { default_mode: i32, personal_mode: i32, @@ -406,28 +407,32 @@ impl Restrictions { impl Game<'_> { pub(super) fn open_world_options(&mut self) { let hint = horizon_client::lan::available_port(); - let lan = self.lan.is_some(); let mut port = EditBox::new(0.0, 0.0, 150.0, 20.0); port.max_length = 5; - let (guest_commands, force) = self.lan.as_ref().map_or((false, true), |h| { - (h.settings.guest_commands, h.settings.force_game_mode) - }); - if let Some(p) = self.lan_port() { + // The world is the server thread's when there is one. + let state = match &self.integrated { + Some(server) => match server.call(|g| g.server_options()) { + Some(state) => state, + None => return, + }, + None => self.local_server_options(), + }; + if let Some(p) = state.port { port.set_value(&p.to_string()); } let mut options = WorldOptions { - default_mode: self.level.mode(), - personal_mode: self.mode_id(), - cheats: self.allow_commands(), - difficulty: self.ui.difficulty, - lan, + default_mode: state.default_mode, + personal_mode: state.personal_mode, + cheats: state.cheats, + difficulty: state.difficulty, + lan: state.port.is_some(), port, hint, - guest_commands, - force, - hardcore: self.level.hardcore, - difficulty_locked: self.level.difficulty_locked, - locked: self.level.difficulty_locked || self.level.hardcore, + guest_commands: state.guest_commands, + force: state.force, + hardcore: state.hardcore, + difficulty_locked: state.difficulty_locked, + locked: state.difficulty_locked || state.hardcore, scroll: 0.0, view: View::Options, rules: None, @@ -808,7 +813,7 @@ impl Game<'_> { fn apply_and_close_world_options(&mut self, o: WorldOptions) { let wanted = o.snapshot(); - let before = o.initial.clone(); + let before = o.initial; self.world_options = Some(o); self.apply_world_options(&before, &wanted); self.close_world_options(); @@ -891,7 +896,47 @@ impl Game<'_> { } } + /// The world options of a world run in the frame. + fn local_server_options(&self) -> ServerOptions { + let (guest_commands, force) = self.lan.as_ref().map_or((false, true), |h| { + (h.settings.guest_commands, h.settings.force_game_mode) + }); + ServerOptions { + default_mode: self.level.mode(), + personal_mode: self.mode_id(), + cheats: self.allow_commands(), + difficulty: self.ui.difficulty, + hardcore: self.level.hardcore, + difficulty_locked: self.level.difficulty_locked, + port: self.lan_port(), + guest_commands, + force, + } + } + fn apply_world_options(&mut self, before: &Snapshot, wanted: &Snapshot) { + if let Some(server) = &self.integrated { + // The server applies them; the window tells what came of + // Open to LAN (ShareToLanScreen's messages). + let (b, w) = (*before, *wanted); + server.call(move |g| g.apply_world_options(&b, &w)); + if w.lan != b.lan || (w.lan && w.port != b.port) { + match (w.lan, self.lan_port()) { + (true, Some(port)) => self.system_message(Text::translate( + "menu.multiplayerOptions.publish.started.lan", + &[Text::literal(port.to_string())], + )), + (true, None) => { + self.system_message(Text::translate("commands.publish.failed", &[])); + } + (false, _) => self.system_message(Text::translate( + "menu.multiplayerOptions.publish.stopped", + &[], + )), + } + } + return; + } if wanted.difficulty != before.difficulty { let name = DIFFICULTIES[usize::from(wanted.difficulty) & 3]; self.as_console(|g| g.run_command(&format!("difficulty {name}"))); @@ -904,10 +949,15 @@ impl Game<'_> { self.set_default_game_mode(wanted.default_mode); } if wanted.personal_mode != before.personal_mode { - self.set_mode_id(wanted.personal_mode); + if self.serving() { + self.set_owner_mode(wanted.personal_mode); + } else { + self.set_mode_id(wanted.personal_mode); + } } if wanted.cheats != before.cheats { self.set_allow_commands(wanted.cheats); + self.owner_allow_commands(wanted.cheats); } let settings_changed = wanted.guest_commands != before.guest_commands || wanted.force != before.force; diff --git a/crates/horizon-client/src/lan/conn.rs b/crates/horizon-client/src/lan/conn.rs index 0688db0c6..a1ffac4fa 100644 --- a/crates/horizon-client/src/lan/conn.rs +++ b/crates/horizon-client/src/lan/conn.rs @@ -361,8 +361,9 @@ fn login_and_configure( name: &str, ) -> Result, String> { let e = |e: horizon_protocol::Error| e.to_string(); + // ServerLoginPacketListenerImpl: memory connections are not compressed. let threshold = shared.config.compression_threshold; - if threshold >= 0 { + if threshold >= 0 && !c.is_memory() { c.send(&login::Clientbound::Compression(login::Compression { threshold }).encode()) .map_err(e)?; c.set_compression(threshold); diff --git a/crates/horizon-client/src/lan/hub.rs b/crates/horizon-client/src/lan/hub.rs index 3f1f88c4a..cb438508e 100644 --- a/crates/horizon-client/src/lan/hub.rs +++ b/crates/horizon-client/src/lan/hub.rs @@ -48,6 +48,10 @@ pub struct HubConfig { pub max_players: usize, /// A dedicated server: operators from `ops`, the dedicated-only commands. pub dedicated: bool, + /// An integrated server (`dedicated` too, since it has no host player): + /// the owner's level from `ops`, the others' from Allow Commands and + /// the guests' command access, and the integrated-only commands. + pub integrated: bool, } /// The host player as the other players see them. @@ -445,7 +449,11 @@ impl Hub { /// (IntegratedServer.setGuestCommandAccess); a dedicated server its /// operators' level (`ops`). fn default_permission(&self, uuid: u128) -> u8 { - if self.config.dedicated { + if self.config.integrated { + // IntegratedServer.getProfilePermissions / getCustomPermissionLevel. + let guests = if self.config.guest_commands { 2 } else { 0 }; + self.ops.get(&uuid).copied().unwrap_or(guests) + } else if self.config.dedicated { self.ops.get(&uuid).copied().unwrap_or(0) } else if self.config.guest_commands { 2 @@ -682,7 +690,10 @@ impl Hub { fn send_commands(&self, i: usize) { let g = &self.guests[i]; let packet = match &self.sync.commands { - Some(tree) => tree.packet(g.permission, self.config.dedicated, &self.sync.builtin), + Some(tree) => { + let dedicated = self.config.dedicated && !self.config.integrated; + tree.packet(g.permission, dedicated, &self.sync.builtin) + } None => play::Commands { nodes: vec![play::CommandNode { kind: 0, diff --git a/crates/horizon-client/src/lan/mod.rs b/crates/horizon-client/src/lan/mod.rs index f4211c6ea..7084f20a6 100644 --- a/crates/horizon-client/src/lan/mod.rs +++ b/crates/horizon-client/src/lan/mod.rs @@ -310,6 +310,8 @@ pub struct Lan { events: Receiver, pub port: u16, listener: Option>, + /// Stops the accept loop alone: local connections stay. + listener_stop: Arc, /// The multicast announcement (LanServerPinger); absent when the socket failed. _pinger: Option, } @@ -325,26 +327,8 @@ impl Lan { } /// ServerConnectionListener.startTcpServerListener with a configuration. pub fn start_with(sync: Arc, config: NetConfig) -> io::Result { - let listener = if config.listen { - let bind = config - .bind - .unwrap_or(std::net::IpAddr::V4(std::net::Ipv4Addr::UNSPECIFIED)); - let listener = TcpListener::bind((bind, config.port))?; - listener.set_nonblocking(true)?; - Some(listener) - } else { - None - }; - let port = match &listener { - Some(l) => l.local_addr()?.port(), - None => 0, - }; - let _pinger = if config.announce && listener.is_some() { - discovery::Pinger::start(config.motd.clone(), port).ok() - } else { - None - }; let (tx, events) = channel(); + let (listen, port, announce) = (config.listen, config.port, config.announce); let shared = Arc::new(Shared { sync, events: tx, @@ -357,21 +341,77 @@ impl Lan { random: Mutex::new(crate::server::java_properties::now_millis() as u64 | 1), config, }); - let accept_shared = shared.clone(); - let listener = listener - .map(|listener| { - std::thread::Builder::new() - .name("horizon-lan-accept".into()) - .spawn(move || accept_loop(listener, accept_shared)) - }) - .transpose()?; - Ok(Self { + let mut lan = Self { shared, events, - port, - listener, - _pinger, - }) + port: 0, + listener: None, + listener_stop: Arc::new(AtomicBool::new(false)), + _pinger: None, + }; + if listen { + lan.listen(port, announce)?; + } + Ok(lan) + } + /// Start accepting connections on `port` (0 picks a free one), and + /// announce the world on the local network when `announce` + /// (`IntegratedServer.publishServer`'s LanServerPinger). Returns the port. + pub fn listen(&mut self, port: u16, announce: bool) -> io::Result { + if self.listener.is_some() { + return Err(io::Error::new( + io::ErrorKind::AlreadyExists, + "already listening", + )); + } + let listener = Self::bind(self.shared.config.bind, port)?; + self.listen_on(listener, announce) + } + /// The socket [`Lan::listen`] accepts on, bound ahead so that a failure + /// can be reported before the hub is at hand. + pub fn bind(address: Option, port: u16) -> io::Result { + let bind = address.unwrap_or(std::net::IpAddr::V4(std::net::Ipv4Addr::UNSPECIFIED)); + let listener = TcpListener::bind((bind, port))?; + listener.set_nonblocking(true)?; + Ok(listener) + } + /// [`Lan::listen`] on a socket already bound. + pub fn listen_on(&mut self, listener: TcpListener, announce: bool) -> io::Result { + if self.listener.is_some() { + return Err(io::Error::new( + io::ErrorKind::AlreadyExists, + "already listening", + )); + } + let port = listener.local_addr()?.port(); + let stop = Arc::new(AtomicBool::new(false)); + let (accept_shared, accept_stop) = (self.shared.clone(), stop.clone()); + let thread = std::thread::Builder::new() + .name("horizon-lan-accept".into()) + .spawn(move || accept_loop(listener, accept_shared, &accept_stop))?; + self._pinger = if announce { + discovery::Pinger::start(self.shared.motd(), port).ok() + } else { + None + }; + self.listener = Some(thread); + self.listener_stop = stop; + self.port = port; + Ok(port) + } + /// Stop accepting connections and announcing; connections already in + /// (the local one included) stay. + pub fn stop_listening(&mut self) { + self.listener_stop.store(true, Ordering::Relaxed); + if let Some(t) = self.listener.take() { + let _ = t.join(); + } + self._pinger = None; + self.port = 0; + } + /// Whether connections from the network are accepted. + pub fn listening(&self) -> bool { + self.listener.is_some() } /// `Connection.connectToLocalServer`: a connection through memory, its /// server end served on its own thread like an accepted socket. @@ -402,10 +442,7 @@ impl Lan { } pub fn stop(&mut self) { self.shared.stop.store(true, Ordering::Relaxed); - if let Some(t) = self.listener.take() { - let _ = t.join(); - } - self._pinger = None; + self.stop_listening(); } } impl Drop for Lan { @@ -414,8 +451,8 @@ impl Drop for Lan { } } -fn accept_loop(listener: TcpListener, shared: Arc) { - while !shared.stop.load(Ordering::Relaxed) { +fn accept_loop(listener: TcpListener, shared: Arc, stop: &AtomicBool) { + while !shared.stop.load(Ordering::Relaxed) && !stop.load(Ordering::Relaxed) { match listener.accept() { Ok((stream, addr)) => { let shared = shared.clone(); diff --git a/crates/horizon-client/tests/lan_bot.rs b/crates/horizon-client/tests/lan_bot.rs index 7a4a4a3c4..36f53444c 100644 --- a/crates/horizon-client/tests/lan_bot.rs +++ b/crates/horizon-client/tests/lan_bot.rs @@ -241,6 +241,7 @@ fn server(resources: &Path) -> Server { view_distance: 3, simulation_distance: 3, dedicated: false, + integrated: false, dimension: "minecraft:overworld".into(), seed: 1234, max_players: 8, diff --git a/crates/horizon-protocol/src/connection.rs b/crates/horizon-protocol/src/connection.rs index 3c6087f2e..687839416 100644 --- a/crates/horizon-protocol/src/connection.rs +++ b/crates/horizon-protocol/src/connection.rs @@ -227,6 +227,10 @@ impl Connection { }, }) } + /// `Connection.isMemoryConnection`: through a [`Pipe`] rather than a socket. + pub fn is_memory(&self) -> bool { + matches!(self.reader.stream, Stream::Memory(_)) + } /// ClientboundLoginCompressionPacket: negative thresholds disable compression. pub fn set_compression(&mut self, threshold: i32) { let t = usize::try_from(threshold).ok();