diff --git a/Cargo.lock b/Cargo.lock index 6ebc69964..cdd211d85 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1417,6 +1417,7 @@ dependencies = [ "horizon-friends", "horizon-mods", "horizon-protocol", + "horizon-server-files", "horizon-shaderpack", "horizon-telemetry", "horizon-theme", @@ -1541,6 +1542,28 @@ dependencies = [ "serde_json", ] +[[package]] +name = "horizon-server" +version = "0.1.0" +dependencies = [ + "horizon-server-files", + "libc", + "serde", + "toml", + "toml_edit", + "windows-sys 0.61.2", +] + +[[package]] +name = "horizon-server-files" +version = "0.1.0" +dependencies = [ + "horizon-core", + "horizon-protocol", + "horizon-world", + "log", +] + [[package]] name = "horizon-shaderpack" version = "0.1.0" @@ -3739,6 +3762,7 @@ dependencies = [ "indexmap", "toml_datetime", "toml_parser", + "toml_writer", "winnow", ] diff --git a/Cargo.toml b/Cargo.toml index 1b4cb92d4..607dee6fb 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [workspace] exclude = ["launcher", "crates/horizon-telemetry-server"] -members = ["crates/horizon-core", "crates/horizon-dualsense", "crates/horizon-world", "crates/voxel-kernels", "crates/horizon-client", "crates/horizon-assets", "crates/horizon-protocol", "crates/horizon-theme", "crates/horizon-shaderpack", "crates/horizon-prepare", "crates/horizon-telemetry", "crates/horizon-bench", "crates/horizon-friends", "crates/horizon-relay", "crates/horizon-mod-sdk", "crates/horizon-mods", "crates/horizon-mods/tests/guest", "crates/cargo-horizon-mod", "crates/horizon-port-pack", "crates/horizon-mod-sdk/examples/coords-hud", "xtask"] +members = ["crates/horizon-core", "crates/horizon-dualsense", "crates/horizon-world", "crates/voxel-kernels", "crates/horizon-client", "crates/horizon-server-files", "crates/horizon-server", "crates/horizon-assets", "crates/horizon-protocol", "crates/horizon-theme", "crates/horizon-shaderpack", "crates/horizon-prepare", "crates/horizon-telemetry", "crates/horizon-bench", "crates/horizon-friends", "crates/horizon-relay", "crates/horizon-mod-sdk", "crates/horizon-mods", "crates/horizon-mods/tests/guest", "crates/cargo-horizon-mod", "crates/horizon-port-pack", "crates/horizon-mod-sdk/examples/coords-hud", "xtask"] resolver = "2" [workspace.package] diff --git a/crates/horizon-client/Cargo.toml b/crates/horizon-client/Cargo.toml index 19b4c81db..29a02553f 100644 --- a/crates/horizon-client/Cargo.toml +++ b/crates/horizon-client/Cargo.toml @@ -12,6 +12,8 @@ horizon-assets = { path = "../horizon-assets" } horizon-core = { path = "../horizon-core" } horizon-world = { path = "../horizon-world" } horizon-protocol = { path = "../horizon-protocol" } +# server.properties, eula.txt and the user lists, shared with horizon-server. +horizon-server-files = { path = "../horizon-server-files" } horizon-friends = { path = "../horizon-friends" } # Horizon mods: sandboxed WebAssembly components, off unless installed and turned on (docs/mods.md). horizon-mods = { path = "../horizon-mods" } diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index 6148dc4aa..79a8ddd86 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -148,7 +148,7 @@ pub mod screen_draw; pub mod screen_effects; pub mod screen_layout; pub mod sculk; -pub mod server; +pub use horizon_server_files as server; pub mod settings; pub mod shader_pack; pub mod shadows; diff --git a/crates/horizon-server-files/Cargo.toml b/crates/horizon-server-files/Cargo.toml new file mode 100644 index 000000000..52114718d --- /dev/null +++ b/crates/horizon-server-files/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "horizon-server-files" +version = "0.1.0" +edition.workspace = true +license.workspace = true +rust-version = "1.90" +description = "The dedicated server's vanilla files: server.properties, eula.txt, ops, whitelist and bans" + +[dependencies] +horizon-core = { path = "../horizon-core" } +horizon-protocol = { path = "../horizon-protocol" } +horizon-world = { path = "../horizon-world" } +log = "0.4" + +[lints] +workspace = true diff --git a/crates/horizon-client/src/server/eula.rs b/crates/horizon-server-files/src/eula.rs similarity index 86% rename from crates/horizon-client/src/server/eula.rs rename to crates/horizon-server-files/src/eula.rs index b5896cfd7..769af9401 100644 --- a/crates/horizon-client/src/server/eula.rs +++ b/crates/horizon-server-files/src/eula.rs @@ -9,8 +9,13 @@ pub const EULA_LINK: &str = "https://aka.ms/MinecraftEULA"; /// The default file, as Properties.store(OutputStream) writes it. pub fn default_file(millis: i64) -> String { + file(millis, false) +} + +/// The file with `eula` set: what the owner's agreement writes (horizon-server init). +pub fn file(millis: i64, agreed: bool) -> String { let mut p = Properties::default(); - p.put("eula", "false".into()); + p.put("eula", agreed.to_string()); p.store( Some(&format!( "By changing the setting below to TRUE you are indicating your agreement to our EULA ({EULA_LINK})." diff --git a/crates/horizon-client/src/server/java_properties.rs b/crates/horizon-server-files/src/java_properties.rs similarity index 100% rename from crates/horizon-client/src/server/java_properties.rs rename to crates/horizon-server-files/src/java_properties.rs diff --git a/crates/horizon-client/src/server/json.rs b/crates/horizon-server-files/src/json.rs similarity index 100% rename from crates/horizon-client/src/server/json.rs rename to crates/horizon-server-files/src/json.rs diff --git a/crates/horizon-client/src/server/mod.rs b/crates/horizon-server-files/src/lib.rs similarity index 50% rename from crates/horizon-client/src/server/mod.rs rename to crates/horizon-server-files/src/lib.rs index 1bb0d80c1..30c75c869 100644 --- a/crates/horizon-client/src/server/mod.rs +++ b/crates/horizon-server-files/src/lib.rs @@ -1,8 +1,8 @@ //! The dedicated server's files and settings, ported from //! net.minecraft.server.dedicated and net.minecraft.server.players: -//! server.properties, eula.txt and the four user lists. The server itself -//! runs the game's own world, simulation and LAN hub headless -//! (`horizon-client --dedicated`, see the game's `dedicated` module). +//! server.properties, eula.txt and the four user lists. The game's dedicated +//! server (`horizon-client --dedicated`) reads them, and `horizon-server` +//! manages them; this crate needs neither a window nor the game. pub mod eula; pub mod java_properties; pub mod json; diff --git a/crates/horizon-client/src/server/properties.rs b/crates/horizon-server-files/src/properties.rs similarity index 100% rename from crates/horizon-client/src/server/properties.rs rename to crates/horizon-server-files/src/properties.rs diff --git a/crates/horizon-client/src/server/user_lists.rs b/crates/horizon-server-files/src/user_lists.rs similarity index 100% rename from crates/horizon-client/src/server/user_lists.rs rename to crates/horizon-server-files/src/user_lists.rs diff --git a/crates/horizon-server/Cargo.toml b/crates/horizon-server/Cargo.toml new file mode 100644 index 000000000..919001968 --- /dev/null +++ b/crates/horizon-server/Cargo.toml @@ -0,0 +1,24 @@ +[package] +name = "horizon-server" +version = "0.1.0" +edition.workspace = true +license.workspace = true +rust-version = "1.90" +description = "Host a Horizon server: server.toml, the CLI and the supervisor that runs the game headless (docs/server.md)" + +[dependencies] +horizon-server-files = { path = "../horizon-server-files" } +serde = { version = "1", features = ["derive"] } +toml = "1.1" +# Edits server.toml in place, keeping the owner's comments and order. +toml_edit = "0.25" + +[target.'cfg(unix)'.dependencies] +# SIGINT/SIGTERM/SIGHUP: stop the game cleanly when the terminal or the service manager asks. +libc = "0.2" + +[target.'cfg(windows)'.dependencies] +windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_System_Console", "Win32_System_Threading"] } + +[lints] +workspace = true diff --git a/crates/horizon-server/src/config.rs b/crates/horizon-server/src/config.rs new file mode 100644 index 000000000..ce581be60 --- /dev/null +++ b/crates/horizon-server/src/config.rs @@ -0,0 +1,515 @@ +//! `server.toml`, the one file an owner edits (docs/server.md, section 4). +//! +//! It has typed sections for what owners change and `[properties]` for any other vanilla key. Before every +//! start the supervisor writes them into `server.properties`, which the game reads exactly as vanilla's +//! server does; what the game changes there itself (`/whitelist on`) is copied back afterwards. + +use horizon_server_files::{ + java_properties::{Properties, date_string, now_millis}, + properties::{DIFFICULTIES, GAME_MODES, ServerProperties, SystemEntropy}, +}; +use serde::{Deserialize, Serialize}; +use std::{collections::BTreeMap, path::Path}; + +pub const FILE: &str = "server.toml"; +pub const PROPERTIES: &str = "server.properties"; + +/// What `init` writes: every typed setting, with vanilla 26.3's defaults and what it means. +pub const TEMPLATE: &str = r##"# Horizon server settings (docs/server.md). The server writes them into server.properties before +# every start: edit this file, not that one. + +[server] +motd = "A Minecraft Server" +port = 25565 +bind = "" # listen on every address, or only on this one (server-ip) +max_players = 20 +online_mode = true # not supported by Horizon yet: the server runs offline and says so +whitelist = true # only whitelisted players and operators can join +enforce_whitelist = false # kick online players taken off the whitelist +view_distance = 10 +simulation_distance = 10 + +[world] +name = "world" # the world folder +seed = "" # empty: a random seed on the first start +game_mode = "survival" # survival, creative, adventure or spectator +difficulty = "easy" # peaceful, easy, normal or hard +hardcore = false + +# Any other server.properties key, spelled as vanilla spells it, for example: +# spawn-protection = 16 +[properties] + +[engine] +path = "" # the game program; empty: the one installed beside horizon-server +resources = "" # the prepared game files; empty: resources/ here, else the usual places +restart_on_crash = true +"##; + +/// Each typed setting: its section, its name, and the vanilla key it writes. +const TYPED: [(&str, &str, &str); 14] = [ + ("server", "motd", "motd"), + ("server", "port", "server-port"), + ("server", "bind", "server-ip"), + ("server", "max_players", "max-players"), + ("server", "online_mode", "online-mode"), + ("server", "whitelist", "white-list"), + ("server", "enforce_whitelist", "enforce-whitelist"), + ("server", "view_distance", "view-distance"), + ("server", "simulation_distance", "simulation-distance"), + ("world", "name", "level-name"), + ("world", "seed", "level-seed"), + ("world", "game_mode", "gamemode"), + ("world", "difficulty", "difficulty"), + ("world", "hardcore", "hardcore"), +]; + +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Config { + #[serde(default)] + pub server: Server, + #[serde(default)] + pub world: World, + #[serde(default)] + pub properties: BTreeMap, + #[serde(default)] + pub engine: Engine, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default, deny_unknown_fields)] +pub struct Server { + pub motd: String, + pub port: u16, + pub bind: String, + pub max_players: u32, + pub online_mode: bool, + pub whitelist: bool, + pub enforce_whitelist: bool, + pub view_distance: u32, + pub simulation_distance: u32, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default, deny_unknown_fields)] +pub struct World { + pub name: String, + /// A number or any text (vanilla hashes text); empty for a random seed. + #[serde(deserialize_with = "text_or_number")] + pub seed: String, + pub game_mode: String, + pub difficulty: String, + pub hardcore: bool, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default, deny_unknown_fields)] +pub struct Engine { + pub path: String, + pub resources: String, + pub restart_on_crash: bool, +} + +impl Default for Server { + fn default() -> Self { + Self { + motd: "A Minecraft Server".into(), + port: 25565, + bind: String::new(), + max_players: 20, + online_mode: true, + whitelist: true, + enforce_whitelist: false, + view_distance: 10, + simulation_distance: 10, + } + } +} +impl Default for World { + fn default() -> Self { + Self { + name: "world".into(), + seed: String::new(), + game_mode: "survival".into(), + difficulty: "easy".into(), + hardcore: false, + } + } +} +impl Default for Engine { + fn default() -> Self { + Self { + path: String::new(), + resources: String::new(), + restart_on_crash: true, + } + } +} + +fn text_or_number<'de, D: serde::Deserializer<'de>>(d: D) -> Result { + #[derive(Deserialize)] + #[serde(untagged)] + enum Seed { + Text(String), + Number(i64), + } + Ok(match Seed::deserialize(d)? { + Seed::Text(s) => s, + Seed::Number(n) => n.to_string(), + }) +} + +impl Config { + pub fn parse(text: &str) -> Result { + let config: Self = toml::from_str(text).map_err(|e| e.to_string())?; + config.check()?; + Ok(config) + } + + pub fn load(dir: &Path) -> Result { + let path = dir.join(FILE); + let text = std::fs::read_to_string(&path) + .map_err(|e| format!("{}: {e} (run `horizon-server init` first)", path.display()))?; + Self::parse(&text).map_err(|e| format!("{}: {e}", path.display())) + } + + fn check(&self) -> Result<(), String> { + let w = &self.world; + if !GAME_MODES.contains(&w.game_mode.as_str()) { + return Err(format!( + "world.game_mode is \"{}\": use {}", + w.game_mode, + GAME_MODES.join(", ") + )); + } + if !DIFFICULTIES.contains(&w.difficulty.as_str()) { + return Err(format!( + "world.difficulty is \"{}\": use {}", + w.difficulty, + DIFFICULTIES.join(", ") + )); + } + if w.name.is_empty() || w.name.contains(['/', '\\']) || w.name == ".." { + return Err(format!( + "world.name \"{}\" must be a folder name, without slashes", + w.name + )); + } + if self.server.port == 0 { + return Err("server.port must be a port number from 1 to 65535".into()); + } + if let Some((section, field, key)) = + TYPED.iter().find(|t| self.properties.contains_key(t.2)) + { + return Err(format!( + "[properties] sets {key}: set {section}.{field} instead" + )); + } + Ok(()) + } + + /// The vanilla keys and values this configuration sets, typed settings first. + pub fn vanilla(&self) -> Vec<(String, String)> { + let table = toml::Table::try_from(self).expect("a configuration is a table"); + let mut out: Vec<(String, String)> = TYPED + .iter() + .map(|(section, field, key)| { + ((*key).to_owned(), property_text(&table[*section][*field])) + }) + .collect(); + out.extend( + self.properties + .iter() + .map(|(k, v)| (k.clone(), property_text(v))), + ); + out + } + + /// Writes this configuration into `server.properties`, keeping the keys it doesn't set. Returns what it + /// wrote, for [`sync_back`]. + pub fn write_properties(&self, dir: &Path) -> std::io::Result> { + let path = dir.join(PROPERTIES); + let mut properties = read_properties(&path).unwrap_or_default(); + let written = self.vanilla(); + for (key, value) in &written { + properties.put(key, value.clone()); + } + let text = properties.store( + Some("Minecraft server properties"), + &date_string(now_millis()), + false, + ); + std::fs::write(path, text)?; + Ok(written) + } + + /// A configuration from a vanilla `server.properties`: typed settings from their keys, and every other + /// key the file sets to something other than vanilla's default under `[properties]`. + pub fn import(source: &Properties) -> Result { + let parsed = ServerProperties::new(source.clone(), &mut SystemEntropy::default())?; + let defaults = ServerProperties::new(Properties::default(), &mut SystemEntropy::default())?; + let mut table = toml::Table::try_from(Self::default()).map_err(|e| e.to_string())?; + for (section, field, key) in TYPED { + let (Some(text), Some(slot)) = ( + parsed.raw.get(key), + table + .get_mut(section) + .and_then(|s| s.as_table_mut()) + .and_then(|s| s.get_mut(field)), + ) else { + continue; + }; + if let Some(value) = typed_value(text, slot) { + *slot = value; + } + } + let mut extra = toml::Table::new(); + let mut keys: Vec<&String> = source.map.keys().collect(); + keys.sort(); + for key in keys { + let value = parsed.raw.get(key).unwrap_or_default(); + if TYPED.iter().any(|t| t.2 == key) || defaults.raw.get(key) == Some(value) { + continue; + } + extra.insert(key.clone(), loose_value(value)); + } + table.insert("properties".into(), toml::Value::Table(extra)); + let config: Self = table.try_into().map_err(|e| e.to_string())?; + config.check()?; + Ok(config) + } +} + +/// `server.toml` for a configuration: the template's comments with this configuration's values. +pub fn render(config: &Config) -> String { + let mut doc: toml_edit::DocumentMut = TEMPLATE.parse().expect("the template parses"); + let table = toml::Table::try_from(config).expect("a configuration is a table"); + for (section, field, _) in TYPED { + set(&mut doc, section, field, &table[section][field]); + } + for (key, value) in &config.properties { + set(&mut doc, "properties", key, value); + } + for field in ["path", "resources", "restart_on_crash"] { + set(&mut doc, "engine", field, &table["engine"][field]); + } + doc.to_string() +} + +/// After the game stopped: copies into `server.toml` the keys it wrote that the game changed in +/// `server.properties` (`/whitelist on` stores `white-list`), keeping the owner's comments. Returns the keys +/// copied. +pub fn sync_back(dir: &Path, written: &[(String, String)]) -> Result, String> { + let Ok(now) = read_properties(&dir.join(PROPERTIES)) else { + return Ok(Vec::new()); + }; + let changed: Vec<(&str, &str)> = written + .iter() + .filter_map(|(key, value)| { + now.get(key) + .filter(|v| v != value) + .map(|v| (key.as_str(), v)) + }) + .collect(); + if changed.is_empty() { + return Ok(Vec::new()); + } + let path = dir.join(FILE); + let text = std::fs::read_to_string(&path).map_err(|e| e.to_string())?; + let mut doc: toml_edit::DocumentMut = text.parse().map_err(|e| format!("{e}"))?; + let defaults = toml::Table::try_from(Config::default()).map_err(|e| e.to_string())?; + for (key, value) in &changed { + match TYPED.iter().find(|t| t.2 == *key) { + Some((section, field, _)) => { + if let Some(v) = typed_value(value, &defaults[*section][*field]) { + set(&mut doc, section, field, &v); + } + } + None => set(&mut doc, "properties", key, &loose_value(value)), + } + } + let updated = doc.to_string(); + Config::parse(&updated)?; + std::fs::write(&path, updated).map_err(|e| e.to_string())?; + Ok(changed.iter().map(|(k, _)| (*k).to_owned()).collect()) +} + +/// Sets one typed setting in `server.toml` (`whitelist on`), keeping the owner's comments. +pub fn update(dir: &Path, section: &str, field: &str, value: toml::Value) -> Result<(), String> { + let path = dir.join(FILE); + let text = std::fs::read_to_string(&path).map_err(|e| format!("{}: {e}", path.display()))?; + let mut doc: toml_edit::DocumentMut = text.parse().map_err(|e| format!("{e}"))?; + set(&mut doc, section, field, &value); + let updated = doc.to_string(); + Config::parse(&updated)?; + std::fs::write(&path, updated).map_err(|e| e.to_string()) +} + +pub fn read_properties(path: &Path) -> Result { + let bytes = std::fs::read(path).map_err(|e| e.to_string())?; + Properties::load_file(&bytes).map_err(|e| format!("{}: {e}", path.display())) +} + +/// Sets one value in a TOML document, keeping the comment after the old value. +fn set(doc: &mut toml_edit::DocumentMut, section: &str, key: &str, value: &toml::Value) { + let Some(table) = doc + .entry(section) + .or_insert_with(toml_edit::table) + .as_table_mut() + else { + return; + }; + let mut new = match value { + toml::Value::String(s) => toml_edit::value(s.as_str()), + toml::Value::Integer(n) => toml_edit::value(*n), + toml::Value::Float(f) => toml_edit::value(*f), + toml::Value::Boolean(b) => toml_edit::value(*b), + other => toml_edit::value(other.to_string()), + }; + if let (Some(old), Some(v)) = ( + table.get(key).and_then(|i| i.as_value()), + new.as_value_mut(), + ) { + *v.decor_mut() = old.decor().clone(); + } + table.insert(key, new); +} + +/// How a TOML value reads in server.properties. +fn property_text(value: &toml::Value) -> String { + match value { + toml::Value::String(s) => s.clone(), + other => other.to_string(), + } +} + +/// A server.properties value as the TOML type of `like`. +fn typed_value(text: &str, like: &toml::Value) -> Option { + Some(match like { + toml::Value::Boolean(_) => toml::Value::Boolean(text.eq_ignore_ascii_case("true")), + toml::Value::Integer(_) => toml::Value::Integer(text.trim().parse().ok()?), + _ => toml::Value::String(text.to_owned()), + }) +} + +/// A server.properties value for `[properties]`: a boolean or a number when it reads back the same. +fn loose_value(text: &str) -> toml::Value { + match text { + "true" => toml::Value::Boolean(true), + "false" => toml::Value::Boolean(false), + _ => match text.parse::() { + Ok(n) if n.to_string() == text => toml::Value::Integer(n), + _ => toml::Value::String(text.to_owned()), + }, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn properties(pairs: &[(&str, &str)]) -> Properties { + let mut p = Properties::default(); + for (k, v) in pairs { + p.put(k, (*v).to_owned()); + } + p + } + + #[test] + fn template_is_the_default() { + assert_eq!(Config::parse(TEMPLATE).unwrap(), Config::default()); + assert_eq!(render(&Config::default()), TEMPLATE); + } + + #[test] + fn defaults_are_vanilla() { + // Every typed default is what vanilla 26.3 writes for a missing key. + let vanilla = + ServerProperties::new(Properties::default(), &mut SystemEntropy::default()).unwrap(); + for (key, value) in Config::default().vanilla() { + assert_eq!(vanilla.raw.get(&key), Some(value.as_str()), "{key}"); + } + } + + #[test] + fn import_keeps_what_differs() { + let source = properties(&[ + ("motd", "Hello"), + ("server-port", "25600"), + ("white-list", "false"), + ("gamemode", "1"), + ("level-seed", "12345"), + ("spawn-protection", "0"), + ("allow-flight", "false"), + ("rate-limit", "10"), + ]); + let c = Config::import(&source).unwrap(); + assert_eq!(c.server.motd, "Hello"); + assert_eq!(c.server.port, 25600); + assert!(!c.server.whitelist); + assert_eq!(c.world.game_mode, "creative"); + assert_eq!(c.world.seed, "12345"); + // allow-flight=false is vanilla's default: dropped. + assert_eq!( + c.properties, + BTreeMap::from([ + ("rate-limit".to_owned(), toml::Value::Integer(10)), + ("spawn-protection".to_owned(), toml::Value::Integer(0)), + ]) + ); + let text = render(&c); + assert!(text.contains("spawn-protection = 0"), "{text}"); + assert!(text.contains("port = 25600"), "{text}"); + assert_eq!(Config::parse(&text).unwrap(), c); + } + + #[test] + fn seed_may_be_a_number() { + let c = Config::parse("[world]\nseed = -42\n").unwrap(); + assert_eq!(c.world.seed, "-42"); + } + + #[test] + fn rejects_mistakes() { + assert!(Config::parse("[world]\ngame_mode = \"creatve\"\n").is_err()); + assert!(Config::parse("[server]\nprot = 1\n").is_err()); + assert!(Config::parse("[properties]\nmotd = \"x\"\n").is_err()); + assert!(Config::parse("[world]\nname = \"../x\"\n").is_err()); + } + + #[test] + fn writes_properties_and_syncs_back() { + let dir = + std::env::temp_dir().join(format!("horizon-server-config-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let mut c = Config::default(); + c.properties + .insert("spawn-protection".into(), toml::Value::Integer(0)); + std::fs::write(dir.join(FILE), render(&c)).unwrap(); + std::fs::write(dir.join(PROPERTIES), "rcon.port=25576\nmotd=old\n").unwrap(); + let written = c.write_properties(&dir).unwrap(); + let p = read_properties(&dir.join(PROPERTIES)).unwrap(); + assert_eq!(p.get("motd"), Some("A Minecraft Server")); + assert_eq!(p.get("rcon.port"), Some("25576"), "other keys are kept"); + assert_eq!(p.get("spawn-protection"), Some("0")); + // The game turns the whitelist off and changes spawn protection. + let mut p = p; + p.put("white-list", "false".into()); + p.put("spawn-protection", "4".into()); + std::fs::write(dir.join(PROPERTIES), p.store(None, "date", false)).unwrap(); + let mut changed = sync_back(&dir, &written).unwrap(); + changed.sort(); + assert_eq!(changed, ["spawn-protection", "white-list"]); + let text = std::fs::read_to_string(dir.join(FILE)).unwrap(); + assert!( + text.contains("whitelist = false # only whitelisted"), + "the comment stays: {text}" + ); + let back = Config::parse(&text).unwrap(); + assert!(!back.server.whitelist); + assert_eq!(back.properties["spawn-protection"], toml::Value::Integer(4)); + std::fs::remove_dir_all(&dir).unwrap(); + } +} diff --git a/crates/horizon-server/src/engine.rs b/crates/horizon-server/src/engine.rs new file mode 100644 index 000000000..41f71f433 --- /dev/null +++ b/crates/horizon-server/src/engine.rs @@ -0,0 +1,127 @@ +//! The engine: the game itself, run headless (`horizon-client --dedicated`, crates/horizon-client +//! game/dedicated.rs). It reads the vanilla files the supervisor writes, takes console commands on stdin and +//! logs on stdout. + +use crate::config::Config; +use std::{ + path::{Path, PathBuf}, + process::{Child, Command, Stdio}, +}; + +/// The game's program names, most specific first: a headless engine once there is one, else the game. +const PROGRAMS: [&str; 2] = ["horizon-engine", "horizon-client"]; + +fn exe(name: &str) -> String { + format!("{name}{}", std::env::consts::EXE_SUFFIX) +} + +/// The game program: `engine.path`, else one installed beside `horizon-server`, else one on the PATH. +pub fn program(config: &Config, dir: &Path) -> Result { + if !config.engine.path.is_empty() { + let path = dir.join(&config.engine.path); + return path + .is_file() + .then_some(path) + .ok_or_else(|| format!("engine.path {} is not a file", config.engine.path)); + } + let beside = std::env::current_exe() + .ok() + .and_then(|e| e.parent().map(Path::to_path_buf)); + let path_dirs = std::env::var_os("PATH") + .map(|p| std::env::split_paths(&p).collect::>()) + .unwrap_or_default(); + PROGRAMS + .iter() + .flat_map(|name| { + beside + .iter() + .chain(&path_dirs) + .map(move |d| d.join(exe(name))) + }) + .find(|p| p.is_file()) + .ok_or_else(|| { + "the game program (horizon-client) is neither beside horizon-server nor on the PATH: \ + install it there, or set engine.path in server.toml" + .into() + }) +} + +/// Where the prepared game files may be, in the order they are tried. +pub fn resource_candidates(config: &Config, dir: &Path, program: Option<&Path>) -> Vec { + if !config.engine.resources.is_empty() { + return vec![dir.join(&config.engine.resources)]; + } + let version = "26.3"; + let mut out = vec![dir.join("resources")]; + // A release folder or a checkout: .local/horizon-client/ beside the program or above it. + if let Some(program) = program { + for ancestor in program.ancestors().skip(1).take(4) { + out.push(ancestor.join(".local/horizon-client").join(version)); + } + } + out +} + +/// The prepared game files: a folder holding the asset index `horizon-prepare` writes. +pub fn resources(config: &Config, dir: &Path, program: Option<&Path>) -> Result { + let candidates = resource_candidates(config, dir, program); + candidates + .iter() + .find(|d| d.join("asset-index.json").is_file()) + .cloned() + .ok_or_else(|| { + let tried: Vec = candidates + .iter() + .map(|d| format!(" {}", d.display())) + .collect(); + format!( + "no prepared game files. Horizon reads them from your own copy of Minecraft 26.3:\n\ + prepare them with `horizon-prepare --prepare --server-jar PATH` (or the launcher) and copy \ + the folder to resources/ here, or set engine.resources in server.toml. Looked in:\n{}", + tried.join("\n") + ) + }) +} + +/// Starts the engine in the server folder, with its console and log piped to the supervisor. +pub fn spawn(program: &Path, resources: &Path, dir: &Path) -> std::io::Result { + let mut command = Command::new(program); + command + .arg("--resources") + .arg(resources) + .args(["--dedicated", "--nogui"]) + .current_dir(dir) + .env("HORIZON_NO_AUDIO", "1") + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()); + // The terminal's Ctrl-C reaches the supervisor alone, which then stops the game cleanly. + #[cfg(unix)] + std::os::unix::process::CommandExt::process_group(&mut command, 0); + #[cfg(windows)] + std::os::windows::process::CommandExt::creation_flags( + &mut command, + windows_sys::Win32::System::Threading::CREATE_NEW_PROCESS_GROUP, + ); + command.spawn() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn resources_are_searched_in_order() { + let mut config = Config::default(); + let dir = Path::new("/srv/mc"); + let program = Path::new("/opt/horizon/target/release/horizon-client"); + let found = resource_candidates(&config, dir, Some(program)); + assert_eq!(found[0], Path::new("/srv/mc/resources")); + assert!(found.contains(&PathBuf::from("/opt/horizon/.local/horizon-client/26.3"))); + config.engine.resources = "/data/res".into(); + assert_eq!( + resource_candidates(&config, dir, Some(program)), + [PathBuf::from("/data/res")] + ); + } +} diff --git a/crates/horizon-server/src/init.rs b/crates/horizon-server/src/init.rs new file mode 100644 index 000000000..51d8abaf7 --- /dev/null +++ b/crates/horizon-server/src/init.rs @@ -0,0 +1,276 @@ +//! `horizon-server init`: the first run (docs/server.md, section 3). It asks about the EULA, the world, the +//! port and who may join, imports an existing `server.properties`, finds the game, and writes `server.toml`. +//! Every question has a flag, so it also runs unattended (Docker, scripts). + +use crate::{config, config::Config, engine}; +use horizon_server_files::{ + eula, + java_properties::now_millis, + user_lists::{NameAndId, OpEntry, OpList, WhiteEntry, WhiteList}, +}; +use std::{ + io::{BufRead, IsTerminal, Write}, + path::Path, +}; + +/// The answers given as flags; what is missing is asked, or defaulted with `yes`. +#[derive(Default)] +pub struct Answers { + pub eula: bool, + pub world: Option, + pub seed: Option, + pub port: Option, + pub whitelist: Option, + pub players: Vec, + pub op: Option, + /// Take the default for every question not answered by a flag. + pub yes: bool, +} + +struct Prompt { + interactive: bool, +} + +impl Prompt { + fn ask(&self, question: &str, default: &str) -> String { + if !self.interactive { + return default.to_owned(); + } + if default.is_empty() { + print!("{question}: "); + } else { + print!("{question} [{default}]: "); + } + let _ = std::io::stdout().flush(); + let mut line = String::new(); + if std::io::stdin().lock().read_line(&mut line).unwrap_or(0) == 0 { + return default.to_owned(); + } + match line.trim() { + "" => default.to_owned(), + answer => answer.to_owned(), + } + } + fn yes(&self, question: &str, default: bool) -> bool { + let answer = self.ask( + &format!("{question} ({})", if default { "Y/n" } else { "y/N" }), + "", + ); + match answer.to_ascii_lowercase().as_str() { + "" => default, + a => a.starts_with('y'), + } + } +} + +pub fn run(dir: &Path, answers: Answers) -> Result<(), String> { + std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?; + let toml_path = dir.join(config::FILE); + if toml_path.exists() { + return Err(format!( + "{} already exists: this server is set up. Edit it, or start the server with `horizon-server run`", + toml_path.display() + )); + } + let prompt = Prompt { + interactive: !answers.yes && std::io::stdin().is_terminal(), + }; + + // An existing vanilla server folder: its settings become server.toml. + let properties = dir.join(config::PROPERTIES); + let mut cfg = if properties.exists() { + let source = config::read_properties(&properties)?; + let cfg = Config::import(&source)?; + let kept = dir.join("server.properties.imported"); + std::fs::copy(&properties, &kept).map_err(|e| e.to_string())?; + println!( + "Imported server.properties into server.toml (the original is kept as {}).", + kept.display() + ); + cfg + } else { + Config::default() + }; + + // 1. The EULA: only a yes writes eula=true. + let eula_path = dir.join("eula.txt"); + let agreed = eula::agreed(&eula_path).unwrap_or(false); + if !agreed { + println!( + "Minecraft's End User License Agreement applies to running a server: {}", + eula::EULA_LINK + ); + let yes = answers.eula || (prompt.interactive && prompt.yes("Do you agree to it?", false)); + if !yes { + let _ = std::fs::write(&eula_path, eula::file(now_millis(), false)); + return Err( + "the server can't run until you agree to the EULA: run init again and answer yes, \ + or pass --eula" + .into(), + ); + } + std::fs::write(&eula_path, eula::file(now_millis(), true)).map_err(|e| e.to_string())?; + } + + // 2. The world: an existing one keeps its seed. + cfg.world.name = answers + .world + .unwrap_or_else(|| prompt.ask("World name", &cfg.world.name)); + if dir.join(&cfg.world.name).join("level.dat").exists() { + println!("Using the existing world in {}.", cfg.world.name); + } else { + cfg.world.seed = answers + .seed + .unwrap_or_else(|| prompt.ask("Seed (empty for a random one)", &cfg.world.seed)); + } + + // 3. The port, checked free now rather than at the first start. + cfg.server.port = match answers.port { + Some(port) => port, + None => prompt + .ask("Port", &cfg.server.port.to_string()) + .parse() + .map_err(|_| "the port must be a number from 1 to 65535".to_owned())?, + }; + if std::net::TcpListener::bind(("0.0.0.0", cfg.server.port)).is_err() { + println!( + "Port {} is in use right now: stop what uses it, or change server.port in server.toml.", + cfg.server.port + ); + } + + // 4. Who may join. + cfg.server.whitelist = answers.whitelist.unwrap_or_else(|| { + prompt.yes( + "Only let in players you list (whitelist)?", + cfg.server.whitelist, + ) + }); + let mut players = answers.players; + if players.is_empty() && cfg.server.whitelist { + players = prompt + .ask("Players to let in (names, separated by commas)", "") + .split([',', ' ']) + .filter(|n| !n.is_empty()) + .map(str::to_owned) + .collect(); + } + let op = answers.op.or_else(|| { + let first = players.first()?; + prompt + .yes(&format!("Make {first} an operator?"), true) + .then(|| first.clone()) + }); + add_players(dir, &players, op.as_deref())?; + + // 5. The game and its files. + match engine::program(&cfg, dir) { + Ok(program) => { + println!("Game: {}", program.display()); + match engine::resources(&cfg, dir, Some(&program)) { + Ok(resources) => println!("Game files: {}", resources.display()), + Err(e) => println!("{e}"), + } + } + Err(e) => println!("{e}"), + } + + std::fs::write(&toml_path, config::render(&cfg)).map_err(|e| e.to_string())?; + println!( + "Wrote {}. Start the server with: horizon-server run --dir {}", + toml_path.display(), + dir.display() + ); + if cfg.server.online_mode { + println!( + "Note: Horizon's server doesn't check Mojang accounts yet (online mode), so it runs offline: \ + keep the whitelist on, or play on a LAN or a tailnet." + ); + } + Ok(()) +} + +/// Adds players to the whitelist (and one as an operator) in vanilla's files, with offline UUIDs as the +/// server runs offline. +fn add_players(dir: &Path, players: &[String], op: Option<&str>) -> Result<(), String> { + if !players.is_empty() { + let mut white = WhiteList::new(dir.join("whitelist.json")); + let _ = white.load(); + for name in players { + white.add(WhiteEntry { + user: NameAndId::offline(name), + }); + } + println!("Whitelisted: {}", players.join(", ")); + } + if let Some(name) = op { + let mut ops = OpList::new(dir.join("ops.json")); + let _ = ops.load(); + ops.add(OpEntry { + user: NameAndId::offline(name), + level: 4, + bypasses_player_limit: false, + }); + println!("Operator: {name}"); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn unattended_init_writes_everything() { + let dir = std::env::temp_dir().join(format!("horizon-server-init-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let answers = Answers { + eula: true, + world: Some("survival".into()), + seed: Some("12345".into()), + port: Some(25599), + whitelist: Some(true), + players: vec!["Alex".into(), "Steve".into()], + op: Some("Alex".into()), + yes: true, + }; + run(&dir, answers).unwrap(); + let cfg = Config::load(&dir).unwrap(); + assert_eq!( + ( + cfg.world.name.as_str(), + cfg.world.seed.as_str(), + cfg.server.port + ), + ("survival", "12345", 25599) + ); + assert!(eula::agreed(&dir.join("eula.txt")).unwrap()); + let white = std::fs::read_to_string(dir.join("whitelist.json")).unwrap(); + assert!( + white.contains("\"Alex\"") && white.contains("\"Steve\""), + "{white}" + ); + let ops = std::fs::read_to_string(dir.join("ops.json")).unwrap(); + assert!( + ops.contains("\"Alex\"") && ops.contains("\"level\": 4"), + "{ops}" + ); + // A second init refuses to overwrite the configuration. + assert!(run(&dir, Answers::default()).is_err()); + std::fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn no_eula_no_server() { + let dir = std::env::temp_dir().join(format!("horizon-server-eula-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let answers = Answers { + yes: true, + ..Answers::default() + }; + assert!(run(&dir, answers).unwrap_err().contains("EULA")); + assert!(!dir.join(config::FILE).exists()); + assert!(!eula::agreed(&dir.join("eula.txt")).unwrap()); + std::fs::remove_dir_all(&dir).unwrap(); + } +} diff --git a/crates/horizon-server/src/lists.rs b/crates/horizon-server/src/lists.rs new file mode 100644 index 000000000..b0dc5a375 --- /dev/null +++ b/crates/horizon-server/src/lists.rs @@ -0,0 +1,153 @@ +//! `op`, `deop` and `whitelist` while the server is stopped: they edit vanilla's files with the code the game +//! reads them with (horizon-server-files) and answer with vanilla's console messages. While it runs, the game +//! owns the lists, so the same commands are typed in its console instead. + +use crate::{config, supervisor}; +use horizon_server_files::user_lists::{NameAndId, OpEntry, OpList, WhiteEntry, WhiteList}; +use std::path::Path; + +pub fn run(dir: &Path, command: &str, args: &[String]) -> Result<(), String> { + let config = config::Config::load(dir)?; + // Holding the folder's lock keeps the server from starting halfway through. + let _lock = supervisor::lock(dir).map_err(|_| { + format!( + "the server is running: type `{command} {}` in its console", + args.join(" ") + ) + })?; + let args: Vec<&str> = args.iter().map(String::as_str).collect(); + let ops_path = dir.join("ops.json"); + let white_path = dir.join("whitelist.json"); + let message = match (command, args.as_slice()) { + ("op", [name]) => { + let mut ops = load(OpList::new(ops_path))?; + let user = NameAndId::offline(name); + if ops.contains(&user) { + "Nothing changed. The player already is an operator".to_owned() + } else { + ops.add(OpEntry { + user, + level: 4, + bypasses_player_limit: false, + }); + format!("Made {name} a server operator") + } + } + ("deop", [name]) => { + let mut ops = load(OpList::new(ops_path))?; + if ops.remove(&NameAndId::offline(name)) { + format!("Made {name} no longer a server operator") + } else { + "Nothing changed. The player is not an operator".to_owned() + } + } + ("whitelist", ["add", name]) => { + let mut white = load(WhiteList::new(white_path))?; + let user = NameAndId::offline(name); + if white.contains(&user) { + "Player is already whitelisted".to_owned() + } else { + white.add(WhiteEntry { user }); + format!("Added {name} to the whitelist") + } + } + ("whitelist", ["remove", name]) => { + let mut white = load(WhiteList::new(white_path))?; + if white.remove(&NameAndId::offline(name)) { + format!("Removed {name} from the whitelist") + } else { + "Player is not whitelisted".to_owned() + } + } + ("whitelist", [state @ ("on" | "off")]) => { + let on = *state == "on"; + match (on, config.server.whitelist) { + (true, true) => "Whitelist is already turned on".to_owned(), + (false, false) => "Whitelist is already turned off".to_owned(), + _ => { + config::update(dir, "server", "whitelist", toml::Value::Boolean(on))?; + format!("Whitelist is now turned {state}") + } + } + } + ("whitelist", ["list"]) => { + let white = load(WhiteList::new(white_path))?; + let names: Vec = white + .entries() + .iter() + .map(|e| e.user.name.clone()) + .collect(); + let state = if config.server.whitelist { "on" } else { "off" }; + if names.is_empty() { + format!("There are no whitelisted players (the whitelist is {state})") + } else { + format!( + "There are {} whitelisted player(s): {} (the whitelist is {state})", + names.len(), + names.join(", ") + ) + } + } + _ => { + return Err( + "use: op NAME, deop NAME, whitelist on|off|list, whitelist add|remove NAME".into(), + ); + } + }; + println!("{message}"); + Ok(()) +} + +/// A list from its file; a missing file is an empty list, a broken one an error (vanilla would replace it). +fn load( + mut list: horizon_server_files::user_lists::UserList, +) -> Result, String> { + if list.file.exists() { + list.load() + .map_err(|e| format!("{}: {e}", list.file.display()))?; + } + Ok(list) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn edits_the_lists_while_stopped() { + let dir = std::env::temp_dir().join(format!("horizon-server-lists-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join(config::FILE), config::TEMPLATE).unwrap(); + let s = |v: &[&str]| v.iter().map(|a| (*a).to_owned()).collect::>(); + run(&dir, "op", &s(&["Alex"])).unwrap(); + run(&dir, "whitelist", &s(&["add", "Steve"])).unwrap(); + run(&dir, "whitelist", &s(&["off"])).unwrap(); + assert!( + std::fs::read_to_string(dir.join("ops.json")) + .unwrap() + .contains("Alex") + ); + assert!( + std::fs::read_to_string(dir.join("whitelist.json")) + .unwrap() + .contains("Steve") + ); + assert!(!config::Config::load(&dir).unwrap().server.whitelist); + run(&dir, "deop", &s(&["Alex"])).unwrap(); + assert!( + !std::fs::read_to_string(dir.join("ops.json")) + .unwrap() + .contains("Alex") + ); + // A running server owns the lists. + let lock = supervisor::lock(&dir).unwrap(); + assert!( + run(&dir, "op", &s(&["Alex"])) + .unwrap_err() + .contains("running") + ); + drop(lock); + std::fs::remove_dir_all(&dir).unwrap(); + } +} diff --git a/crates/horizon-server/src/main.rs b/crates/horizon-server/src/main.rs new file mode 100644 index 000000000..43d08589b --- /dev/null +++ b/crates/horizon-server/src/main.rs @@ -0,0 +1,117 @@ +//! `horizon-server`: host a Horizon server (docs/server.md). It keeps the server's settings in `server.toml`, +//! runs the game headless as the engine, and manages the vanilla files around it. + +mod config; +mod engine; +mod init; +mod lists; +mod signals; +mod supervisor; + +use std::{path::PathBuf, process::ExitCode}; + +const HELP: &str = "\ +horizon-server: host a Horizon (Minecraft Java Edition 26.3) server + +Usage: horizon-server [--dir DIR] + + init Set up a server here: the EULA, the world, the port, who may join (asks, or takes flags: + --eula --world NAME --seed SEED --port N --whitelist/--no-whitelist --player NAME... --op NAME + --yes) + run Run the server in the foreground; type console commands, Ctrl-C stops it cleanly. It + restarts the game if it crashes. + import FILE Write server.toml from a vanilla server.properties + op NAME, deop NAME + whitelist on|off|list, whitelist add|remove NAME + Change who may join while the server is stopped (while it runs, type the same command + in its console) + + --dir DIR The server folder (default: the current folder) + +Settings live in server.toml; the server writes server.properties from it before every start. +"; + +fn main() -> ExitCode { + let mut args: Vec = std::env::args().skip(1).collect(); + let mut dir = PathBuf::from("."); + if let Some(i) = args.iter().position(|a| a == "--dir") { + if i + 1 >= args.len() { + eprintln!("horizon-server: --dir needs a folder"); + return ExitCode::from(2); + } + dir = PathBuf::from(args.remove(i + 1)); + args.remove(i); + } + let result = match args.first().map(String::as_str) { + None | Some("help" | "-h" | "--help") => { + print!("{HELP}"); + Ok(()) + } + Some("version" | "-V" | "--version") => { + println!("horizon-server {}", env!("CARGO_PKG_VERSION")); + Ok(()) + } + Some("init") => init_answers(&args[1..]).and_then(|a| init::run(&dir, a)), + Some("run") => supervisor::run(&dir), + Some("import") => import(&dir, &args[1..]), + Some(command @ ("op" | "deop" | "whitelist")) => lists::run(&dir, command, &args[1..]), + Some(other) => Err(format!( + "unknown command {other}; `horizon-server help` lists them" + )), + }; + match result { + Ok(()) => ExitCode::SUCCESS, + Err(e) => { + eprintln!("horizon-server: {e}"); + ExitCode::FAILURE + } + } +} + +fn init_answers(args: &[String]) -> Result { + let mut answers = init::Answers::default(); + let mut it = args.iter(); + while let Some(arg) = it.next() { + let mut value = |flag: &str| { + it.next() + .cloned() + .ok_or_else(|| format!("{flag} needs a value")) + }; + match arg.as_str() { + "--eula" => answers.eula = true, + "--yes" | "-y" => answers.yes = true, + "--world" => answers.world = Some(value(arg)?), + "--seed" => answers.seed = Some(value(arg)?), + "--port" => { + answers.port = Some( + value(arg)? + .parse() + .map_err(|_| "--port needs a number from 1 to 65535")?, + ); + } + "--whitelist" => answers.whitelist = Some(true), + "--no-whitelist" => answers.whitelist = Some(false), + "--player" => answers.players.push(value(arg)?), + "--op" => answers.op = Some(value(arg)?), + other => return Err(format!("init: unknown option {other}")), + } + } + Ok(answers) +} + +fn import(dir: &std::path::Path, args: &[String]) -> Result<(), String> { + let [source] = args else { + return Err("import needs the server.properties to read".into()); + }; + let target = dir.join(config::FILE); + if target.exists() { + return Err(format!( + "{} already exists; move it away first", + target.display() + )); + } + let cfg = config::Config::import(&config::read_properties(std::path::Path::new(source))?)?; + std::fs::write(&target, config::render(&cfg)).map_err(|e| e.to_string())?; + println!("Wrote {}", target.display()); + Ok(()) +} diff --git a/crates/horizon-server/src/signals.rs b/crates/horizon-server/src/signals.rs new file mode 100644 index 000000000..11222257c --- /dev/null +++ b/crates/horizon-server/src/signals.rs @@ -0,0 +1,41 @@ +//! Stop requests from outside: Ctrl-C in the terminal, SIGTERM from systemd or launchd, SIGHUP when the +//! terminal closes, the console window closing on Windows. The handler only counts them; the supervisor +//! sees the count and stops the game cleanly (a second request stops it at once). + +use std::sync::atomic::{AtomicU32, Ordering}; + +static REQUESTS: AtomicU32 = AtomicU32::new(0); + +/// How many stop requests arrived. +pub fn requests() -> u32 { + REQUESTS.load(Ordering::SeqCst) +} + +#[cfg(unix)] +pub fn install() { + extern "C" fn handle(_: libc::c_int) { + REQUESTS.fetch_add(1, Ordering::SeqCst); + } + let handler = handle as extern "C" fn(libc::c_int); + for signal in [libc::SIGINT, libc::SIGTERM, libc::SIGHUP] { + // SAFETY: the handler only increments an atomic, which is async-signal-safe. + unsafe { + libc::signal(signal, handler as libc::sighandler_t); + } + } +} + +#[cfg(windows)] +pub fn install() { + unsafe extern "system" fn handle(_: u32) -> windows_sys::core::BOOL { + REQUESTS.fetch_add(1, Ordering::SeqCst); + 1 + } + // SAFETY: the handler only increments an atomic; it stays valid for the life of the process. + unsafe { + windows_sys::Win32::System::Console::SetConsoleCtrlHandler(Some(handle), 1); + } +} + +#[cfg(not(any(unix, windows)))] +pub fn install() {} diff --git a/crates/horizon-server/src/supervisor.rs b/crates/horizon-server/src/supervisor.rs new file mode 100644 index 000000000..376c4835e --- /dev/null +++ b/crates/horizon-server/src/supervisor.rs @@ -0,0 +1,255 @@ +//! `horizon-server run`: writes `server.properties` from `server.toml`, runs the engine with the console on +//! stdin, stops it cleanly on Ctrl-C or SIGTERM, and restarts it when it crashes (docs/server.md, section 7). + +use crate::{config, config::Config, engine, signals}; +use horizon_server_files::java_properties::now_millis; +use std::{ + fs::File, + io::{BufRead, BufReader, Read, Write}, + path::Path, + process::{Child, ExitStatus}, + sync::mpsc, + thread, + time::{Duration, Instant}, +}; + +/// After this many crashes within [`CRASH_WINDOW`] the supervisor stops restarting the game. +const MAX_CRASHES: usize = 5; +const CRASH_WINDOW: Duration = Duration::from_secs(600); +/// The first wait before a restart; it doubles after each crash, up to [`MAX_BACKOFF`]. +const FIRST_BACKOFF: Duration = Duration::from_secs(5); +const MAX_BACKOFF: Duration = Duration::from_secs(300); +/// How long `stop` may take before the game is killed. +const STOP_TIMEOUT: Duration = Duration::from_secs(120); + +/// A line from the supervisor, in the game's log format (`[HH:mm:ss] [thread/LEVEL]: message`, UTC). +pub fn note(level: &str, message: &str) { + let secs = now_millis().div_euclid(1000).rem_euclid(86_400); + println!( + "[{:02}:{:02}:{:02}] [Supervisor/{level}]: {message}", + secs / 3600, + secs / 60 % 60, + secs % 60 + ); +} + +/// The folder's lock: one supervisor per server folder. Released when the process ends, even by a crash. +pub fn lock(dir: &Path) -> Result { + let state = dir.join(".horizon"); + std::fs::create_dir_all(&state).map_err(|e| format!("{}: {e}", state.display()))?; + let file = File::options() + .create(true) + .truncate(false) + .write(true) + .open(state.join("lock")) + .map_err(|e| e.to_string())?; + match file.try_lock() { + Ok(()) => Ok(file), + Err(std::fs::TryLockError::WouldBlock) => { + Err(format!("a server is already running in {}", dir.display())) + } + Err(std::fs::TryLockError::Error(e)) => Err(e.to_string()), + } +} + +enum Exit { + /// Asked to stop, or the game ended by itself without an error (`stop` typed in its console, the EULA + /// not agreed, the port taken): not restarted. + Stopped, + Crashed(ExitStatus), +} + +pub fn run(dir: &Path) -> Result<(), String> { + signals::install(); + let config = Config::load(dir)?; + let program = engine::program(&config, dir)?; + let resources = engine::resources(&config, dir, Some(&program))?; + let _lock = lock(dir)?; + let console = console_lines(); + let mut crashes: Vec = Vec::new(); + loop { + // Read again before every start: edits to server.toml apply on the next restart. + let config = Config::load(dir)?; + let written = config + .write_properties(dir) + .map_err(|e| format!("server.properties: {e}"))?; + note( + "INFO", + &format!( + "Starting {} with the game files in {}", + program.display(), + resources.display() + ), + ); + let mut child = engine::spawn(&program, &resources, dir) + .map_err(|e| format!("{}: {e}", program.display()))?; + let exit = supervise(&mut child, &console); + match config::sync_back(dir, &written) { + Ok(keys) if !keys.is_empty() => note( + "INFO", + &format!( + "Copied into server.toml what the game changed: {}", + keys.join(", ") + ), + ), + Ok(_) => {} + Err(e) => note("WARN", &format!("Could not update server.toml: {e}")), + } + let status = match exit { + Exit::Stopped => return Ok(()), + Exit::Crashed(status) => status, + }; + if !config.engine.restart_on_crash { + return Err(format!( + "the game stopped unexpectedly ({status}); engine.restart_on_crash is off" + )); + } + let now = Instant::now(); + crashes.retain(|t| now.duration_since(*t) < CRASH_WINDOW); + crashes.push(now); + if crashes.len() >= MAX_CRASHES { + return Err(format!( + "the game stopped unexpectedly {MAX_CRASHES} times in {} minutes: not restarting it. \ + See logs/latest.log and crash-reports/", + CRASH_WINDOW.as_secs() / 60 + )); + } + let wait = backoff(crashes.len()); + note( + "WARN", + &format!( + "The game stopped unexpectedly ({status}); restarting in {} s", + wait.as_secs() + ), + ); + let until = Instant::now() + wait; + while Instant::now() < until { + if signals::requests() > 0 { + return Ok(()); + } + thread::sleep(Duration::from_millis(100)); + } + } +} + +/// The wait before the restart that follows the `crashes`th recent crash. +fn backoff(crashes: usize) -> Duration { + let doublings = u32::try_from(crashes.saturating_sub(1)) + .unwrap_or(u32::MAX) + .min(16); + (FIRST_BACKOFF * 2u32.pow(doublings)).min(MAX_BACKOFF) +} + +/// The supervisor's own stdin, line by line (nothing when it has none, as under a service manager). +fn console_lines() -> mpsc::Receiver { + let (tx, rx) = mpsc::channel(); + let _ = thread::Builder::new() + .name("console".into()) + .spawn(move || { + for line in std::io::stdin().lock().lines() { + let Ok(line) = line else { break }; + if tx.send(line).is_err() { + break; + } + } + }); + rx +} + +/// Copies the game's output to ours, line by line. +fn pump(from: impl Read + Send + 'static, to_stderr: bool) { + let _ = thread::Builder::new() + .name("engine-log".into()) + .spawn(move || { + for line in BufReader::new(from).lines() { + let Ok(line) = line else { break }; + if to_stderr { + eprintln!("{line}"); + } else { + println!("{line}"); + } + } + }); +} + +/// Runs one engine process to its end: console lines in, the log out, and a clean `stop` when asked. +fn supervise(child: &mut Child, console: &mpsc::Receiver) -> Exit { + if let Some(out) = child.stdout.take() { + pump(out, false); + } + if let Some(err) = child.stderr.take() { + pump(err, true); + } + let mut stdin = child.stdin.take(); + let mut stopping: Option = None; + let mut handled = signals::requests(); + loop { + while let Ok(line) = console.try_recv() { + let command = line.trim().trim_start_matches('/'); + if command == "stop" && stopping.is_none() { + stopping = Some(Instant::now()); + } + if let Some(input) = stdin.as_mut() + && writeln!(input, "{line}") + .and_then(|()| input.flush()) + .is_err() + { + stdin = None; + } + } + let requests = signals::requests(); + if requests > handled { + handled = requests; + if stopping.is_none() { + note("INFO", "Stopping the server"); + stopping = Some(Instant::now()); + if let Some(input) = stdin.as_mut() { + let _ = writeln!(input, "stop").and_then(|()| input.flush()); + } + } else { + note("WARN", "Stopping the game at once, without saving"); + let _ = child.kill(); + } + } + if stopping.is_some_and(|t| t.elapsed() > STOP_TIMEOUT) { + note( + "WARN", + &format!( + "The game did not stop within {} s: killing it", + STOP_TIMEOUT.as_secs() + ), + ); + let _ = child.kill(); + } + match child.try_wait() { + Ok(Some(status)) if stopping.is_some() || status.success() => return Exit::Stopped, + Ok(Some(status)) => return Exit::Crashed(status), + Ok(None) => thread::sleep(Duration::from_millis(50)), + Err(e) => { + note("ERROR", &format!("Lost track of the game: {e}")); + return Exit::Stopped; + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn backoff_doubles_up_to_five_minutes() { + let waits: Vec = (1..=8).map(|n| backoff(n).as_secs()).collect(); + assert_eq!(waits, [5, 10, 20, 40, 80, 160, 300, 300]); + } + + #[test] + fn one_supervisor_per_folder() { + let dir = std::env::temp_dir().join(format!("horizon-server-lock-{}", std::process::id())); + let first = lock(&dir).unwrap(); + assert!(lock(&dir).unwrap_err().contains("already running")); + drop(first); + lock(&dir).unwrap(); + std::fs::remove_dir_all(&dir).unwrap(); + } +}