From 613a0dd3f18b5e1a7f55b887c8e1628cede68188 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 12 Oct 2026 17:46:50 +0200 Subject: [PATCH] WIP: unfinished dedicated-server parity work, stopped by Ludovic Uncommitted changes the agent had in progress when it was stopped on 2026-10-12; may not build or pass its harnesses yet. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/audio.rs | 18 +- crates/horizon-client/src/game.rs | 30 +- crates/horizon-client/src/game/dedicated.rs | 987 ++++++++++++++++++++ crates/horizon-client/src/game/lan.rs | 87 +- crates/horizon-client/src/lan/conn.rs | 113 ++- crates/horizon-client/src/lan/guest.rs | 3 + crates/horizon-client/src/lan/hub.rs | 18 +- crates/horizon-client/src/lan/mod.rs | 236 ++++- 8 files changed, 1399 insertions(+), 93 deletions(-) create mode 100644 crates/horizon-client/src/game/dedicated.rs diff --git a/crates/horizon-client/src/audio.rs b/crates/horizon-client/src/audio.rs index 5853a4d7f..51d8343c2 100644 --- a/crates/horizon-client/src/audio.rs +++ b/crates/horizon-client/src/audio.rs @@ -329,12 +329,26 @@ fn mix(mixer: &mut Mixer, data: &mut [f32], channels: usize, rate: u32) { } impl Audio { pub fn new(root: &Path) -> Self { + Self::with_output(root, true) + } + /// No output device: the dedicated server. + pub fn silent(root: &Path) -> Self { + Self::with_output(root, false) + } + fn with_output(root: &Path, output: bool) -> Self { let registry = SoundRegistry::load(root); let mixer = Arc::new(Mutex::new(Mixer::default())); - let (stream, live) = match Self::open(mixer.clone()) { + let opened = if output { + Self::open(mixer.clone()) + } else { + Err("no output on a dedicated server".into()) + }; + let (stream, live) = match opened { Ok(v) => (Some(v), true), Err(e) => { - eprintln!("Horizon: audio unavailable: {e}"); + if output { + eprintln!("Horizon: audio unavailable: {e}"); + } (None, false) } }; diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 642ddb08f..465282dfe 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -20,6 +20,7 @@ mod commands; mod control; mod creaking; mod creatures; +mod dedicated; mod crossbow; mod dispense_fixture; mod dispenser; @@ -181,6 +182,9 @@ struct Options { /// Multiplayer: `--server HOST[:PORT]` joins at start; `--name` is the offline player name. server: Option, player_name: String, + /// `--dedicated`: run as a dedicated server; vanilla's server arguments + /// (`--nogui`, `--port`, `--world`, `--universe`, `--initSettings`) follow. + dedicated: Option>, } impl Options { fn read() -> Result> { @@ -212,6 +216,7 @@ impl Options { control: None, server: None, player_name: std::env::var("HORIZON_PLAYER_NAME").unwrap_or_else(|_| "Player".into()), + dedicated: None, }; let mut args = std::env::args().skip(1); while let Some(arg) = args.next() { @@ -222,6 +227,10 @@ impl Options { ); return Ok(None); } + "--dedicated" => { + o.dedicated = Some(args.by_ref().collect()); + break; + } "--creative" => o.creative = true, "--test-terrain" => o.test_terrain = true, "--no-pause" => o.no_pause = true, @@ -2542,6 +2551,10 @@ impl Game<'_> { } let riding = self.riding.is_some(); let Some(player) = self.player.as_mut() else { + // A dedicated server has no local player: the world still runs. + if self.options.dedicated.is_some() { + return self.tick_world(running); + } return Ok(()); }; // Hold position until the surrounding terrain exists. @@ -2729,6 +2742,11 @@ impl Game<'_> { self.screen = Screen::Dead; self.capture(false); } + self.tick_world(running) + } + /// What the tick runs after the local player's own update: effects, the + /// world's entities and blocks, and the network hub. + fn tick_world(&mut self, running: bool) -> Result<()> { self.tick_omens(); self.tick_effects(); self.tick_burning(); @@ -7833,6 +7851,9 @@ pub fn run() -> Result<()> { let Some(mut options) = Options::read()? else { return Ok(()); }; + if options.dedicated.is_some() && !dedicated::preflight(&mut options)? { + return Ok(()); + } let started = Instant::now(); let vanilla_root = options.resources.clone(); let early_settings = Settings::load(&std::env::current_dir()?.join("options.txt")); @@ -7907,7 +7928,11 @@ pub fn run() -> Result<()> { .join("saves") .join(".horizon-title"), )); - let audio = Audio::new(&root); + let audio = if options.dedicated.is_some() { + Audio::silent(&root) + } else { + Audio::new(&root) + }; let world = World::new(facts.air, 0); let creative = options.creative; let stations = horizon_client::stations::StationData::load(&root, &items); @@ -8184,6 +8209,9 @@ pub fn run() -> Result<()> { if let Ok(spec) = std::env::var("HORIZON_DISPENSE_FIXTURE") { return game.dispense_fixture(&spec); } + if game.options.dedicated.is_some() { + return game.run_dedicated(); + } match game.options.world.clone() { _ if game.options.server.is_some() => { let (address, name) = ( diff --git a/crates/horizon-client/src/game/dedicated.rs b/crates/horizon-client/src/game/dedicated.rs new file mode 100644 index 000000000..498fa0e8a --- /dev/null +++ b/crates/horizon-client/src/game/dedicated.rs @@ -0,0 +1,987 @@ +//! The dedicated server (net.minecraft.server.Main and DedicatedServer): +//! `horizon-client --dedicated [--nogui] [--port N] [--world NAME] +//! [--universe DIR] [--initSettings]`. It reads server.properties and +//! eula.txt from the working directory, opens `/` and +//! runs the same game as single player, without a local player: the world, +//! its simulation and the play-state hub that LAN hosting uses, configured +//! from server.properties, with the operator, whitelist and ban lists and a +//! console on standard input. +use super::{Game, Options, lan::LanSettings}; +use horizon_client::{ + Result, + lan::{LoginGate, NetConfig, hub::HubConfig}, + server::{ + eula, + java_properties::now_millis, + properties::{GAME_MODES, ServerProperties, SystemEntropy}, + user_lists::{ + BanEntry, BanList, IpBanList, NameAndId, OpEntry, OpList, WhiteEntry, WhiteList, + format_date, + }, + }, + text::Text, +}; +use horizon_protocol::text::translatable; +use horizon_world::nbt::{JavaString, Tag}; +use std::{ + path::PathBuf, + sync::{Arc, Mutex, OnceLock, mpsc}, + time::{Duration, Instant}, +}; + +/// What the startup read before the game's resources were loaded. +struct Setup { + props: ServerProperties, + universe: PathBuf, + level_name: String, + port: Option, + started: Instant, +} +static SETUP: OnceLock>> = OnceLock::new(); + +/// Log4j's console pattern: `[HH:mm:ss] [thread/LEVEL]: message`. +pub(super) fn log(level: &str, message: &str) { + let secs = now_millis().div_euclid(1000).rem_euclid(86_400); + println!( + "[{:02}:{:02}:{:02}] [Server thread/{level}]: {message}", + secs / 3600, + secs / 60 % 60, + secs % 60 + ); +} + +/// Main.main up to the server start: arguments, server.properties (stored +/// back at once), eula.txt. False when the process should stop here. +pub(super) fn preflight(options: &mut Options) -> Result { + let args = options.dedicated.clone().unwrap_or_default(); + let mut universe = PathBuf::from("."); + let mut world = None; + let mut port = None; + let mut init_settings = false; + let mut it = args.iter(); + while let Some(arg) = it.next() { + let name = arg.trim_start_matches('-'); + match name { + "nogui" | "demo" | "bonusChest" | "forceUpgrade" | "eraseCache" + | "recreateRegionFiles" | "safeMode" | "jfrProfile" => {} + "initSettings" => init_settings = true, + "help" => { + eprintln!( + "Option Description\n------ -----------\n--help\n--initSettings Initializes 'server.properties' and 'eula.txt', then quits\n--nogui\n--port (default: -1)\n--universe (default: .)\n--world " + ); + return Ok(false); + } + "universe" => universe = PathBuf::from(it.next().ok_or("--universe needs a value")?), + "world" => world = Some(it.next().ok_or("--world needs a value")?.clone()), + "port" => { + let v: i32 = it.next().ok_or("--port needs a value")?.parse()?; + port = u16::try_from(v).ok(); + } + "serverId" | "pidFile" => { + let value = it.next().ok_or("missing value")?; + if name == "pidFile" { + std::fs::write(value, std::process::id().to_string())?; + } + } + _ => return Err(format!("{arg} is not a recognized option").into()), + } + } + let started = Instant::now(); + let settings = PathBuf::from("server.properties"); + let props = ServerProperties::from_file(&settings, &mut SystemEntropy::default())?; + for w in &props.warnings { + log("WARN", w); + } + props.store(&settings)?; + let eula_file = PathBuf::from("eula.txt"); + let agreed = match eula::agreed(&eula_file) { + Ok(a) => a, + Err(w) => { + log("WARN", &w); + false + } + }; + if init_settings { + let abs = |p: &PathBuf| std::env::current_dir().map_or(p.clone(), |d| d.join(p)); + log( + "INFO", + &format!( + "Initialized '{}' and '{}'", + abs(&settings).display(), + abs(&eula_file).display() + ), + ); + return Ok(false); + } + if !agreed { + log( + "INFO", + "You need to agree to the EULA in order to run the server. Go to eula.txt for more info.", + ); + return Ok(false); + } + let level_name = world.unwrap_or_else(|| props.level_name.clone()); + SETUP + .get_or_init(|| Mutex::new(None)) + .lock() + .unwrap() + .replace(Setup { + props, + universe, + level_name, + port, + started, + }); + Ok(true) +} + +/// The operator, whitelist and ban lists (DedicatedPlayerList), shared with +/// the connection threads that check logins. +pub(super) struct Lists { + pub ops: OpList, + pub white: WhiteList, + pub bans: BanList, + pub ip_bans: IpBanList, + pub use_whitelist: bool, + pub enforce_whitelist: bool, +} +impl Lists { + fn load() -> Self { + let mut l = Self { + ops: OpList::new("ops.json"), + white: WhiteList::new("whitelist.json"), + bans: BanList::new("banned-players.json"), + ip_bans: IpBanList::new("banned-ips.json"), + use_whitelist: false, + enforce_whitelist: false, + }; + let warn = |what: &str, r: std::result::Result<(), String>| { + if let Err(e) = r { + log("WARN", &format!("Failed to load {what}: {e}")); + } + }; + // DedicatedPlayerList's constructor order. + warn("user banlist", l.bans.load()); + let _ = l.bans.save(); + warn("ip banlist", l.ip_bans.load()); + let _ = l.ip_bans.save(); + warn("operators list", l.ops.load()); + warn("white-list", l.white.load()); + let _ = l.ops.save(); + if !l.white.file.exists() { + let _ = l.white.save(); + } + l + } + /// PlayerList.isWhiteListed. + fn whitelisted(&self, user: &NameAndId) -> bool { + !self.use_whitelist || self.ops.contains(user) || self.white.contains(user) + } + /// PlayerList.canPlayerLogin before the player count. + fn can_login(&mut self, address: std::net::SocketAddr, user: &NameAndId) -> Option { + if self.bans.contains(user) + && let Some(ban) = self.bans.get(user).cloned() + { + let mut reason = translatable_tag( + "multiplayer.disconnect.banned.reason", + vec![ban_reason(&ban.reason)], + ); + if let Some(expires) = ban.expires { + append( + &mut reason, + translatable_tag( + "multiplayer.disconnect.banned.expiration", + vec![Tag::String(JavaString::from(ban_date(expires).as_str()))], + ), + ); + } + return Some(reason); + } + if !self.whitelisted(user) { + return Some(translatable("multiplayer.disconnect.not_whitelisted", &[])); + } + let ip = address.ip().to_string(); + if self.ip_bans.contains(&ip) + && let Some(ban) = self.ip_bans.get(&ip).cloned() + { + let mut reason = translatable_tag( + "multiplayer.disconnect.banned_ip.reason", + vec![ban_reason(&ban.reason)], + ); + if let Some(expires) = ban.expires { + append( + &mut reason, + translatable_tag( + "multiplayer.disconnect.banned_ip.expiration", + vec![Tag::String(JavaString::from(ban_date(expires).as_str()))], + ), + ); + } + return Some(reason); + } + None + } +} + +/// PlayerList.BAN_DATE_FORMAT ("yyyy-MM-dd 'at' HH:mm:ss z"), in UTC. +fn ban_date(millis: i64) -> String { + let s = format_date(millis); + format!("{} at {} UTC", &s[..10], &s[11..19]) +} +/// BanListEntry.getReasonMessage. +fn ban_reason(reason: &Option) -> Tag { + match reason { + Some(r) => Tag::String(JavaString::from(r.as_str())), + None => translatable("multiplayer.disconnect.banned.reason.default", &[]), + } +} +fn translatable_tag(key: &str, args: Vec) -> Tag { + Tag::compound([ + ("translate", Tag::String(JavaString::from(key))), + ("with", Tag::List(args)), + ]) +} +/// MutableComponent.append. +fn append(to: &mut Tag, sibling: Tag) { + if let Tag::Compound(map) = to { + let extra = map + .entry(JavaString::from("extra")) + .or_insert_with(|| Tag::List(Vec::new())); + if let Tag::List(items) = extra { + items.push(sibling); + } + } +} + +/// What the server loop keeps between ticks. +struct ServerState { + lists: Arc>, + console: mpsc::Receiver, + stop: bool, + autosave: bool, + empty_ticks: i32, +} + +impl Game<'_> { + /// DedicatedServer.initServer and MinecraftServer.runServer. + pub(super) fn run_dedicated(&mut self) -> Result<()> { + let Setup { + props, + universe, + level_name, + port, + started, + } = SETUP + .get() + .and_then(|m| m.lock().unwrap().take()) + .ok_or("dedicated server not prepared")?; + // The console thread starts first, as in initServer. + let (tx, console) = mpsc::channel(); + std::thread::Builder::new() + .name("Server console handler".into()) + .spawn(move || { + let stdin = std::io::stdin(); + let mut line = String::new(); + while stdin.read_line(&mut line).is_ok_and(|n| n > 0) { + if tx.send(line.trim_end_matches(['\r', '\n']).to_owned()).is_err() { + break; + } + line.clear(); + } + })?; + log("INFO", "Starting minecraft server version 26.3"); + log("INFO", "Loading properties"); + let game_mode = props.game_mode; + log( + "INFO", + &format!( + "Default game type: {}", + GAME_MODES[game_mode as usize].to_uppercase() + ), + ); + let port = port.unwrap_or(props.server_port as u16); + log( + "INFO", + &format!( + "Starting Minecraft server on {}:{port}", + if props.server_ip.is_empty() { + "*" + } else { + &props.server_ip + } + ), + ); + if props.online_mode { + // Authentication needs Mojang's session servers (an HTTPS client + // and RSA), which Horizon does not have yet: offline mode. + log( + "WARN", + "online-mode=true is not supported by Horizon yet: running in offline mode", + ); + } + log("WARN", "**** SERVER IS RUNNING IN OFFLINE/INSECURE MODE!"); + log( + "WARN", + "The server will make no attempt to authenticate usernames. Beware.", + ); + log( + "WARN", + "While this makes the game possible to play without internet access, it also opens up the ability for hackers to connect with any username they choose.", + ); + log( + "WARN", + "To change this, set \"online-mode\" to \"true\" in the server.properties file.", + ); + let mut lists = Lists::load(); + lists.use_whitelist = props.white_list; + lists.enforce_whitelist = props.enforce_whitelist; + let lists = Arc::new(Mutex::new(lists)); + log("INFO", &format!("Preparing level \"{level_name}\"")); + let world_dir = std::env::current_dir()?.join(&universe).join(&level_name); + let folder = world_dir.to_string_lossy().into_owned(); + let new_world = !world_dir.join("level.dat").exists(); + self.open_world(&folder, Some(&level_name), Some(props.seed), game_mode == 1)?; + if new_world { + self.level.hardcore = props.hardcore; + } + // The single-player host's state is not used: players have their own files. + self.level.position = None; + // DedicatedServer.initServer: worldData.setGameType; forceDifficulty. + self.set_default_game_mode(game_mode); + self.ui.difficulty = props.difficulty as u8; + self.settings.render_distance = props.view_distance.clamp(2, 32); + self.streaming.radius = 0; + self.settle_spawn()?; + let gate_lists = lists.clone(); + let gate: LoginGate = Arc::new(move |address, uuid, name| { + let user = NameAndId { + id: uuid, + name: name.to_owned(), + }; + gate_lists.lock().unwrap().can_login(address, &user) + }); + let bypass_lists = lists.clone(); + let favicon = std::fs::read("server-icon.png") + .ok() + .filter(|b| png_size(b) == Some((64, 64))); + let net = NetConfig { + bind: (!props.server_ip.is_empty()) + .then(|| props.server_ip.parse().ok()) + .flatten(), + port, + motd: props.motd.clone(), + max_players: props.max_players.max(0) as usize, + compression_threshold: props.network_compression_threshold, + enable_status: props.enable_status, + hide_online_players: props.hide_online_players, + favicon, + // DedicatedServer.enforceSecureProfile needs online mode. + enforces_secure_chat: false, + accepts_transfers: props.accepts_transfers, + announce: false, + bypasses_limit: Some(Arc::new(move |uuid| { + bypass_lists + .lock() + .unwrap() + .ops + .entries() + .iter() + .any(|e| e.user.id == uuid && e.bypasses_player_limit) + })), + gate: Some(gate), + }; + let config = HubConfig { + default_game_mode: game_mode, + guest_commands: true, + force_game_mode: props.force_game_mode, + hardcore: self.level.hardcore, + view_distance: props.view_distance.clamp(2, 32), + simulation_distance: props.simulation_distance.clamp(2, 32), + dimension: self.dim.id().to_owned(), + seed: self.level.seed, + max_players: props.max_players.max(0) as usize, + dedicated: true, + }; + let settings = LanSettings { + port, + guest_commands: true, + force_game_mode: props.force_game_mode, + }; + if let Err(e) = self.lan_host(settings, net, config, None) { + log("WARN", "**** FAILED TO BIND TO PORT!"); + log("WARN", &format!("The exception was: {e}")); + log("WARN", "Perhaps a server is already running on that port?"); + return Ok(()); + } + self.sync_ops(&lists); + log( + "INFO", + &format!( + "Done ({:.3}s)! For help, type \"help\"", + started.elapsed().as_secs_f64() + ), + ); + let mut state = ServerState { + lists, + console, + stop: false, + autosave: true, + empty_ticks: 0, + }; + let pause_after = props.pause_when_empty_seconds * 20; + let idle_timeout = props.player_idle_timeout; + let mut next = Instant::now(); + while !state.stop { + while let Ok(line) = state.console.try_recv() { + self.console_command(&mut state, &line); + } + let players = self.lan.as_ref().map_or(0, |h| h.hub.guests.len()); + if pause_after > 0 { + if players == 0 { + state.empty_ticks += 1; + } else { + state.empty_ticks = 0; + } + } + let paused = pause_after > 0 && state.empty_ticks >= pause_after; + if paused && state.empty_ticks == pause_after { + log( + "INFO", + &format!( + "Server empty for {} seconds, pausing", + props.pause_when_empty_seconds + ), + ); + self.save_game()?; + } + self.update_dedicated_streaming(); + self.update_world(); + if paused { + // MinecraftServer.tickServer: only the connections run. + self.tick_lan(); + } else { + if !state.autosave { + // `save-off`: the periodic save inside the tick is skipped. + self.ticks = self.ticks.max(1); + } + self.tick()?; + } + if idle_timeout > 0 { + self.kick_idle(idle_timeout); + } + let rate = self.clock.rate().max(1.0); + next += Duration::from_secs_f64(1.0 / f64::from(rate)); + let now = Instant::now(); + if next > now { + std::thread::sleep(next - now); + } else if now - next > Duration::from_secs(2) { + next = now; + } + } + self.stop_dedicated() + } + + /// Load the spawn area and find the world spawn as single player does, + /// without keeping a player there. + fn settle_spawn(&mut self) -> Result<()> { + let deadline = Instant::now() + Duration::from_secs(600); + while self.player.is_none() { + self.update_world(); + self.spawn_player()?; + if Instant::now() > deadline { + return Err("the spawn area did not load".into()); + } + std::thread::sleep(Duration::from_millis(2)); + } + self.player = None; + Ok(()) + } + + /// The chunks to keep loaded: the players' (lan_update_streaming), or + /// the spawn chunk while nobody is online. + fn update_dedicated_streaming(&mut self) { + let center = self + .lan + .as_ref() + .and_then(|h| h.hub.guests.iter().find(|g| g.placed).map(|g| g.chunk())) + .or_else(|| { + self.spawn + .map(|s| ((s.x.floor() as i32) >> 4, (s.z.floor() as i32) >> 4)) + }); + if let Some(c) = center { + self.streaming.center = c; + } + } + + /// ServerGamePacketListenerImpl.tick: players idle longer than the + /// timeout are kicked. + fn kick_idle(&mut self, minutes: i32) { + let Some(host) = self.lan.as_mut() else { + return; + }; + let limit = u64::try_from(minutes).unwrap_or(0) * 1200; + let idle: Vec = host + .hub + .guests + .iter() + .filter(|g| host.hub.ticks.saturating_sub(g.last_action_tick) > limit) + .map(|g| g.conn) + .collect(); + for conn in idle { + host.hub + .kick(conn, translatable("multiplayer.disconnect.idling", &[])); + } + } + + /// Ops' permission levels for the hub (PlayerList.getProfilePermissions). + fn sync_ops(&mut self, lists: &Arc>) { + let Some(host) = self.lan.as_mut() else { + return; + }; + host.hub.ops = lists + .lock() + .unwrap() + .ops + .entries() + .iter() + .map(|e| (e.user.id, e.level as u8)) + .collect(); + host.hub.resend_commands(); + } + + /// A known player by name: online first, else the offline profile. + fn resolve(&self, name: &str) -> NameAndId { + self.lan + .as_ref() + .and_then(|h| { + h.hub + .guests + .iter() + .find(|g| g.name.eq_ignore_ascii_case(name)) + }) + .map_or_else( + || NameAndId::offline(name), + |g| NameAndId { + id: g.uuid, + name: g.name.clone(), + }, + ) + } + + fn console_reply(&self, text: Text) { + log("INFO", &text.plain()); + } + + /// DedicatedServer.handleConsoleInputs: one console line, run as the + /// server (permission level 4). The dedicated-only commands are here; + /// everything else goes to the game's dispatcher. + fn console_command(&mut self, state: &mut ServerState, line: &str) { + let line = line.strip_prefix('/').unwrap_or(line); + let mut words = line.split_whitespace(); + let Some(command) = words.next() else { + return; + }; + let rest: Vec<&str> = words.collect(); + let lit = |s: &str| Text::literal(s.to_owned()); + match command { + "stop" => { + self.console_reply(Text::translate("commands.stop.stopping", &[])); + state.stop = true; + } + "save-all" => { + self.console_reply(Text::translate("commands.save.saving", &[])); + match self.save_game() { + Ok(()) => self.console_reply(Text::translate("commands.save.success", &[])), + Err(e) => log("ERROR", &format!("{e}")), + } + } + "save-off" => { + if state.autosave { + state.autosave = false; + self.console_reply(Text::translate("commands.save.disabled", &[])); + } else { + self.console_reply(Text::translate("commands.save.alreadyOff", &[])); + } + } + "save-on" => { + if state.autosave { + self.console_reply(Text::translate("commands.save.alreadyOn", &[])); + } else { + state.autosave = true; + self.console_reply(Text::translate("commands.save.enabled", &[])); + } + } + "list" => { + let guests: Vec<(String, u128)> = self + .lan + .as_ref() + .map(|h| h.hub.guests.iter().map(|g| (g.name.clone(), g.uuid)).collect()) + .unwrap_or_default(); + let max = self.lan.as_ref().map_or(0, |h| h.hub.lan.shared.max_players()); + let names: Vec = if rest.first() == Some(&"uuids") { + guests + .iter() + .map(|(n, u)| format!("{n} ({})", horizon_protocol::crypto::uuid_string(*u))) + .collect() + } else { + guests.iter().map(|(n, _)| n.clone()).collect() + }; + self.console_reply(Text::translate( + "commands.list.players", + &[ + lit(&guests.len().to_string()), + lit(&max.to_string()), + lit(&names.join(", ")), + ], + )); + } + "op" | "deop" if !rest.is_empty() => { + let user = self.resolve(rest[0]); + let level = 4; + let changed = { + let mut l = state.lists.lock().unwrap(); + if command == "op" { + if l.ops.contains(&user) { + false + } else { + l.ops.add(OpEntry { + user: user.clone(), + level, + bypasses_player_limit: false, + }) + } + } else { + l.ops.remove(&user) + } + }; + let key = match (command, changed) { + ("op", true) => "commands.op.success", + ("op", false) => "commands.op.failed", + (_, true) => "commands.deop.success", + _ => "commands.deop.failed", + }; + self.console_reply(Text::translate(key, &[lit(&user.name)])); + let lists = state.lists.clone(); + self.sync_ops(&lists); + } + "whitelist" => self.console_whitelist(state, &rest), + "ban" if !rest.is_empty() => { + let user = self.resolve(rest[0]); + let reason = (rest.len() > 1).then(|| rest[1..].join(" ")); + let added = state.lists.lock().unwrap().bans.add(BanEntry::new( + user.clone(), + Some("Server".into()), + None, + reason.clone(), + )); + if added { + self.console_reply(Text::translate( + "commands.ban.success", + &[ + lit(&user.name), + reason.as_deref().map_or_else( + || Text::translate("multiplayer.disconnect.banned.reason.default", &[]), + lit, + ), + ], + )); + self.kick_uuid(user.id, translatable("multiplayer.disconnect.banned", &[])); + } else { + self.console_reply(Text::translate("commands.ban.failed", &[])); + } + } + "ban-ip" if !rest.is_empty() => { + let target = rest[0]; + let ip = if target.parse::().is_ok() { + Some(target.to_owned()) + } else { + self.lan.as_ref().and_then(|h| { + h.hub + .guests + .iter() + .find(|g| g.name.eq_ignore_ascii_case(target)) + .map(|g| g.address.ip().to_string()) + }) + }; + let Some(ip) = ip else { + self.console_reply(Text::translate("commands.banip.invalid", &[])); + return; + }; + let reason = (rest.len() > 1).then(|| rest[1..].join(" ")); + let added = state.lists.lock().unwrap().ip_bans.add(BanEntry::new( + ip.clone(), + Some("Server".into()), + None, + reason.clone(), + )); + if !added { + self.console_reply(Text::translate("commands.banip.failed", &[])); + return; + } + self.console_reply(Text::translate( + "commands.banip.success", + &[ + lit(&ip), + reason.as_deref().map_or_else( + || Text::translate("multiplayer.disconnect.banned.reason.default", &[]), + lit, + ), + ], + )); + let banned: Vec = self + .lan + .as_ref() + .map(|h| { + h.hub + .guests + .iter() + .filter(|g| g.address.ip().to_string() == ip) + .map(|g| g.uuid) + .collect() + }) + .unwrap_or_default(); + if !banned.is_empty() { + self.console_reply(Text::translate( + "commands.banip.info", + &[lit(&banned.len().to_string()), lit("")], + )); + } + for uuid in banned { + self.kick_uuid(uuid, translatable("multiplayer.disconnect.ip_banned", &[])); + } + } + "pardon" if !rest.is_empty() => { + let user = self.resolve(rest[0]); + let removed = state.lists.lock().unwrap().bans.remove(&user); + let key = if removed { + "commands.pardon.success" + } else { + "commands.pardon.failed" + }; + self.console_reply(Text::translate(key, &[lit(&user.name)])); + } + "pardon-ip" if !rest.is_empty() => { + let ip = rest[0].to_owned(); + if ip.parse::().is_err() { + self.console_reply(Text::translate("commands.pardonip.invalid", &[])); + return; + } + let removed = state.lists.lock().unwrap().ip_bans.remove(&ip); + let key = if removed { + "commands.pardonip.success" + } else { + "commands.pardonip.failed" + }; + self.console_reply(Text::translate(key, &[lit(&ip)])); + } + "banlist" => { + let l = state.lists.lock().unwrap(); + let mut lines = Vec::new(); + let which = rest.first().copied().unwrap_or(""); + if which != "ips" { + for b in l.bans.entries() { + lines.push((b.user.name.clone(), b.source.clone(), b.reason.clone())); + } + } + if which != "players" { + for b in l.ip_bans.entries() { + lines.push((b.user.clone(), b.source.clone(), b.reason.clone())); + } + } + drop(l); + if lines.is_empty() { + self.console_reply(Text::translate("commands.banlist.none", &[])); + } else { + self.console_reply(Text::translate( + "commands.banlist.list", + &[lit(&lines.len().to_string())], + )); + for (name, source, reason) in lines { + self.console_reply(Text::translate( + "commands.banlist.entry", + &[ + lit(&name), + lit(&source), + reason.as_deref().map_or_else( + || Text::translate("multiplayer.disconnect.banned.reason.default", &[]), + lit, + ), + ], + )); + } + } + } + "kick" if !rest.is_empty() => { + let user = self.resolve(rest[0]); + let online = self + .lan + .as_ref() + .is_some_and(|h| h.hub.guests.iter().any(|g| g.uuid == user.id)); + if !online { + self.console_reply(Text::translate("argument.entity.notfound.player", &[])); + return; + } + let reason = if rest.len() > 1 { + Tag::String(JavaString::from(rest[1..].join(" ").as_str())) + } else { + translatable("multiplayer.disconnect.kicked", &[]) + }; + self.kick_uuid(user.id, reason); + self.console_reply(Text::translate( + "commands.kick.success", + &[ + lit(&user.name), + if rest.len() > 1 { + lit(&rest[1..].join(" ")) + } else { + Text::translate("multiplayer.disconnect.kicked", &[]) + }, + ], + )); + } + "say" if !rest.is_empty() => { + let message = format!("[Server] {}", rest.join(" ")); + log("INFO", &message); + if let Some(h) = &self.lan { + h.hub.system_message(Tag::String(JavaString::from(message.as_str()))); + } + } + _ => { + // The game's dispatcher, captured for the console. + self.chat_capture = Some(Vec::new()); + self.run_command(line); + for text in self.chat_capture.take().unwrap_or_default() { + log("INFO", &text.plain()); + } + } + } + } + + fn console_whitelist(&mut self, state: &mut ServerState, rest: &[&str]) { + let lit = |s: &str| Text::literal(s.to_owned()); + match rest { + ["on"] | ["off"] => { + let on = rest[0] == "on"; + let mut l = state.lists.lock().unwrap(); + let key = match (on, l.use_whitelist) { + (true, true) => "commands.whitelist.alreadyOn", + (true, false) => "commands.whitelist.enabled", + (false, false) => "commands.whitelist.alreadyOff", + (false, true) => "commands.whitelist.disabled", + }; + l.use_whitelist = on; + drop(l); + self.store_property("white-list", on.to_string()); + self.console_reply(Text::translate(key, &[])); + } + ["list"] => { + let names: Vec = state + .lists + .lock() + .unwrap() + .white + .entries() + .iter() + .map(|e| e.user.name.clone()) + .collect(); + if names.is_empty() { + self.console_reply(Text::translate("commands.whitelist.none", &[])); + } else { + self.console_reply(Text::translate( + "commands.whitelist.list", + &[lit(&names.len().to_string()), lit(&names.join(", "))], + )); + } + } + ["reload"] => { + let _ = state.lists.lock().unwrap().white.load(); + self.console_reply(Text::translate("commands.whitelist.reloaded", &[])); + } + ["add", name] | ["remove", name] => { + let user = self.resolve(name); + let mut l = state.lists.lock().unwrap(); + let (ok, key) = if rest[0] == "add" { + if l.white.contains(&user) { + (false, "commands.whitelist.add.failed") + } else { + l.white.add(WhiteEntry { user: user.clone() }); + (true, "commands.whitelist.add.success") + } + } else if l.white.remove(&user) { + (true, "commands.whitelist.remove.success") + } else { + (false, "commands.whitelist.remove.failed") + }; + drop(l); + let args = if ok { vec![lit(&user.name)] } else { Vec::new() }; + self.console_reply(Text::translate(key, &args)); + } + _ => self.console_reply(Text::translate("command.unknown.argument", &[])), + } + } + + /// DedicatedServerSettings.update: change one key and store the file. + fn store_property(&mut self, key: &str, value: String) { + let path = PathBuf::from("server.properties"); + if let Ok(p) = ServerProperties::from_file(&path, &mut SystemEntropy::default()) + && let Ok(p) = p.update(key, value) + { + let _ = p.store(&path); + } + } + + fn kick_uuid(&mut self, uuid: u128, reason: Tag) { + if let Some(h) = self.lan.as_mut() { + let conns: Vec = h + .hub + .guests + .iter() + .filter(|g| g.uuid == uuid) + .map(|g| g.conn) + .collect(); + for conn in conns { + h.hub.kick(conn, reason.clone()); + } + } + } + + /// MinecraftServer.stopServer: players saved and sent away, worlds saved. + fn stop_dedicated(&mut self) -> Result<()> { + log("INFO", "Stopping server"); + log("INFO", "Saving players"); + if let Some(h) = self.lan.as_mut() { + for g in &h.hub.guests { + horizon_client::lan::playerdata::save(g, &self.world_root); + } + let conns: Vec = h.hub.guests.iter().map(|g| g.conn).collect(); + for conn in conns { + h.hub + .kick(conn, translatable("multiplayer.disconnect.server_shutdown", &[])); + } + } + std::thread::sleep(Duration::from_millis(100)); + log("INFO", "Saving worlds"); + self.save_game()?; + log( + "INFO", + &format!( + "Saving chunks for level 'ServerLevel[{}]'/{}", + self.level.name, + self.dim.id() + ), + ); + self.lan_close(false); + log("INFO", "ThreadedAnvilChunkStorage: All dimensions are saved"); + Ok(()) + } +} + +/// The width and height of a PNG (its IHDR chunk). +fn png_size(bytes: &[u8]) -> Option<(u32, u32)> { + if bytes.len() < 24 || &bytes[..8] != b"\x89PNG\r\n\x1a\n" || &bytes[12..16] != b"IHDR" { + return None; + } + let w = u32::from_be_bytes(bytes[16..20].try_into().ok()?); + let h = u32::from_be_bytes(bytes[20..24].try_into().ok()?); + Some((w, h)) +} diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 2dffef7a6..f359679db 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -7,7 +7,7 @@ use horizon_client::{ Result, items::ItemStack, lan::{ - self, Lan, MAX_PLAYERS, + self, Lan, MAX_PLAYERS, NetConfig, chunks::ChunkEncoder, data::SyncData, entity::EntityState, @@ -345,6 +345,40 @@ impl Game<'_> { if self.lan.is_some() || self.remote.is_some() || self.title.is_some() { return Err("already open".into()); } + let motd = format!("{PLAYER_NAME} - {}", self.level.name); + let host_uuid = self.level.player_uuid.map_or_else( + || offline_uuid(PLAYER_NAME), + |u| { + u128::from(u[0] as u32) << 96 + | u128::from(u[1] as u32) << 64 + | u128::from(u[2] as u32) << 32 + | u128::from(u[3] as u32) + }, + ); + let config = HubConfig { + default_game_mode: self.level.mode(), + guest_commands: settings.guest_commands, + force_game_mode: settings.force_game_mode, + hardcore: self.level.hardcore, + view_distance: self.settings.render_distance.clamp(2, 32), + simulation_distance: self.settings.render_distance.clamp(2, 32), + dimension: self.dim.id().to_owned(), + seed: self.level.seed, + max_players: MAX_PLAYERS, + dedicated: false, + }; + let net = NetConfig::lan(settings.port, motd, MAX_PLAYERS); + self.lan_host(settings, net, config, Some(host_uuid)) + } + /// Start the network side and the play-state hub: for the LAN (with the + /// host's own profile reserved) or for a dedicated server (no host). + pub(super) fn lan_host( + &mut self, + settings: LanSettings, + net: NetConfig, + config: HubConfig, + host: Option, + ) -> Result<()> { let root = self.options.resources.clone(); let sync = SYNC .get_or_init(|| SyncData::load(&root).map(Arc::new)) @@ -372,37 +406,14 @@ impl Game<'_> { &biome_names, ®istry, ); - let motd = format!("{PLAYER_NAME} - {}", self.level.name); - let lan = Lan::start(sync.clone(), settings.port, motd, MAX_PLAYERS)?; - let host_uuid = self.level.player_uuid.map_or_else( - || offline_uuid(PLAYER_NAME), - |u| { - u128::from(u[0] as u32) << 96 - | u128::from(u[1] as u32) << 64 - | u128::from(u[2] as u32) << 32 - | u128::from(u[3] as u32) - }, - ); - lan.reserve(host_uuid); + let lan = Lan::start_with(sync.clone(), net)?; + if let Some(uuid) = host { + lan.reserve(uuid); + } + let host_uuid = host.unwrap_or(0); self.next_entity += 1; let host_entity = self.next_entity as i32; - let hub = Hub::new( - lan, - sync, - encoder, - HubConfig { - default_game_mode: self.level.mode(), - guest_commands: settings.guest_commands, - force_game_mode: settings.force_game_mode, - hardcore: self.level.hardcore, - view_distance: self.settings.render_distance.clamp(2, 32), - simulation_distance: self.settings.render_distance.clamp(2, 32), - dimension: self.dim.id().to_owned(), - seed: self.level.seed, - max_players: MAX_PLAYERS, - dedicated: false, - }, - ); + let hub = Hub::new(lan, sync, encoder, config); let port = hub.lan.port; self.world.block_log = Some(Vec::new()); self.lan = Some(LanHost { @@ -543,7 +554,9 @@ impl Game<'_> { let Some(mut host) = self.lan.take() else { return; }; - if let Some(state) = self.lan_host_state(&host) { + let state = self.lan_host_state(&host); + // A dedicated server runs the hub without a host player. + if state.is_some() || host.hub.config.dedicated { let has_guests = !host.hub.guests.is_empty(); let entities = if has_guests { self.lan_entities(&mut host.hub) @@ -554,7 +567,7 @@ impl Game<'_> { let events = { let mut ctx = TickCtx { world: &mut self.world, - host: Some(&state), + host: state.as_ref(), entities: &entities, next_entity: &mut self.next_entity, spawn, @@ -570,14 +583,16 @@ impl Game<'_> { }; host.hub.tick(&mut ctx) }; - if host.host_mode != state.game_mode { + if let Some(state) = &state + && host.host_mode != state.game_mode + { host.host_mode = state.game_mode; host.hub.set_host_game_mode(state.uuid, state.game_mode); } for event in events { match event { HostEvent::Joined(conn) => { - self.lan_guest_joined(&mut host, conn, &state, &entities, spawn) + self.lan_guest_joined(&mut host, conn, state.as_ref(), &entities, spawn) } HostEvent::Left(guest) => { playerdata::save(&guest, &self.world_root); @@ -602,7 +617,7 @@ impl Game<'_> { &mut self, host: &mut LanHost, conn: u32, - state: &HostState, + state: Option<&HostState>, entities: &[EntityState], spawn: [f64; 3], ) { @@ -624,7 +639,7 @@ impl Game<'_> { } let mut ctx = TickCtx { world: &mut self.world, - host: Some(state), + host: state, entities, next_entity: &mut self.next_entity, spawn, diff --git a/crates/horizon-client/src/lan/conn.rs b/crates/horizon-client/src/lan/conn.rs index 6cd41d6d6..92ceea338 100644 --- a/crates/horizon-client/src/lan/conn.rs +++ b/crates/horizon-client/src/lan/conn.rs @@ -35,16 +35,61 @@ const KEEP_ALIVE_EVERY: Duration = Duration::from_secs(15); const KEEP_ALIVE_TIMEOUT: Duration = Duration::from_secs(30); /// Packets queued for one client beyond this many bytes disconnect it. const MAX_PENDING: usize = 96 << 20; -/// Connection.setupCompression threshold of the integrated server. -const COMPRESSION_THRESHOLD: i32 = 256; - /// Vanilla's server-side disconnect during login is a JSON component. -fn login_disconnect(c: &mut Connection, key: &str) { - let json = format!("{{\"translate\":\"{key}\"}}"); +fn login_disconnect(c: &mut Connection, reason: &horizon_world::nbt::Tag) { + let json = component_json(reason); let _ = c.send(&login::Clientbound::Disconnect(login::Disconnect { reason_json: json }).encode()); } +/// A component as ComponentSerialization.CODEC writes it with JsonOps (and +/// Gson without HTML escaping): plain text collapses to a string, the +/// content fields come first, then `extra`, then the style. +pub fn component_json(tag: &horizon_world::nbt::Tag) -> String { + component_value(tag).compact() +} +fn component_value(tag: &horizon_world::nbt::Tag) -> crate::server::json::Json { + use crate::server::json::Json; + use horizon_world::nbt::Tag; + const ORDER: &[&str] = &[ + "type", "text", "translate", "fallback", "with", "score", "selector", "separator", + "keybind", "nbt", "interpret", "block", "entity", "storage", "source", "object", + "sprite", "atlas", "player", "hat", "extra", "color", "shadow_color", "bold", "italic", + "underlined", "strikethrough", "obfuscated", "click_event", "hover_event", "insertion", + "font", + ]; + match tag { + Tag::String(s) => Json::String(s.to_string_lossy()), + Tag::List(items) => Json::Array(items.iter().map(component_value).collect()), + Tag::Compound(map) => { + if map.len() == 1 + && let Some(Tag::String(t)) = map.get(&horizon_world::nbt::JavaString::from("text")) + { + return Json::String(t.to_string_lossy()); + } + let mut keys: Vec = map.keys().map(|k| k.to_string_lossy()).collect(); + keys.sort_by_key(|k| ORDER.iter().position(|o| o == k).unwrap_or(ORDER.len())); + Json::Object( + keys.into_iter() + .map(|k| { + let v = &map[&horizon_world::nbt::JavaString::from(k.as_str())]; + let value = match v { + Tag::Byte(b) => Json::Bool(*b != 0), + Tag::Int(i) => Json::Number(i.to_string()), + other => component_value(other), + }; + (k, value) + }) + .collect(), + ) + } + Tag::Byte(b) => Json::Bool(*b != 0), + Tag::Int(i) => Json::Number(i.to_string()), + Tag::Long(i) => Json::Number(i.to_string()), + _ => Json::Null, + } +} + /// StringUtil.isValidPlayerName. pub fn valid_name(name: &str) -> bool { (1..=16).contains(&name.len()) && name.chars().all(|c| c as u32 > 32 && (c as u32) < 127) @@ -63,7 +108,11 @@ impl PlayerSender { } } -pub fn serve(stream: TcpStream, shared: Arc) -> Result<(), String> { +pub fn serve( + stream: TcpStream, + address: std::net::SocketAddr, + shared: Arc, +) -> Result<(), String> { let e = |e: horizon_protocol::Error| e.to_string(); let mut c = Connection::from_stream(stream).map_err(e)?; c.reader @@ -75,10 +124,20 @@ pub fn serve(stream: TcpStream, shared: Arc) -> Result<(), String> { _ => return Err("expected a handshake".into()), }; match intention.intent { + // ServerHandshakePacketListenerImpl: a server that does not reply + // to status requests closes the connection. + handshake::STATUS if !shared.config.enable_status => Ok(()), handshake::STATUS => serve_status(&mut c, &shared), + handshake::TRANSFER if !shared.config.accepts_transfers => { + login_disconnect( + &mut c, + &translatable("multiplayer.disconnect.transfers_disabled", &[]), + ); + Ok(()) + } handshake::LOGIN | handshake::TRANSFER => { if intention.protocol != PROTOCOL_VERSION { - let key = if intention.protocol < PROTOCOL_VERSION { + let key = if intention.protocol < 754 { "multiplayer.disconnect.outdated_client" } else { "multiplayer.disconnect.incompatible" @@ -93,7 +152,7 @@ pub fn serve(stream: TcpStream, shared: Arc) -> Result<(), String> { ); return Ok(()); } - serve_login(c, &shared) + serve_login(c, address, &shared) } other => Err(format!("unknown intent {other}")), } @@ -101,10 +160,14 @@ pub fn serve(stream: TcpStream, shared: Arc) -> Result<(), String> { fn serve_status(c: &mut Connection, shared: &Shared) -> Result<(), String> { let e = |e: horizon_protocol::Error| e.to_string(); + let mut requested = false; loop { let (id, payload) = c.recv().map_err(e)?; match status::Serverbound::decode(id, &payload).map_err(e)? { + // ServerStatusPacketListenerImpl: a second request disconnects. + status::Serverbound::StatusRequest(_) if requested => return Ok(()), status::Serverbound::StatusRequest(_) => { + requested = true; let json = shared.status_json(); c.send( &status::Clientbound::StatusResponse(status::StatusResponse { json }).encode(), @@ -121,7 +184,11 @@ fn serve_status(c: &mut Connection, shared: &Shared) -> Result<(), String> { } } -fn serve_login(mut c: Connection, shared: &Arc) -> Result<(), String> { +fn serve_login( + mut c: Connection, + address: std::net::SocketAddr, + shared: &Arc, +) -> Result<(), String> { let e = |e: horizon_protocol::Error| e.to_string(); let (id, payload) = c.recv().map_err(e)?; let hello = match login::Serverbound::decode(id, &payload).map_err(e)? { @@ -129,20 +196,23 @@ fn serve_login(mut c: Connection, shared: &Arc) -> Result<(), String> { _ => return Err("expected a login hello".into()), }; if !valid_name(&hello.name) { - login_disconnect(&mut c, "multiplayer.disconnect.invalid_name"); + login_disconnect( + &mut c, + &translatable("multiplayer.disconnect.invalid_name", &[]), + ); return Ok(()); } // Offline mode: the profile is derived from the name (PlayerList.canPlayerLogin // then rejects duplicates and a full server). let uuid = offline_uuid(&hello.name); - if let Some(reason) = shared.try_admit(uuid, &hello.name) { - login_disconnect(&mut c, reason); + if let Some(reason) = shared.try_admit(address, uuid, &hello.name) { + login_disconnect(&mut c, &reason); return Ok(()); } let result = login_and_configure(&mut c, shared, uuid, &hello.name); match result { Ok(Some(parts)) => { - play(c, shared, parts); + play(c, shared, parts, address); Ok(()) } Ok(None) => { @@ -170,14 +240,12 @@ fn login_and_configure( name: &str, ) -> Result, String> { let e = |e: horizon_protocol::Error| e.to_string(); - c.send( - &login::Clientbound::Compression(login::Compression { - threshold: COMPRESSION_THRESHOLD, - }) - .encode(), - ) - .map_err(e)?; - c.set_compression(COMPRESSION_THRESHOLD); + let threshold = shared.config.compression_threshold; + if threshold >= 0 { + c.send(&login::Clientbound::Compression(login::Compression { threshold }).encode()) + .map_err(e)?; + c.set_compression(threshold); + } c.send( &login::Clientbound::LoginFinished(login::LoginFinished { profile: login::GameProfile { @@ -266,7 +334,7 @@ fn login_and_configure( })) } -fn play(c: Connection, shared: &Arc, parts: Parts) { +fn play(c: Connection, shared: &Arc, parts: Parts, address: std::net::SocketAddr) { let conn_id = shared.next_id(); let events = shared.events.clone(); let _ = c.reader.set_read_timeout(Some(KEEP_ALIVE_TIMEOUT)); @@ -294,6 +362,7 @@ fn play(c: Connection, shared: &Arc, parts: Parts) { brand: parts.brand, sender, latency, + address, }; let reason = if events.send(NetEvent::Joined(Box::new(joined))).is_ok() { read_loop(&mut reader, conn_id, &events, &alive) diff --git a/crates/horizon-client/src/lan/guest.rs b/crates/horizon-client/src/lan/guest.rs index c32e19d07..0f0f2b023 100644 --- a/crates/horizon-client/src/lan/guest.rs +++ b/crates/horizon-client/src/lan/guest.rs @@ -20,6 +20,8 @@ pub const SPECTATOR: i32 = 3; pub struct Guest { pub conn: u32, + /// The client's address (IP bans, `list`). + pub address: std::net::SocketAddr, pub uuid: u128, pub name: String, pub entity_id: i32, @@ -97,6 +99,7 @@ impl Guest { pub fn new(j: Joined, entity_id: i32, position: [f64; 3], view_distance: i32) -> Self { Self { conn: j.conn, + address: j.address, uuid: j.uuid, name: j.name, entity_id, diff --git a/crates/horizon-client/src/lan/hub.rs b/crates/horizon-client/src/lan/hub.rs index ed9771043..51c1cc83b 100644 --- a/crates/horizon-client/src/lan/hub.rs +++ b/crates/horizon-client/src/lan/hub.rs @@ -409,9 +409,7 @@ impl Hub { /// The permissions changed: tell everyone their level and commands again. pub fn resend_commands(&mut self) { for i in 0..self.guests.len() { - if !self.config.dedicated { - self.guests[i].permission = self.default_permission(self.guests[i].uuid); - } + self.guests[i].permission = self.default_permission(self.guests[i].uuid); if self.guests[i].placed { self.send_permission_level(i); } @@ -586,6 +584,20 @@ impl Hub { g.inbox.push_back(*packet); } } + NetEvent::Duplicate(uuid) => { + let conns: Vec = self + .guests + .iter() + .filter(|g| g.uuid == uuid) + .map(|g| g.conn) + .collect(); + for conn in conns { + self.kick( + conn, + translatable("multiplayer.disconnect.duplicate_login", &[]), + ); + } + } } } for i in 0..self.guests.len() { diff --git a/crates/horizon-client/src/lan/mod.rs b/crates/horizon-client/src/lan/mod.rs index cd0214c5e..23f6120d5 100644 --- a/crates/horizon-client/src/lan/mod.rs +++ b/crates/horizon-client/src/lan/mod.rs @@ -20,14 +20,17 @@ pub mod tracking; pub use conn::PlayerSender; use horizon_protocol::packets::play; -use horizon_protocol::{GAME_VERSION, PROTOCOL_VERSION, packets::configuration::ClientInformation}; +use horizon_protocol::{ + GAME_VERSION, PROTOCOL_VERSION, crypto::uuid_string, packets::configuration::ClientInformation, + text::translatable, +}; use std::{ collections::HashSet, io, net::{SocketAddr, TcpListener, TcpStream}, sync::{ Arc, Mutex, - atomic::{AtomicBool, AtomicI32, AtomicU32, Ordering}, + atomic::{AtomicBool, AtomicI32, AtomicU32, AtomicUsize, Ordering}, mpsc::{Receiver, Sender, channel}, }, thread::JoinHandle, @@ -44,6 +47,9 @@ pub enum NetEvent { Packet(u32, Box), /// The connection ended (reason for the log). Left(u32, String), + /// PlayerList.disconnectAllPlayersWithProfile: a new login of this + /// profile replaces the player already in the world. + Duplicate(u128), } pub struct Joined { pub conn: u32, @@ -54,6 +60,7 @@ pub struct Joined { pub sender: PlayerSender, /// Smoothed keep-alive round trip in milliseconds. pub latency: Arc, + pub address: SocketAddr, } /// Queued for a connection's writer thread. pub enum Out { @@ -64,54 +71,211 @@ pub enum Out { Close, } +/// PlayerList.canPlayerLogin for a dedicated server: the disconnect reason +/// (bans, whitelist) for a profile connecting from an address, if refused. +pub type LoginGate = Arc Option + Send + Sync>; + +/// How the server side of the network behaves: an integrated server's LAN +/// uses the defaults, a dedicated server takes them from server.properties. +#[derive(Clone)] +pub struct NetConfig { + /// server-ip (all interfaces when absent). + pub bind: Option, + /// 0 picks a free port. + pub port: u16, + pub motd: String, + pub max_players: usize, + /// network-compression-threshold; negative disables compression. + pub compression_threshold: i32, + /// enable-status: answer status pings. + pub enable_status: bool, + pub hide_online_players: bool, + /// server-icon.png (64x64 PNG bytes). + pub favicon: Option>, + /// MinecraftServer.enforceSecureProfile. + pub enforces_secure_chat: bool, + pub accepts_transfers: bool, + /// LanServerPinger: announce the world on the local network. + pub announce: bool, + /// Ops bypass a full server (ServerOpList.canBypassPlayerLimit). + pub bypasses_limit: Option bool + Send + Sync>>, + pub gate: Option, +} +impl NetConfig { + /// IntegratedServer.publishServer. + pub fn lan(port: u16, motd: String, max_players: usize) -> Self { + Self { + bind: None, + port, + motd, + max_players, + compression_threshold: 256, + enable_status: true, + hide_online_players: false, + favicon: None, + enforces_secure_chat: false, + accepts_transfers: false, + announce: true, + bypasses_limit: None, + gate: None, + } + } +} + /// State shared with the connection threads. pub struct Shared { pub sync: Arc, pub events: Sender, + pub config: NetConfig, motd: Mutex, - online: Mutex>, - max_players: usize, + max_players: AtomicUsize, + /// PlayerList.players in join order: profile id and name. + online: Mutex>, + /// Profiles held by the host (the LAN host's own name). + reserved: Mutex>, next: AtomicU32, stop: AtomicBool, + random: Mutex, } impl Shared { pub fn next_id(&self) -> u32 { self.next.fetch_add(1, Ordering::Relaxed) } - /// PlayerList.canPlayerLogin: duplicates and a full server are refused. - pub fn try_admit(&self, uuid: u128, _name: &str) -> Option<&'static str> { - let mut online = self.online.lock().unwrap(); - if online.contains(&uuid) { - return Some("multiplayer.disconnect.duplicate_login"); + /// PlayerList.canPlayerLogin then disconnectAllPlayersWithProfile: the + /// refusal reason, or None once the profile holds a place. A profile + /// already playing is kicked and its place awaited. + pub fn try_admit( + &self, + address: SocketAddr, + uuid: u128, + name: &str, + ) -> Option { + if let Some(gate) = &self.config.gate + && let Some(reason) = gate(address, uuid, name) + { + return Some(reason); } - if online.len() >= self.max_players { - return Some("multiplayer.disconnect.server_full"); + if self.reserved.lock().unwrap().contains(&uuid) { + return Some(translatable("multiplayer.disconnect.duplicate_login", &[])); } - online.insert(uuid); + { + let online = self.online.lock().unwrap(); + let bypass = self.config.bypasses_limit.as_ref().is_some_and(|b| b(uuid)); + let taken = online.len() + self.reserved.lock().unwrap().len(); + if taken >= self.max_players() && !bypass { + return Some(translatable("multiplayer.disconnect.server_full", &[])); + } + } + if self.is_online(uuid) { + let _ = self.events.send(NetEvent::Duplicate(uuid)); + let deadline = std::time::Instant::now() + Duration::from_secs(30); + while self.is_online(uuid) { + if std::time::Instant::now() > deadline { + return Some(translatable("multiplayer.disconnect.slow_login", &[])); + } + std::thread::sleep(Duration::from_millis(10)); + } + } + self.online.lock().unwrap().push((uuid, name.to_owned())); None } + fn is_online(&self, uuid: u128) -> bool { + self.online.lock().unwrap().iter().any(|(u, _)| *u == uuid) + } pub fn motd(&self) -> String { self.motd.lock().unwrap().clone() } + pub fn max_players(&self) -> usize { + self.max_players.load(Ordering::Relaxed) + } + pub fn set_max_players(&self, n: usize) { + self.max_players.store(n, Ordering::Relaxed); + } pub fn release(&self, uuid: u128) { - self.online.lock().unwrap().remove(&uuid); + self.online.lock().unwrap().retain(|(u, _)| *u != uuid); } pub fn online(&self) -> usize { - self.online.lock().unwrap().len() + self.online.lock().unwrap().len() + self.reserved.lock().unwrap().len() } - /// The status response (ServerStatus): version, players and the MOTD. + fn next_random(&self, bound: usize) -> usize { + let mut r = self.random.lock().unwrap(); + *r = r.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1_442_695_040_888_963_407); + ((*r >> 33) as usize) % bound.max(1) + } + /// The status response (MinecraftServer.buildServerStatus encoded with + /// ServerStatus.CODEC): description, players with up to 12 shuffled + /// names, version, favicon and enforcesSecureChat when true. pub fn status_json(&self) -> String { + use crate::server::json::Json; let motd = self.motd.lock().unwrap().clone(); - serde_json::json!({ - "version": { "name": GAME_VERSION, "protocol": PROTOCOL_VERSION }, - "players": { "max": self.max_players, "online": self.online() }, - "description": { "text": motd }, - "enforcesSecureChat": false, - }) - .to_string() + let online: Vec<(u128, String)> = self.online.lock().unwrap().clone(); + let count = self.online(); + let mut players = vec![ + ("max".to_owned(), Json::Number(self.max_players().to_string())), + ("online".to_owned(), Json::Number(count.to_string())), + ]; + if !self.config.hide_online_players && !online.is_empty() { + let size = online.len().min(12); + let offset = self.next_random(online.len() - size + 1); + let mut sample: Vec<(u128, String)> = online[offset..offset + size].to_vec(); + for i in (1..sample.len()).rev() { + let j = self.next_random(i + 1); + sample.swap(i, j); + } + players.push(( + "sample".to_owned(), + Json::Array( + sample + .into_iter() + .map(|(u, n)| { + Json::Object(vec![ + ("id".to_owned(), Json::String(uuid_string(u))), + ("name".to_owned(), Json::String(n)), + ]) + }) + .collect(), + ), + )); + } + let mut status = vec![ + ("description".to_owned(), Json::String(motd)), + ("players".to_owned(), Json::Object(players)), + ( + "version".to_owned(), + Json::Object(vec![ + ("name".to_owned(), Json::String(GAME_VERSION.to_owned())), + ("protocol".to_owned(), Json::Number(PROTOCOL_VERSION.to_string())), + ]), + ), + ]; + if let Some(icon) = &self.config.favicon { + status.push(( + "favicon".to_owned(), + Json::String(format!("data:image/png;base64,{}", base64(icon))), + )); + } + if self.config.enforces_secure_chat { + status.push(("enforcesSecureChat".to_owned(), Json::Bool(true))); + } + Json::Object(status).compact() } } +/// java.util.Base64.getEncoder (padded, no line breaks). +pub fn base64(data: &[u8]) -> String { + const A: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + let mut out = String::with_capacity(data.len().div_ceil(3) * 4); + for chunk in data.chunks(3) { + let b = [chunk[0], *chunk.get(1).unwrap_or(&0), *chunk.get(2).unwrap_or(&0)]; + let n = u32::from(b[0]) << 16 | u32::from(b[1]) << 8 | u32::from(b[2]); + out.push(char::from(A[(n >> 18) as usize & 63])); + out.push(char::from(A[(n >> 12) as usize & 63])); + out.push(if chunk.len() > 1 { char::from(A[(n >> 6) as usize & 63]) } else { '=' }); + out.push(if chunk.len() > 2 { char::from(A[n as usize & 63]) } else { '=' }); + } + out +} + /// A running LAN server. pub struct Lan { pub shared: Arc, @@ -129,19 +293,33 @@ impl Lan { motd: String, max_players: usize, ) -> io::Result { - let listener = TcpListener::bind(("0.0.0.0", port))?; + Self::start_with(sync, NetConfig::lan(port, motd, max_players)) + } + /// ServerConnectionListener.startTcpServerListener with a configuration. + pub fn start_with(sync: Arc, config: NetConfig) -> io::Result { + 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)?; let port = listener.local_addr()?.port(); - let _pinger = discovery::Pinger::start(motd.clone(), port).ok(); + let _pinger = if config.announce { + discovery::Pinger::start(config.motd.clone(), port).ok() + } else { + None + }; let (tx, events) = channel(); let shared = Arc::new(Shared { sync, events: tx, - motd: Mutex::new(motd), - online: Mutex::new(HashSet::new()), - max_players, + motd: Mutex::new(config.motd.clone()), + max_players: AtomicUsize::new(config.max_players), + online: Mutex::new(Vec::new()), + reserved: Mutex::new(HashSet::new()), next: AtomicU32::new(1), stop: AtomicBool::new(false), + random: Mutex::new(crate::server::java_properties::now_millis() as u64 | 1), + config, }); let accept_shared = shared.clone(); let listener = std::thread::Builder::new() @@ -161,7 +339,7 @@ impl Lan { } /// Reserve a uuid for the host so a guest cannot take the name. pub fn reserve(&self, uuid: u128) { - self.shared.online.lock().unwrap().insert(uuid); + self.shared.reserved.lock().unwrap().insert(uuid); } pub fn set_motd(&self, motd: &str) { *self.shared.motd.lock().unwrap() = motd.to_owned(); @@ -198,7 +376,7 @@ fn accept_loop(listener: TcpListener, shared: Arc) { } fn handle(stream: TcpStream, addr: SocketAddr, shared: Arc) { let _ = stream.set_nonblocking(false); - if let Err(e) = conn::serve(stream, shared) + if let Err(e) = conn::serve(stream, addr, shared) && std::env::var_os("HORIZON_NET_DEBUG").is_some() { eprintln!("[lan] {addr}: {e}");