From c7073db8b5b54fd8f03d40dd7e03c8bc1e23d07f Mon Sep 17 00:00:00 2001 From: Cosmic <84875247+Online5277@users.noreply.github.com> Date: Fri, 16 Oct 2026 12:47:49 -0400 Subject: [PATCH 01/14] Apply falling anvil impact damage and wear --- crates/horizon-client/src/entity_nbt.rs | 45 +++- crates/horizon-client/src/falling_block.rs | 192 ++++++++++++++++++ crates/horizon-client/src/game.rs | 55 +++-- crates/horizon-client/src/game/creatures.rs | 1 + .../horizon-client/src/game/falling_damage.rs | 123 +++++++++++ crates/horizon-client/src/game/persist.rs | 21 +- crates/horizon-client/src/lib.rs | 1 + crates/horizon-client/src/mobs.rs | 7 + 8 files changed, 394 insertions(+), 51 deletions(-) create mode 100644 crates/horizon-client/src/falling_block.rs create mode 100644 crates/horizon-client/src/game/falling_damage.rs diff --git a/crates/horizon-client/src/entity_nbt.rs b/crates/horizon-client/src/entity_nbt.rs index 4e1220d91..adeb1da25 100644 --- a/crates/horizon-client/src/entity_nbt.rs +++ b/crates/horizon-client/src/entity_nbt.rs @@ -1046,12 +1046,15 @@ pub fn arrow_from_nbt( } /// `FallingBlockEntity`: BlockState, Time, DropItem, HurtEntities. +#[allow(clippy::too_many_arguments)] pub fn falling_block_to_nbt( state: Tag, position: Vec3, motion: Vec3, time: i32, drop_item: bool, + damage: crate::falling_block::Damage, + fall_distance: f64, uuid: [i32; 4], ) -> Tag { let base = Base { @@ -1061,29 +1064,27 @@ pub fn falling_block_to_nbt( motion, rotation: [0.0, 0.0], on_ground: false, - fall_distance: 0.0, + fall_distance, }; let mut tag = base.tag(None); for (key, value) in [ ("BlockState", state), ("Time", Tag::Int(time)), ("DropItem", Tag::Byte(i8::from(drop_item))), - ("HurtEntities", Tag::Byte(0)), - ("CancelDrop", Tag::Byte(0)), - ("FallHurtAmount", Tag::Float(0)), - ("FallHurtMax", Tag::Int(40)), ] { put(&mut tag, key, value); } + damage.save(&mut tag); tag } -/// (block state tag, position, motion, time) -pub fn falling_block_from_nbt(tag: &Tag) -> Option<(Tag, Vec3, Vec3, i32)> { +/// (block state tag, position, motion, time, fall distance) +pub fn falling_block_from_nbt(tag: &Tag) -> Option<(Tag, Vec3, Vec3, i32, f64)> { Some(( tag.get("BlockState")?.clone(), position(tag)?, motion(tag), number(tag.get("Time")).unwrap_or(0) as i32, + float(tag.get("fall_distance")).unwrap_or(0.0), )) } @@ -1493,6 +1494,36 @@ mod tests { use super::*; use crate::items::ItemStack; + #[test] + fn falling_block_round_trip_keeps_impact_distance_and_settings() { + let state = Tag::compound([("Name", string("minecraft:damaged_anvil"))]); + let position = Vec3::new(3.5, 100.0, -7.5); + let velocity = Vec3::new(0.0, -1.25, 0.0); + let damage = crate::falling_block::Damage { + cancel_drop: true, + ..crate::falling_block::Damage::anvil() + }; + let tag = falling_block_to_nbt( + state.clone(), + position, + velocity, + 30, + false, + damage, + 19.75, + [1, 2, 3, 4], + ); + let (loaded_state, pos, motion, age, distance) = falling_block_from_nbt(&tag).unwrap(); + assert_eq!(loaded_state, state); + assert_eq!( + (pos, motion, age, distance), + (position, velocity, 30, 19.75) + ); + assert_eq!(falling_block_flags(&tag), (false, false)); + assert_eq!(crate::falling_block::Damage::from_nbt(&tag, true), damage); + assert_eq!(uuid(&tag), Some([1, 2, 3, 4])); + } + #[test] fn item_entities_round_trip() { let e = ItemEntity { diff --git a/crates/horizon-client/src/falling_block.rs b/crates/horizon-client/src/falling_block.rs new file mode 100644 index 000000000..86c6ebd6f --- /dev/null +++ b/crates/horizon-client/src/falling_block.rs @@ -0,0 +1,192 @@ +//! FallingBlockEntity's impact damage, anvil wear and saved impact settings. +use crate::{ + mobs::{Damage as MobDamage, DamageKind, Mob}, + save::{float, number, put}, +}; +use horizon_core::geometry::{Aabb, Vec3}; +use horizon_world::{chunk::BlockState, nbt::Tag}; + +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Damage { + pub hurt_entities: bool, + pub cancel_drop: bool, + pub per_distance: f32, + pub max: i32, +} +impl Default for Damage { + fn default() -> Self { + Self { + hurt_entities: false, + cancel_drop: false, + per_distance: 0.0, + max: 40, + } + } +} +impl Damage { + pub fn anvil() -> Self { + Self { + hurt_entities: true, + per_distance: 2.0, + ..Self::default() + } + } + pub fn from_nbt(tag: &Tag, anvil: bool) -> Self { + Self { + hurt_entities: number(tag.get("HurtEntities")).map_or(anvil, |v| v != 0), + cancel_drop: number(tag.get("CancelDrop")).is_some_and(|v| v != 0), + per_distance: float(tag.get("FallHurtAmount")).unwrap_or(0.0) as f32, + max: number(tag.get("FallHurtMax")).unwrap_or(40) as i32, + } + } + pub fn save(self, tag: &mut Tag) { + for (key, value) in [ + ("HurtEntities", Tag::Byte(i8::from(self.hurt_entities))), + ("CancelDrop", Tag::Byte(i8::from(self.cancel_drop))), + ("FallHurtAmount", Tag::Float(self.per_distance.to_bits())), + ("FallHurtMax", Tag::Int(self.max)), + ] { + put(tag, key, value); + } + } + pub fn impact(self, fall_distance: f64) -> Option { + if !self.hurt_entities { + return None; + } + let steps = (fall_distance - 1.0).ceil() as i32; + if steps < 0 { + return None; + } + let amount = ((steps as f32 * self.per_distance).floor() as i32).min(self.max) as f32; + Some(Impact { + amount, + wear_chance: if amount > 0.0 { + 0.05 + steps as f32 * 0.05 + } else { + 0.0 + }, + }) + } +} + +#[derive(Clone, Copy, Debug)] +pub struct Impact { + pub amount: f32, + pub wear_chance: f32, +} + +/// AnvilBlock.damage: advance wear without changing facing; false means broken. +pub fn wear_anvil(state: &mut BlockState) -> bool { + state.name = match state.name.as_str() { + "minecraft:anvil" => "minecraft:chipped_anvil", + "minecraft:chipped_anvil" => "minecraft:damaged_anvil", + _ => return false, + } + .into(); + true +} + +pub fn bounds(position: Vec3) -> Aabb { + let size = f64::from(0.98_f32); + Aabb::new( + Vec3::new(position.x - size / 2.0, position.y, position.z - size / 2.0), + Vec3::new( + position.x + size / 2.0, + position.y + size, + position.z + size / 2.0, + ), + ) +} +pub fn hurt_mobs(mobs: &mut [Mob], position: Vec3, amount: f32) { + if amount <= 0.0 { + return; + } + let bounds = bounds(position); + let source = MobDamage { + kind: DamageKind::FallingBlock, + attacker: None, + from: Some([position.x, position.y, position.z]), + }; + for mob in mobs + .iter_mut() + .filter(|m| m.alive() && bounds.intersects(m.bounds())) + { + mob.damage(amount, source); + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn impact_uses_ceil_distance_capped_damage_and_positive_damage_wear() { + let damage = Damage::anvil(); + assert!(Damage::default().impact(50.0).is_none()); + assert!(damage.impact(0.0).is_none()); + let short = damage.impact(1.0).unwrap(); + assert_eq!((short.amount, short.wear_chance), (0.0, 0.0)); + assert_eq!(damage.impact(1.01).unwrap().amount, 2.0); + assert_eq!(damage.impact(5.0).unwrap().amount, 8.0); + assert_eq!(damage.impact(100.0).unwrap().amount, 40.0); + assert!(damage.impact(21.0).unwrap().wear_chance > 1.0); + } + #[test] + fn damage_settings_round_trip_and_keep_vanilla_load_defaults() { + let empty = Tag::Compound(Default::default()); + assert_eq!(Damage::from_nbt(&empty, false), Damage::default()); + let loaded_anvil = Damage::from_nbt(&empty, true); + assert!(loaded_anvil.hurt_entities); + assert_eq!(loaded_anvil.per_distance, 0.0); + let damage = Damage { + hurt_entities: true, + cancel_drop: true, + per_distance: 3.5, + max: 17, + }; + let mut tag = empty; + damage.save(&mut tag); + assert_eq!(Damage::from_nbt(&tag, false), damage); + } + #[test] + fn anvil_wears_twice_then_breaks_preserving_facing() { + for facing in ["north", "south", "east", "west"] { + let mut state = BlockState { + name: "minecraft:anvil".into(), + properties: [("facing".into(), facing.into())].into(), + }; + for name in ["minecraft:chipped_anvil", "minecraft:damaged_anvil"] { + assert!(wear_anvil(&mut state)); + assert_eq!(state.name, name); + assert_eq!(state.properties["facing"], facing); + } + assert!(!wear_anvil(&mut state)); + } + } + #[test] + #[ignore = "requires prepared entity models/data in HORIZON_TEST_RESOURCES"] + fn impact_hurts_only_living_intersecting_noninvulnerable_mobs() { + use crate::mobs::{Mob, MobTypes}; + use std::{path::Path, sync::Arc}; + let root = std::env::var_os("HORIZON_TEST_RESOURCES").expect("HORIZON_TEST_RESOURCES"); + let types = MobTypes::load(Path::new(&root)).unwrap(); + let cow = Arc::new(types.types["minecraft:cow"].clone()); + let mut mobs = vec![ + Mob::new(1, cow.clone(), Vec3::ZERO, 0.0), + Mob::new(2, cow.clone(), Vec3::new(3.0, 0.0, 0.0), 0.0), + Mob::new(3, cow.clone(), Vec3::ZERO, 0.0), + Mob::new(4, cow, Vec3::ZERO, 0.0), + ]; + mobs[2].invulnerable_flag = true; + mobs[3].extra.head = Some("minecraft:carved_pumpkin".into()); + let initial = mobs.iter().map(|m| m.health).collect::>(); + hurt_mobs( + &mut mobs, + Vec3::ZERO, + Damage::anvil().impact(5.0).unwrap().amount, + ); + assert_eq!(mobs[0].health, initial[0] - 8.0); + assert_eq!(mobs[1].health, initial[1]); + assert_eq!(mobs[2].health, initial[2]); + assert_eq!(mobs[3].health, initial[3] - 6.0); + } +} diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 7072abeb5..4c039204b 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -41,6 +41,7 @@ mod entity_culling; mod events; mod explosion; mod extras; +mod falling_damage; mod fangs; mod fireworks; mod fishing; @@ -642,6 +643,7 @@ struct FallingBlock { drop_item: bool, /// `Entity.fallDistance` (powder snow holds a block that fell far at 0.9). fall_distance: f64, + damage: horizon_client::falling_block::Damage, /// The UUID and compound it was loaded with, kept while it moves. saved: Option>, } @@ -1900,6 +1902,7 @@ impl Game<'_> { 1009 => Some(("minecraft:block.fire.extinguish", 0.5)), 1502 => Some(("minecraft:block.redstone_torch.burnout", 0.5)), 1030 => Some(("minecraft:block.anvil.use", 1.0)), + 1029 => Some(("minecraft:block.anvil.destroy", 1.0)), 1031 => Some(("minecraft:block.anvil.land", 0.3)), 1505 => Some(("minecraft:item.bone_meal.use", 1.0)), _ => None, @@ -1952,6 +1955,11 @@ impl Game<'_> { no_gravity: false, drop_item: true, fall_distance: 0.0, + damage: if self.res.facts.get(state).name.ends_with("anvil") { + horizon_client::falling_block::Damage::anvil() + } else { + Default::default() + }, saved: None, }); } @@ -2207,14 +2215,19 @@ impl Game<'_> { return false; } if solid { - landed.push(( - f.state, - [ - next.x.floor() as i32, - next.y.floor() as i32 + i32::from(!sunk), - next.z.floor() as i32, - ], - )); + let pos = [ + next.x.floor() as i32, + next.y.floor() as i32 + i32::from(!sunk), + next.z.floor() as i32, + ]; + let landing_y = if sunk { + next.y.floor() + f64::from(0.9_f32) + } else { + f64::from(pos[1]) + }; + f.fall_distance += (f.position.y - landing_y).max(0.0); + f.position = Vec3::new(next.x, landing_y, next.z); + landed.push((f.clone(), pos)); return false; } if next.y < f.position.y { @@ -2248,30 +2261,8 @@ impl Game<'_> { self.spawn_item(stack, [at.x, at.y, at.z], v, 10); } } - for (state, pos) in landed { - let landing = self.with_level(|b, level, ticks| { - b.falling_block_landed( - level, - ticks, - BlockPos::new(pos[0], pos[1], pos[2]), - state, - false, - ) - }); - if matches!(landing, Landing::Broken) { - let item = self.res.facts.get(state).item.clone(); - if &*item != "minecraft:air" { - self.pop_resource( - pos, - ItemStack { - item, - count: 1, - damage: 0, - extra: None, - }, - ); - } - } + for (block, pos) in landed { + self.finish_falling_block(block, pos); } self.process_level_events() } diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index e454264d8..262ff11c2 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -2980,6 +2980,7 @@ fn damage_type(kind: horizon_client::mobs::DamageKind, player: bool) -> &'static K::Explosion if player => "minecraft:player_explosion", K::Explosion => "minecraft:explosion", K::Fall => "minecraft:fall", + K::FallingBlock => "minecraft:falling_block", K::OnFire => "minecraft:on_fire", K::InFire => "minecraft:in_fire", K::Lava => "minecraft:lava", diff --git a/crates/horizon-client/src/game/falling_damage.rs b/crates/horizon-client/src/game/falling_damage.rs new file mode 100644 index 000000000..313ddbaac --- /dev/null +++ b/crates/horizon-client/src/game/falling_damage.rs @@ -0,0 +1,123 @@ +//! Landing impacts for falling blocks, before their placement/drop decision. +use super::{FallingBlock, Game, Landing}; +use horizon_client::{falling_block, items::ItemStack}; +use horizon_core::{geometry::Vec3, position::BlockPos, random::RandomSource}; +use horizon_world::level::LevelEvent; + +impl Game<'_> { + pub(super) fn finish_falling_block(&mut self, mut block: FallingBlock, pos: [i32; 3]) { + let anvil = self.res.facts.get(block.state).name.ends_with("anvil"); + if let Some(impact) = block.damage.impact(block.fall_distance) { + if impact.amount > 0.0 { + falling_block::hurt_mobs(&mut self.mobs, block.position, impact.amount); + let kind = if anvil { + "minecraft:falling_anvil" + } else { + "minecraft:falling_block" + }; + self.falling_hurt_player(block.position, impact.amount, kind); + if let Some(mut host) = self.lan.take() { + let bounds = falling_block::bounds(block.position); + let conns = host + .hub + .guests + .iter() + .filter(|g| { + g.placed + && g.loaded + && !g.dead + && !g.creative() + && !g.spectator() + && bounds.intersects(super::lan_mobs::guest_bounds(g)) + }) + .map(|g| g.conn) + .collect::>(); + for conn in conns { + self.guest_hit_by(&mut host, conn, |g| { + g.falling_hurt_player(block.position, impact.amount, kind) + }); + } + self.lan = Some(host); + } + } + if anvil + && impact.wear_chance > 0.0 + && self.world.random.next_float() < impact.wear_chance + && let Some(mut state) = self.res.assets.registry.state(block.state).cloned() + { + if falling_block::wear_anvil(&mut state) { + block.state = self + .res + .assets + .registry + .resolve(&state) + .unwrap_or(block.state); + } else { + block.damage.cancel_drop = true; + } + } + } + if block.damage.cancel_drop { + if anvil { + self.level_events.push(LevelEvent::LevelEvent { + id: 1029, + pos: BlockPos::new(pos[0], pos[1], pos[2]), + data: 0, + }); + } + return; + } + let landing = self.with_level(|b, level, ticks| { + b.falling_block_landed( + level, + ticks, + BlockPos::new(pos[0], pos[1], pos[2]), + block.state, + false, + ) + }); + if matches!(landing, Landing::Broken) + && block.drop_item + && self.ui.rules.bool("entity_drops") + { + let item = self.res.facts.get(block.state).item.clone(); + if &*item != "minecraft:air" { + self.pop_resource( + pos, + ItemStack { + item, + count: 1, + damage: 0, + extra: None, + }, + ); + } + } + } + fn falling_hurt_player(&mut self, position: Vec3, amount: f32, kind: &str) { + if self.creative || self.spectator() { + return; + } + if self.player.as_ref().is_none_or(|p| { + p.health.dead_or_dying() || !falling_block::bounds(position).intersects(p.bounds()) + }) { + return; + } + let amount = if self.armor[0].is_some() { + amount * 0.75 + } else { + amount + }; + let hurt = if let Some(p) = self.player.as_mut() + && let Some(id) = self.motion.health.damage.id(kind) + { + p.hurt(&self.motion.health, self.world.health_rules, id, amount) + .unwrap_or(false) + } else { + false + }; + if hurt { + self.hurt_armor(amount); + } + } +} diff --git a/crates/horizon-client/src/game/persist.rs b/crates/horizon-client/src/game/persist.rs index 054f2c2fc..29549bb02 100644 --- a/crates/horizon-client/src/game/persist.rs +++ b/crates/horizon-client/src/game/persist.rs @@ -49,16 +49,7 @@ fn with_raw(modelled: Tag, raw: Option<&Tag>) -> Tag { // Defaults Horizon invents for fields it does not simulate give way to the save. let invented = matches!( k.to_string_lossy().as_str(), - "Fire" - | "Air" - | "Invulnerable" - | "PortalCooldown" - | "HasBeenShot" - // FallingBlockEntity fields Horizon does not simulate. - | "HurtEntities" - | "CancelDrop" - | "FallHurtAmount" - | "FallHurtMax" + "Fire" | "Air" | "Invulnerable" | "PortalCooldown" | "HasBeenShot" ); if !(invented && out.contains_key(k)) { out.insert(k.clone(), v.clone()); @@ -199,7 +190,7 @@ impl Game<'_> { } } "minecraft:falling_block" => { - if let Some((state, position, velocity, age)) = + if let Some((state, position, velocity, age, fall_distance)) = entity_nbt::falling_block_from_nbt(&tag) && let Some(state) = self.state_from_nbt(&state) { @@ -214,7 +205,11 @@ impl Game<'_> { age, no_gravity, drop_item, - fall_distance: 0.0, + fall_distance, + damage: horizon_client::falling_block::Damage::from_nbt( + &tag, + self.res.facts.get(state).name.ends_with("anvil"), + ), saved: uuid.map(|u| Box::new((u, tag.clone()))), }); } @@ -620,6 +615,8 @@ impl Game<'_> { f.velocity, f.age, f.drop_item, + f.damage, + f.fall_distance, uuid, ); out.entry(chunk_of(f.position)) diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index b56891996..092a782e4 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -59,6 +59,7 @@ pub mod entity_nbt; pub mod environment; pub mod extras; pub mod extras_hud; +pub mod falling_block; pub mod fast_hash; pub mod fastutil_order; pub mod fire_render; diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index a98cbb897..8697f66f0 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -507,6 +507,7 @@ pub enum DamageKind { Fireball, Explosion, Fall, + FallingBlock, OnFire, InFire, Lava, @@ -1610,6 +1611,12 @@ impl Mob { return false; } let mut amount = amount; + if source.kind == DamageKind::FallingBlock + && !species::body_slot(self.species()) + && self.extra.head.is_some() + { + amount *= 0.75; + } let (worn, worn_toughness) = self.worn_armor(); if !source.bypasses_armor() && self.kind.armor + worn > 0.0 { // CombatRules.getDamageAfterAbsorb From 9d21209ae8c4e6f788955abab69e7b96d1ef3237 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 16 Oct 2026 19:27:05 +0200 Subject: [PATCH 02/14] horizon-server: server.toml, init, and a supervisor that runs the game The first part of hosting a Horizon server with one small program (docs/server.md). horizon-server is a new 1.3 MB binary with no window, GPU, audio or controller code; it runs the game headless (horizon-client --dedicated) as its engine. - horizon-server-files: server.properties, eula.txt and the user lists, moved out of horizon-client unchanged so both programs share vanilla's exact reading and writing; horizon_client::server re-exports it. - server.toml: typed settings for what owners change, [properties] for any other vanilla key, vanilla 26.3's defaults (a test checks them against ServerProperties). It is written into server.properties before every start; keys the game changes there itself (/whitelist on) are copied back afterwards, keeping the owner's comments (toml_edit). `import` turns a vanilla server.properties into server.toml. - init: the EULA (only a yes writes eula=true), world, seed, port (checked free), whitelist and first operator; every question has a flag, so it also runs unattended. - run: the console on stdin, a clean `stop` on Ctrl-C, SIGTERM or SIGHUP (the game runs in its own process group), and a restart when the game crashes: 5 s, doubling to 5 min, giving up after 5 crashes in 10 min. One supervisor per folder (a file lock). - op, deop and whitelist for a stopped server, with vanilla's messages. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 24 + Cargo.toml | 2 +- crates/horizon-client/Cargo.toml | 2 + crates/horizon-client/src/lib.rs | 2 +- crates/horizon-server-files/Cargo.toml | 16 + .../src}/eula.rs | 7 +- .../src}/java_properties.rs | 0 .../src}/json.rs | 0 .../src/lib.rs} | 6 +- .../src}/properties.rs | 0 .../src}/user_lists.rs | 0 crates/horizon-server/Cargo.toml | 24 + crates/horizon-server/src/config.rs | 515 ++++++++++++++++++ crates/horizon-server/src/engine.rs | 127 +++++ crates/horizon-server/src/init.rs | 276 ++++++++++ crates/horizon-server/src/lists.rs | 153 ++++++ crates/horizon-server/src/main.rs | 117 ++++ crates/horizon-server/src/signals.rs | 41 ++ crates/horizon-server/src/supervisor.rs | 255 +++++++++ 19 files changed, 1561 insertions(+), 6 deletions(-) create mode 100644 crates/horizon-server-files/Cargo.toml rename crates/{horizon-client/src/server => horizon-server-files/src}/eula.rs (86%) rename crates/{horizon-client/src/server => horizon-server-files/src}/java_properties.rs (100%) rename crates/{horizon-client/src/server => horizon-server-files/src}/json.rs (100%) rename crates/{horizon-client/src/server/mod.rs => horizon-server-files/src/lib.rs} (50%) rename crates/{horizon-client/src/server => horizon-server-files/src}/properties.rs (100%) rename crates/{horizon-client/src/server => horizon-server-files/src}/user_lists.rs (100%) create mode 100644 crates/horizon-server/Cargo.toml create mode 100644 crates/horizon-server/src/config.rs create mode 100644 crates/horizon-server/src/engine.rs create mode 100644 crates/horizon-server/src/init.rs create mode 100644 crates/horizon-server/src/lists.rs create mode 100644 crates/horizon-server/src/main.rs create mode 100644 crates/horizon-server/src/signals.rs create mode 100644 crates/horizon-server/src/supervisor.rs diff --git a/Cargo.lock b/Cargo.lock index 68d0b250d..a54f2627b 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", @@ -1527,6 +1528,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" @@ -3725,6 +3748,7 @@ dependencies = [ "indexmap", "toml_datetime", "toml_parser", + "toml_writer", "winnow", ] diff --git a/Cargo.toml b/Cargo.toml index 49ef5785f..51d129f7c 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-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-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 b56891996..17d0b6a2c 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -146,7 +146,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(); + } +} From e8832190d1017de6d23eb66c0b8dc75ca35cc95f Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 16 Oct 2026 20:06:24 +0200 Subject: [PATCH 03/14] horizon-server: start, stop, status, cmd and logs through a local control API The supervisor serves a small HTTP API on 127.0.0.1 (a token in .horizon/api.json, mode 0600, and a Host check): status, logs, console commands, stop and restart. `start` runs the server in the background and returns once the game is up; `restart` and `cmd` wait for it too. A sampler reads the game's tick rate, tick times, players and chunks every second over the existing control endpoint (`--control-socket`), and RAM and CPU from the system. The dedicated loop now records its tick times in the game clock, so `/tick query` reports real numbers on a dedicated server, as it does in single player. The changes to game/dedicated.rs are additive: the log capture for command replies, the tick counter and the control requests (game/dedicated/status.rs). Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 2 + crates/horizon-client/src/game/dedicated.rs | 30 ++ .../src/game/dedicated/status.rs | 100 +++++ crates/horizon-server/Cargo.toml | 3 + crates/horizon-server/src/api.rs | 378 ++++++++++++++++++ crates/horizon-server/src/cli.rs | 329 +++++++++++++++ crates/horizon-server/src/engine.rs | 57 ++- crates/horizon-server/src/http.rs | 219 ++++++++++ crates/horizon-server/src/lists.rs | 30 +- crates/horizon-server/src/main.rs | 39 +- crates/horizon-server/src/supervisor.rs | 162 +++++++- 11 files changed, 1309 insertions(+), 40 deletions(-) create mode 100644 crates/horizon-client/src/game/dedicated/status.rs create mode 100644 crates/horizon-server/src/api.rs create mode 100644 crates/horizon-server/src/cli.rs create mode 100644 crates/horizon-server/src/http.rs diff --git a/Cargo.lock b/Cargo.lock index a54f2627b..3d5583167 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1532,9 +1532,11 @@ dependencies = [ name = "horizon-server" version = "0.1.0" dependencies = [ + "horizon-bench", "horizon-server-files", "libc", "serde", + "serde_json", "toml", "toml_edit", "windows-sys 0.61.2", diff --git a/crates/horizon-client/src/game/dedicated.rs b/crates/horizon-client/src/game/dedicated.rs index cd7744d87..48ee966de 100644 --- a/crates/horizon-client/src/game/dedicated.rs +++ b/crates/horizon-client/src/game/dedicated.rs @@ -29,6 +29,8 @@ use std::{ time::{Duration, Instant}, }; +mod status; + /// Double.toString for the magnitudes positions have (no exponent form /// between 1e-3 and 1e7). pub(super) fn java_double(v: f64) -> String { @@ -64,6 +66,11 @@ pub(super) fn log(level: &str, message: &str) { _ => ::log::Level::Info, }; horizon_client::logging::write_only(file_level, message); + CAPTURE.with_borrow_mut(|lines| { + if let Some(lines) = lines { + lines.push(message.to_owned()); + } + }); let secs = now_millis().div_euclid(1000).rem_euclid(86_400); println!( "[{:02}:{:02}:{:02}] [Server thread/{level}]: {message}", @@ -73,6 +80,18 @@ pub(super) fn log(level: &str, message: &str) { ); } +thread_local! { + /// The lines logged while a control request runs a console command. + static CAPTURE: std::cell::RefCell>> = const { std::cell::RefCell::new(None) }; +} + +/// Runs `f` and returns the lines it logged. +fn capture_log(f: impl FnOnce()) -> Vec { + CAPTURE.set(Some(Vec::new())); + f(); + CAPTURE.take().unwrap_or_default() +} + /// 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 { @@ -289,6 +308,9 @@ struct ServerState { stop: bool, autosave: bool, empty_ticks: i32, + /// When the last passes of the loop ended, for the tick rate horizon-server shows. + ticks: std::collections::VecDeque, + paused: bool, } impl Game<'_> { @@ -469,14 +491,18 @@ impl Game<'_> { stop: false, autosave: true, empty_ticks: 0, + ticks: Default::default(), + paused: false, }; let pause_after = props.pause_when_empty_seconds * 20; let idle_timeout = props.player_idle_timeout; let mut next = Instant::now(); while !state.stop { + let tick_start = Instant::now(); while let Ok(line) = state.console.try_recv() { self.console_command(&mut state, &line); } + self.poll_server_control(&mut state); let players = self.lan.as_ref().map_or(0, |h| h.hub.guests.len()); if pause_after > 0 { if players == 0 { @@ -486,6 +512,7 @@ impl Game<'_> { } } let paused = pause_after > 0 && state.empty_ticks >= pause_after; + state.paused = paused; if paused && state.empty_ticks == pause_after { log( "INFO", @@ -511,6 +538,9 @@ impl Game<'_> { if idle_timeout > 0 { self.kick_idle(idle_timeout); } + // MinecraftServer.tickServer records each tick's time, for /tick query (and the status). + self.clock.record(tick_start.elapsed()); + state.ticked(Instant::now()); let rate = self.clock.rate().max(1.0); next += Duration::from_secs_f64(1.0 / f64::from(rate)); let now = Instant::now(); diff --git a/crates/horizon-client/src/game/dedicated/status.rs b/crates/horizon-client/src/game/dedicated/status.rs new file mode 100644 index 000000000..a2ec4c1ae --- /dev/null +++ b/crates/horizon-client/src/game/dedicated/status.rs @@ -0,0 +1,100 @@ +//! What `horizon-server` asks the dedicated server on its control endpoint (`--control-socket`, docs/server.md +//! section 2): `server-status` answers with the tick rate, the tick times `/tick query` reports, the players +//! and the loaded chunks; `console ` runs a console command and answers with the lines it logged. +use super::{ServerState, capture_log}; +use crate::game::Game; +use serde_json::{Value, json}; +use std::{ + sync::atomic::Ordering, + time::{Duration, Instant}, +}; + +/// The window the tick rate is measured over. +const TPS_WINDOW: Duration = Duration::from_secs(5); + +impl ServerState { + /// One pass of the server loop ended. + pub(super) fn ticked(&mut self, at: Instant) { + self.ticks.push_back(at); + while self + .ticks + .front() + .is_some_and(|t| at.duration_since(*t) > TPS_WINDOW) + { + self.ticks.pop_front(); + } + } + /// Ticks per second over the last few seconds. + fn tps(&self) -> f64 { + match (self.ticks.front(), self.ticks.back()) { + (Some(first), Some(last)) if self.ticks.len() > 1 => { + (self.ticks.len() - 1) as f64 / last.duration_since(*first).as_secs_f64().max(1e-9) + } + _ => 0.0, + } + } +} + +impl Game<'_> { + /// Answers the requests waiting on the control endpoint. + pub(super) fn poll_server_control(&mut self, state: &mut ServerState) { + while let Some(request) = self.control.as_ref().and_then(|c| c.try_recv()) { + let reply = match request.line.trim().split_once(' ') { + _ if request.line.trim() == "server-status" => self.server_status(state), + Some(("console", line)) => { + // Command feedback is logged as system chat; the reply carries the text alone. + let output: Vec = capture_log(|| self.console_command(state, line)) + .into_iter() + .map(|l| { + l.strip_prefix("System chat: ") + .map_or(l.clone(), str::to_owned) + }) + .collect(); + json!({ "output": output }) + } + _ => json!({ "error": format!("unknown request {:?}", request.line) }), + }; + let _ = request.reply.send(reply.to_string()); + } + } + + fn server_status(&self, state: &ServerState) -> Value { + let millis = |nanos: u64| nanos as f64 / 1e6; + let samples = self.clock.sorted_samples(); + // The percentiles `/tick query` prints (TickCommand.percentileToString). + let at = |q: f64| { + let i = ((samples.len() as f64 * q) as usize).min(samples.len().saturating_sub(1)); + samples.get(i).copied().map_or(0.0, millis) + }; + let (players, max_players) = self.lan.as_ref().map_or((Vec::new(), 0), |h| { + let players = h + .hub + .guests + .iter() + .map(|g| { + json!({ + "name": g.name, + "uuid": horizon_protocol::crypto::uuid_string(g.uuid), + "address": g.address.ip().to_string(), + "ping_ms": g.latency.load(Ordering::Relaxed), + }) + }) + .collect(); + (players, h.hub.lan.shared.max_players()) + }); + json!({ + "tps": state.tps(), + "target_tps": self.clock.rate(), + "mspt": { + "average": millis(self.clock.average_nanos()), + "p50": at(0.5), + "p95": at(0.95), + "p99": at(0.99), + }, + "players": players, + "max_players": max_players, + "chunks": self.world.chunks.len(), + "paused": state.paused, + }) + } +} diff --git a/crates/horizon-server/Cargo.toml b/crates/horizon-server/Cargo.toml index 919001968..deab442ae 100644 --- a/crates/horizon-server/Cargo.toml +++ b/crates/horizon-server/Cargo.toml @@ -8,7 +8,10 @@ description = "Host a Horizon server: server.toml, the CLI and the supervisor th [dependencies] horizon-server-files = { path = "../horizon-server-files" } +# The game process's RAM and CPU (the same probes the benchmark reports use). +horizon-bench = { path = "../horizon-bench" } serde = { version = "1", features = ["derive"] } +serde_json = "1" toml = "1.1" # Edits server.toml in place, keeping the owner's comments and order. toml_edit = "0.25" diff --git a/crates/horizon-server/src/api.rs b/crates/horizon-server/src/api.rs new file mode 100644 index 000000000..dbca00215 --- /dev/null +++ b/crates/horizon-server/src/api.rs @@ -0,0 +1,378 @@ +//! The control API (docs/server.md, section 8): HTTP and JSON on 127.0.0.1, with a random token in +//! `.horizon/api.json` that only the server's own user can read. The CLI manages a running server through +//! it; the web panel and the MCP server will too. +//! +//! - `GET /api/v1/status`: the supervisor's state, the game's status (TPS, MSPT, players), RAM and CPU. +//! - `GET /api/v1/logs?since=N`: the log lines after the Nth. +//! - `POST /api/v1/command {"line": "..."}`: a console command; the lines it logged. +//! - `POST /api/v1/stop`, `POST /api/v1/restart`. + +use crate::{ + engine, + http::{self, Request, Response}, +}; +use serde_json::{Value, json}; +use std::{ + collections::VecDeque, + io::Write, + net::{SocketAddr, TcpListener}, + path::{Path, PathBuf}, + sync::{ + Arc, Mutex, + atomic::{AtomicBool, Ordering}, + }, + time::{Duration, Instant}, +}; + +const ENDPOINT: &str = ".horizon/api.json"; +/// The log lines kept for `logs` and the panel's console. +const LOG_LINES: usize = 2000; + +/// What the supervisor is doing. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Phase { + Starting, + Running, + Stopping, + /// Stopping the game to start it again (`restart`), or waiting to after a crash. + Restarting, +} + +impl Phase { + fn name(self) -> &'static str { + match self { + Self::Starting => "starting", + Self::Running => "running", + Self::Stopping => "stopping", + Self::Restarting => "restarting", + } + } +} + +pub struct State { + pub phase: Phase, + pub engine_pid: Option, + pub engine_started: Option, + pub crashes: u32, + pub last_crash: Option, + /// The latest sample (`sample`): the game's status, RAM and CPU. + pub sample: Value, +} + +/// The log, numbered from the first line since the supervisor started. +#[derive(Default)] +pub struct Log { + lines: VecDeque, + first: u64, +} + +impl Log { + pub fn push(&mut self, line: String) { + if self.lines.len() == LOG_LINES { + self.lines.pop_front(); + self.first += 1; + } + self.lines.push_back(line); + } + /// The lines after the `since`th, and the number to ask from next. + pub fn since(&self, since: u64) -> (u64, Vec) { + let skip = since.saturating_sub(self.first) as usize; + let next = self.first + self.lines.len() as u64; + (next, self.lines.iter().skip(skip).cloned().collect()) + } +} + +/// What the supervisor and the API threads share. +pub struct Shared { + pub dir: PathBuf, + pub state: Mutex, + pub log: Mutex, + pub stop: AtomicBool, + pub restart: AtomicBool, + pub started: Instant, +} + +impl Shared { + pub fn new(dir: &Path) -> Arc { + Arc::new(Self { + dir: dir.to_owned(), + state: Mutex::new(State { + phase: Phase::Starting, + engine_pid: None, + engine_started: None, + crashes: 0, + last_crash: None, + sample: Value::Null, + }), + log: Mutex::new(Log::default()), + stop: AtomicBool::new(false), + restart: AtomicBool::new(false), + started: Instant::now(), + }) + } + pub fn set_phase(&self, phase: Phase) { + self.state.lock().unwrap().phase = phase; + } +} + +fn status(shared: &Shared) -> Value { + let state = shared.state.lock().unwrap(); + json!({ + "phase": state.phase.name(), + "version": env!("CARGO_PKG_VERSION"), + "pid": std::process::id(), + "uptime_seconds": shared.started.elapsed().as_secs(), + "engine_pid": state.engine_pid, + "engine_uptime_seconds": state.engine_started.map(|t| t.elapsed().as_secs()), + "crashes": state.crashes, + "last_crash": state.last_crash, + "sample": state.sample, + }) +} + +/// A random token: two 64-bit hashes keyed by the OS's random hasher seeds, the time and the process. +fn random_token() -> String { + use std::hash::{BuildHasher, Hasher}; + (0..2u64) + .map(|i| { + let mut h = std::collections::hash_map::RandomState::new().build_hasher(); + h.write_u64(i); + h.write_u128( + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_nanos()), + ); + h.write_u32(std::process::id()); + format!("{:016x}", h.finish()) + }) + .collect() +} + +fn same_token(a: &str, b: &str) -> bool { + a.len() == b.len() && a.bytes().zip(b.bytes()).fold(0u8, |d, (x, y)| d | (x ^ y)) == 0 +} + +/// Writes a file only its owner can read. +pub fn write_private(path: &Path, text: &str) -> std::io::Result<()> { + let mut options = std::fs::OpenOptions::new(); + options.write(true).create(true).truncate(true); + #[cfg(unix)] + std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600); + options.open(path)?.write_all(text.as_bytes()) +} + +/// Removes the endpoint file when the supervisor ends. +pub struct Endpoint(PathBuf); +impl Drop for Endpoint { + fn drop(&mut self) { + let _ = std::fs::remove_file(&self.0); + } +} + +/// Starts the API on a free port of 127.0.0.1 and writes where it is and its token. +pub fn start(shared: Arc) -> Result { + let listener = TcpListener::bind("127.0.0.1:0").map_err(|e| format!("control API: {e}"))?; + let address = listener.local_addr().map_err(|e| e.to_string())?; + let token = random_token(); + let path = shared.dir.join(ENDPOINT); + write_private( + &path, + &json!({ "address": address.to_string(), "token": token, "pid": std::process::id() }) + .to_string(), + ) + .map_err(|e| format!("{}: {e}", path.display()))?; + let hosts = [address.to_string(), format!("localhost:{}", address.port())]; + http::serve(listener, move |request| { + // A page in a browser can't send the token, and a rebound DNS name can't pass as this address. + let authorised = request + .header("authorization") + .and_then(|h| h.strip_prefix("Bearer ")) + .is_some_and(|t| same_token(t.trim(), &token)); + if !authorised { + return Response::error(401, "missing or wrong token (see .horizon/api.json)"); + } + if !request + .header("host") + .is_some_and(|h| hosts.iter().any(|a| a == h)) + { + return Response::error(403, "wrong Host"); + } + route(&shared, request) + }) + .map_err(|e| e.to_string())?; + Ok(Endpoint(path)) +} + +fn route(shared: &Shared, request: &Request) -> Response { + match (request.method.as_str(), request.path.as_str()) { + ("GET", "/api/v1/status") => Response::json(200, &status(shared)), + ("GET", "/api/v1/logs") => { + let since = request + .param("since") + .and_then(|s| s.parse().ok()) + .unwrap_or(0); + let (next, lines) = shared.log.lock().unwrap().since(since); + Response::json(200, &json!({ "next": next, "lines": lines })) + } + ("POST", "/api/v1/command") => { + let line = serde_json::from_slice::(&request.body) + .ok() + .and_then(|v| v["line"].as_str().map(str::to_owned)); + let Some(line) = line.filter(|l| !l.trim().is_empty() && !l.contains('\n')) else { + return Response::error(400, "the body must be {\"line\": \"\"}"); + }; + if shared.state.lock().unwrap().phase != Phase::Running { + return Response::error(409, "the game isn't running right now"); + } + match engine::Control::connect(&shared.dir) + .and_then(|mut c| c.ask(&format!("console {}", line.trim_start_matches('/')))) + { + Ok(reply) => Response::json(200, &reply), + Err(e) => Response::error(409, &format!("the game didn't answer: {e}")), + } + } + ("POST", "/api/v1/stop") => { + shared.stop.store(true, Ordering::SeqCst); + Response::json(200, &json!({ "ok": true })) + } + ("POST", "/api/v1/restart") => { + shared.restart.store(true, Ordering::SeqCst); + Response::json(200, &json!({ "ok": true })) + } + ( + _, + "/api/v1/status" | "/api/v1/logs" | "/api/v1/command" | "/api/v1/stop" + | "/api/v1/restart", + ) => Response::error(405, "wrong method"), + _ => Response::error(404, "no such endpoint"), + } +} + +/// The API of the server running in a folder, for the CLI. +pub struct Client { + address: SocketAddr, + token: String, +} + +impl Client { + /// The running server's API; `None` when no server runs in `dir`. + pub fn open(dir: &Path) -> Result, String> { + if crate::supervisor::lock(dir).is_ok() { + return Ok(None); + } + // The supervisor writes the endpoint just after taking the lock: give it a moment. + let path = dir.join(ENDPOINT); + let deadline = Instant::now() + Duration::from_secs(5); + let text = loop { + match std::fs::read_to_string(&path) { + Ok(text) => break text, + Err(_) if Instant::now() < deadline => { + std::thread::sleep(Duration::from_millis(100)) + } + Err(e) => return Err(format!("{}: {e}", path.display())), + } + }; + let v: Value = + serde_json::from_str(&text).map_err(|e| format!("{}: {e}", path.display()))?; + let address = v["address"] + .as_str() + .and_then(|a| a.parse().ok()) + .ok_or_else(|| format!("{}: no address", path.display()))?; + let token = v["token"].as_str().unwrap_or_default().to_owned(); + Ok(Some(Self { address, token })) + } + + pub fn call(&self, method: &str, path: &str, body: Option<&Value>) -> Result { + let (status, text) = http::request( + self.address, + &self.token, + method, + path, + body, + Duration::from_secs(60), + ) + .map_err(|e| format!("the server didn't answer: {e}"))?; + let value: Value = serde_json::from_str(&text).unwrap_or(Value::Null); + if status == 200 { + Ok(value) + } else { + Err(value["error"].as_str().unwrap_or(&text).to_owned()) + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn log_keeps_the_last_lines_numbered() { + let mut log = Log::default(); + for i in 0..LOG_LINES + 10 { + log.push(i.to_string()); + } + let (next, lines) = log.since(0); + assert_eq!(next, (LOG_LINES + 10) as u64); + assert_eq!(lines.len(), LOG_LINES); + assert_eq!(lines[0], "10"); + let (next2, tail) = log.since(next - 2); + assert_eq!( + (next2, tail), + ( + next, + vec![(LOG_LINES + 8).to_string(), (LOG_LINES + 9).to_string()] + ) + ); + } + + #[test] + fn the_api_wants_its_token() { + let dir = std::env::temp_dir().join(format!("horizon-server-api-{}", std::process::id())); + std::fs::create_dir_all(dir.join(".horizon")).unwrap(); + let shared = Shared::new(&dir); + let _endpoint = start(shared.clone()).unwrap(); + let v: Value = + serde_json::from_str(&std::fs::read_to_string(dir.join(ENDPOINT)).unwrap()).unwrap(); + let address: SocketAddr = v["address"].as_str().unwrap().parse().unwrap(); + let token = v["token"].as_str().unwrap(); + let get = |token: &str| { + http::request( + address, + token, + "GET", + "/api/v1/status", + None, + Duration::from_secs(5), + ) + .unwrap() + }; + assert_eq!(get("nope").0, 401); + let (status, body) = get(token); + assert_eq!(status, 200); + let status: Value = serde_json::from_str(&body).unwrap(); + assert_eq!(status["phase"], "starting"); + let (code, _) = http::request( + address, + token, + "POST", + "/api/v1/stop", + None, + Duration::from_secs(5), + ) + .unwrap(); + assert_eq!(code, 200); + assert!(shared.stop.load(Ordering::SeqCst)); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let mode = std::fs::metadata(dir.join(ENDPOINT)) + .unwrap() + .permissions() + .mode(); + assert_eq!(mode & 0o777, 0o600); + } + drop(_endpoint); + assert!(!dir.join(ENDPOINT).exists()); + std::fs::remove_dir_all(&dir).unwrap(); + } +} diff --git a/crates/horizon-server/src/cli.rs b/crates/horizon-server/src/cli.rs new file mode 100644 index 000000000..b05292f5f --- /dev/null +++ b/crates/horizon-server/src/cli.rs @@ -0,0 +1,329 @@ +//! The commands that manage a server in the background (docs/server.md, section 5): `start`, `stop`, +//! `restart`, `status`, `cmd` and `logs`. They talk to the running supervisor through the control API. + +use crate::{api::Client, signals, supervisor}; +use serde_json::{Value, json}; +use std::{ + path::Path, + process::{Command, Stdio}, + time::{Duration, Instant}, +}; + +/// How long `start` waits for the game's `Done`, and `stop` for the server to end. +const START_TIMEOUT: Duration = Duration::from_secs(300); +const STOP_TIMEOUT: Duration = Duration::from_secs(180); + +fn running(dir: &Path) -> Result { + Client::open(dir)?.ok_or_else(|| format!("no server is running in {}", dir.display())) +} + +/// `start`: `run` in the background, its output in logs/supervisor.log; returns once the game is up. +pub fn start(dir: &Path) -> Result<(), String> { + if Client::open(dir)?.is_some() { + return Err(format!("a server is already running in {}", dir.display())); + } + crate::config::Config::load(dir)?; + // Left by a supervisor that was killed: the new one writes its own. + let endpoint = dir.join(".horizon/api.json"); + let _ = std::fs::remove_file(&endpoint); + let logs = dir.join("logs"); + std::fs::create_dir_all(&logs).map_err(|e| e.to_string())?; + let log_path = logs.join("supervisor.log"); + let log = std::fs::OpenOptions::new() + .create(true) + .append(true) + .open(&log_path) + .map_err(|e| format!("{}: {e}", log_path.display()))?; + let exe = std::env::current_exe().map_err(|e| e.to_string())?; + let mut command = Command::new(exe); + command + .arg("--dir") + .arg(dir) + .arg("run") + .stdin(Stdio::null()) + .stdout(log.try_clone().map_err(|e| e.to_string())?) + .stderr(log); + // Its own process group: closing this terminal doesn't stop the server. + #[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::DETACHED_PROCESS + | windows_sys::Win32::System::Threading::CREATE_NEW_PROCESS_GROUP, + ); + let mut child = command.spawn().map_err(|e| e.to_string())?; + let deadline = Instant::now() + START_TIMEOUT; + print!("Starting"); + loop { + if let Ok(Some(status)) = child.try_wait() { + println!(); + return Err(format!( + "the server stopped ({status}); see {}", + log_path.display() + )); + } + // Only once the new supervisor holds the folder (its endpoint is there) may we look: probing the + // lock any earlier could take it from under it. + if endpoint.exists() + && let Ok(Some(client)) = Client::open(dir) + && let Ok(status) = client.call("GET", "/api/v1/status", None) + && status["phase"] == "running" + { + println!( + "\nThe server is running (pid {}). `horizon-server status` shows how it does, \ + `horizon-server stop` stops it.", + child.id() + ); + return Ok(()); + } + if Instant::now() > deadline { + println!(); + return Err(format!( + "the game isn't up after {} s; it may still be starting: see {}", + START_TIMEOUT.as_secs(), + log_path.display() + )); + } + print!("."); + let _ = std::io::Write::flush(&mut std::io::stdout()); + std::thread::sleep(Duration::from_millis(500)); + } +} + +/// `stop` and `restart`. +pub fn stop(dir: &Path, restart: bool) -> Result<(), String> { + let client = running(dir)?; + if restart { + let before = client.call("GET", "/api/v1/status", None)?["engine_pid"].as_u64(); + client.call("POST", "/api/v1/restart", None)?; + print!("Restarting"); + wait_running(&client, before)?; + println!("\nThe game is running again."); + return Ok(()); + } + client.call("POST", "/api/v1/stop", None)?; + let deadline = Instant::now() + STOP_TIMEOUT; + while supervisor::lock(dir).is_err() { + if Instant::now() > deadline { + return Err("the server is still stopping".into()); + } + std::thread::sleep(Duration::from_millis(200)); + } + println!("Stopped."); + Ok(()) +} + +/// Waits until the game is up: a new one when `replaced` is the engine's pid before a restart. +fn wait_running(client: &Client, replaced: Option) -> Result<(), String> { + let deadline = Instant::now() + START_TIMEOUT; + loop { + let status = client.call("GET", "/api/v1/status", None)?; + if status["phase"] == "running" && status["engine_pid"].as_u64() != replaced { + return Ok(()); + } + if status["phase"] == "stopped" || status["phase"] == "stopping" { + return Err("the server is stopping".into()); + } + if Instant::now() > deadline { + return Err(format!( + "the game isn't up after {} s; `horizon-server logs` shows why", + START_TIMEOUT.as_secs() + )); + } + if replaced.is_some() { + print!("."); + let _ = std::io::Write::flush(&mut std::io::stdout()); + } + std::thread::sleep(Duration::from_millis(500)); + } +} + +/// `cmd`: one console command, and what it printed. +pub fn command(dir: &Path, words: &[String]) -> Result<(), String> { + if words.is_empty() { + return Err("cmd needs a console command, for example: horizon-server cmd list".into()); + } + let client = running(dir)?; + // A game that is starting or restarting takes the command once it is up. + wait_running(&client, None)?; + let reply = client.call( + "POST", + "/api/v1/command", + Some(&json!({ "line": words.join(" ") })), + )?; + for line in reply["output"].as_array().into_iter().flatten() { + println!("{}", line.as_str().unwrap_or_default()); + } + Ok(()) +} + +/// `status [--json]`. +pub fn status(dir: &Path, as_json: bool) -> Result<(), String> { + let Some(client) = Client::open(dir)? else { + if as_json { + println!("{}", json!({ "phase": "stopped" })); + } else { + println!("Stopped."); + } + return Ok(()); + }; + let status = client.call("GET", "/api/v1/status", None)?; + if as_json { + println!("{status}"); + } else { + print!("{}", describe(&status)); + } + Ok(()) +} + +/// The status for people: three short lines. +fn describe(status: &Value) -> String { + let mut out = String::new(); + let phase = status["phase"].as_str().unwrap_or("?"); + let uptime = status["engine_uptime_seconds"] + .as_u64() + .or(status["uptime_seconds"].as_u64()) + .map_or_else(String::new, |s| format!(", up {}", duration(s))); + let crashes = match status["crashes"].as_u64() { + Some(0) | None => String::new(), + Some(n) => format!( + ", {n} crash{} (last: {})", + if n == 1 { "" } else { "es" }, + status["last_crash"].as_str().unwrap_or("?") + ), + }; + out += &format!("{}{uptime}{crashes}\n", capitalised(phase)); + let sample = &status["sample"]; + let game = &sample["game"]; + if let Some(tps) = game["tps"].as_f64() { + let mspt = &game["mspt"]; + out += &format!( + "TPS {tps:.1}, MSPT {:.1} ms average, {:.1} ms P95{}\n", + mspt["average"].as_f64().unwrap_or(0.0), + mspt["p95"].as_f64().unwrap_or(0.0), + if game["paused"] == true { + " (paused: nobody online)" + } else { + "" + } + ); + let names: Vec<&str> = game["players"] + .as_array() + .into_iter() + .flatten() + .filter_map(|p| p["name"].as_str()) + .collect(); + out += &format!( + "{} of {} players{}{}, {} chunks loaded\n", + names.len(), + game["max_players"].as_u64().unwrap_or(0), + if names.is_empty() { "" } else { ": " }, + names.join(", "), + game["chunks"].as_u64().unwrap_or(0) + ); + } + let ram = sample["rss_bytes"] + .as_f64() + .map(|b| format!("RAM {:.2} GB", b / 1e9)); + let cpu = sample["cpu_percent"] + .as_f64() + .map(|c| format!("CPU {c:.0} % of a core")); + let usage: Vec = ram.into_iter().chain(cpu).collect(); + if !usage.is_empty() { + out += &format!("{}\n", usage.join(", ")); + } + out +} + +fn capitalised(s: &str) -> String { + let mut c = s.chars(); + c.next() + .map(|f| f.to_uppercase().chain(c).collect()) + .unwrap_or_default() +} + +fn duration(secs: u64) -> String { + match secs { + 0..60 => format!("{secs} s"), + 60..3600 => format!("{} min", secs / 60), + 3600..86_400 => format!("{} h {:02} min", secs / 3600, secs / 60 % 60), + _ => format!("{} d {} h", secs / 86_400, secs / 3600 % 24), + } +} + +/// `logs [-f] [-n N]`: the last lines, from the running server or else from logs/latest.log. +pub fn logs(dir: &Path, follow: bool, count: usize) -> Result<(), String> { + let Some(client) = Client::open(dir)? else { + if follow { + return Err("no server is running to follow".into()); + } + let path = dir.join("logs/latest.log"); + let text = + std::fs::read_to_string(&path).map_err(|e| format!("{}: {e}", path.display()))?; + let lines: Vec<&str> = text.lines().collect(); + for line in &lines[lines.len().saturating_sub(count)..] { + println!("{line}"); + } + return Ok(()); + }; + let reply = client.call("GET", "/api/v1/logs?since=0", None)?; + let lines = reply["lines"].as_array().cloned().unwrap_or_default(); + for line in &lines[lines.len().saturating_sub(count)..] { + println!("{}", line.as_str().unwrap_or_default()); + } + if !follow { + return Ok(()); + } + signals::install(); + let mut next = reply["next"].as_u64().unwrap_or(0); + while signals::requests() == 0 { + std::thread::sleep(Duration::from_millis(500)); + let Ok(reply) = client.call("GET", &format!("/api/v1/logs?since={next}"), None) else { + break; + }; + for line in reply["lines"].as_array().into_iter().flatten() { + println!("{}", line.as_str().unwrap_or_default()); + } + next = reply["next"].as_u64().unwrap_or(next); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn status_reads_well() { + let status = json!({ + "phase": "running", + "engine_uptime_seconds": 7380, + "crashes": 1, + "last_crash": "signal: 9 (SIGKILL)", + "sample": { + "rss_bytes": 1_420_000_000u64, + "cpu_percent": 12.4, + "game": { + "tps": 20.0, + "mspt": { "average": 3.12, "p95": 7.9 }, + "players": [{ "name": "Alex" }, { "name": "Steve" }], + "max_players": 20, + "chunks": 1234, + "paused": false + } + } + }); + assert_eq!( + describe(&status), + "Running, up 2 h 03 min, 1 crash (last: signal: 9 (SIGKILL))\n\ + TPS 20.0, MSPT 3.1 ms average, 7.9 ms P95\n\ + 2 of 20 players: Alex, Steve, 1234 chunks loaded\n\ + RAM 1.42 GB, CPU 12 % of a core\n" + ); + assert_eq!( + describe(&json!({ "phase": "starting", "uptime_seconds": 4 })), + "Starting, up 4 s\n" + ); + } +} diff --git a/crates/horizon-server/src/engine.rs b/crates/horizon-server/src/engine.rs index 41f71f433..c0043e1d3 100644 --- a/crates/horizon-server/src/engine.rs +++ b/crates/horizon-server/src/engine.rs @@ -4,8 +4,11 @@ use crate::config::Config; use std::{ + io::{BufRead, BufReader, Write}, + net::{Ipv4Addr, TcpStream}, path::{Path, PathBuf}, process::{Child, Command, Stdio}, + time::Duration, }; /// The game's program names, most specific first: a headless engine once there is one, else the game. @@ -83,12 +86,15 @@ pub fn resources(config: &Config, dir: &Path, program: Option<&Path>) -> Result< }) } -/// Starts the engine in the server folder, with its console and log piped to the supervisor. +/// Starts the engine in the server folder, with its console and log piped to the supervisor and its status +/// on the control endpoint. pub fn spawn(program: &Path, resources: &Path, dir: &Path) -> std::io::Result { let mut command = Command::new(program); command .arg("--resources") .arg(resources) + .arg("--control-socket") + .arg(control_path(dir)) .args(["--dedicated", "--nogui"]) .current_dir(dir) .env("HORIZON_NO_AUDIO", "1") @@ -106,6 +112,55 @@ pub fn spawn(program: &Path, resources: &Path, dir: &Path) -> std::io::Result PathBuf { + dir.join(".horizon/engine.json") +} + +/// A connection to the game's control endpoint: one JSON line asked, one answered. +pub struct Control { + writer: TcpStream, + reader: BufReader, +} + +impl Control { + pub fn connect(dir: &Path) -> std::io::Result { + let text = std::fs::read_to_string(control_path(dir))?; + let bad = || std::io::Error::new(std::io::ErrorKind::InvalidData, "not a control endpoint"); + let v: serde_json::Value = serde_json::from_str(&text).map_err(|_| bad())?; + let port = v["port"] + .as_u64() + .and_then(|p| u16::try_from(p).ok()) + .ok_or_else(bad)?; + let token = v["token"].as_str().ok_or_else(bad)?; + let writer = TcpStream::connect((Ipv4Addr::LOCALHOST, port))?; + writer.set_read_timeout(Some(Duration::from_secs(30)))?; + let mut control = Self { + reader: BufReader::new(writer.try_clone()?), + writer, + }; + let reply = control.ask(&format!("auth {token}"))?; + if reply["ok"] != true { + return Err(std::io::Error::new( + std::io::ErrorKind::PermissionDenied, + "the game refused the token", + )); + } + Ok(control) + } + + pub fn ask(&mut self, line: &str) -> std::io::Result { + writeln!(self.writer, "{line}")?; + self.writer.flush()?; + let mut reply = String::new(); + if self.reader.read_line(&mut reply)? == 0 { + return Err(std::io::ErrorKind::UnexpectedEof.into()); + } + serde_json::from_str(&reply) + .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e)) + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/horizon-server/src/http.rs b/crates/horizon-server/src/http.rs new file mode 100644 index 000000000..3d1507194 --- /dev/null +++ b/crates/horizon-server/src/http.rs @@ -0,0 +1,219 @@ +//! Just enough HTTP/1.1 for the control API on 127.0.0.1 (docs/server.md, section 8): one request per +//! connection, JSON bodies with a Content-Length. No async runtime and no dependency: a thread per +//! connection is plenty for a CLI, a panel tab and an MCP client. + +use std::{ + io::{BufRead, BufReader, Read, Write}, + net::{SocketAddr, TcpListener, TcpStream}, + time::Duration, +}; + +/// The largest request body the API takes (a console command, a settings change). +const MAX_BODY: usize = 1 << 20; + +pub struct Request { + pub method: String, + pub path: String, + pub query: String, + pub headers: Vec<(String, String)>, + pub body: Vec, +} + +impl Request { + pub fn header(&self, name: &str) -> Option<&str> { + self.headers + .iter() + .find(|(k, _)| k.eq_ignore_ascii_case(name)) + .map(|(_, v)| v.as_str()) + } + /// One `key=value` from the query string (no percent-decoding: the API's values are numbers). + pub fn param(&self, key: &str) -> Option<&str> { + self.query + .split('&') + .filter_map(|p| p.split_once('=')) + .find(|(k, _)| *k == key) + .map(|(_, v)| v) + } +} + +pub struct Response { + pub status: u16, + pub body: String, +} + +impl Response { + pub fn json(status: u16, value: &serde_json::Value) -> Self { + Self { + status, + body: value.to_string(), + } + } + pub fn error(status: u16, message: &str) -> Self { + Self::json(status, &serde_json::json!({ "error": message })) + } +} + +fn reason(status: u16) -> &'static str { + match status { + 200 => "OK", + 400 => "Bad Request", + 401 => "Unauthorized", + 403 => "Forbidden", + 404 => "Not Found", + 405 => "Method Not Allowed", + 409 => "Conflict", + 413 => "Payload Too Large", + _ => "Error", + } +} + +fn read_request(stream: &TcpStream) -> Result { + let bad = |m: &str| Response::error(400, m); + let mut reader = BufReader::new(stream); + let mut line = String::new(); + reader.read_line(&mut line).map_err(|_| bad("no request"))?; + let mut parts = line.split_whitespace(); + let (Some(method), Some(target)) = (parts.next(), parts.next()) else { + return Err(bad("malformed request line")); + }; + let (path, query) = target.split_once('?').unwrap_or((target, "")); + let mut headers = Vec::new(); + loop { + let mut line = String::new(); + if reader.read_line(&mut line).map_err(|_| bad("headers"))? == 0 || line.trim().is_empty() { + break; + } + if headers.len() > 64 { + return Err(bad("too many headers")); + } + if let Some((k, v)) = line.split_once(':') { + headers.push((k.trim().to_owned(), v.trim().to_owned())); + } + } + let length = headers + .iter() + .find(|(k, _)| k.eq_ignore_ascii_case("content-length")) + .map_or(Ok(0), |(_, v)| v.parse::()) + .map_err(|_| bad("bad Content-Length"))?; + if length > MAX_BODY { + return Err(Response::error(413, "the body is too large")); + } + let mut body = vec![0; length]; + reader + .read_exact(&mut body) + .map_err(|_| bad("the body is shorter than its Content-Length"))?; + Ok(Request { + method: method.to_owned(), + path: path.to_owned(), + query: query.to_owned(), + headers, + body, + }) +} + +fn write_response(mut stream: &TcpStream, response: &Response) { + let _ = write!( + stream, + "HTTP/1.1 {} {}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nCache-Control: no-store\r\nConnection: close\r\n\r\n{}", + response.status, + reason(response.status), + response.body.len(), + response.body + ); + let _ = stream.flush(); +} + +/// Serves `handle` on `listener` until the process ends, a thread per connection. +pub fn serve( + listener: TcpListener, + handle: impl Fn(&Request) -> Response + Send + Sync + 'static, +) -> std::io::Result<()> { + let handle = std::sync::Arc::new(handle); + std::thread::Builder::new() + .name("api".into()) + .spawn(move || { + for stream in listener.incoming().flatten() { + let handle = handle.clone(); + let _ = std::thread::Builder::new() + .name("api-client".into()) + .spawn(move || { + let _ = stream.set_read_timeout(Some(Duration::from_secs(10))); + let response = match read_request(&stream) { + Ok(request) => handle(&request), + Err(response) => response, + }; + write_response(&stream, &response); + }); + } + })?; + Ok(()) +} + +/// One request to `address`, with a bearer token; the status and the body. +pub fn request( + address: SocketAddr, + token: &str, + method: &str, + path: &str, + body: Option<&serde_json::Value>, + timeout: Duration, +) -> std::io::Result<(u16, String)> { + let mut stream = TcpStream::connect_timeout(&address, Duration::from_secs(5))?; + stream.set_read_timeout(Some(timeout))?; + let body = body.map(ToString::to_string).unwrap_or_default(); + write!( + stream, + "{method} {path} HTTP/1.1\r\nHost: {address}\r\nAuthorization: Bearer {token}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", + body.len() + )?; + stream.flush()?; + let mut text = String::new(); + stream.read_to_string(&mut text)?; + let (head, body) = text.split_once("\r\n\r\n").unwrap_or((&text, "")); + let status = head + .split_whitespace() + .nth(1) + .and_then(|s| s.parse().ok()) + .ok_or_else(|| std::io::Error::other("not an HTTP response"))?; + Ok((status, body.to_owned())) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn round_trip() { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let address = listener.local_addr().unwrap(); + serve(listener, |r| { + Response::json( + 200, + &serde_json::json!({ + "method": r.method, + "path": r.path, + "since": r.param("since"), + "auth": r.header("authorization"), + "body": String::from_utf8_lossy(&r.body), + }), + ) + }) + .unwrap(); + let (status, body) = request( + address, + "t0k", + "POST", + "/api/v1/command?since=7", + Some(&serde_json::json!({ "line": "list" })), + Duration::from_secs(5), + ) + .unwrap(); + assert_eq!(status, 200); + let v: serde_json::Value = serde_json::from_str(&body).unwrap(); + assert_eq!(v["method"], "POST"); + assert_eq!(v["path"], "/api/v1/command"); + assert_eq!(v["since"], "7"); + assert_eq!(v["auth"], "Bearer t0k"); + assert_eq!(v["body"], r#"{"line":"list"}"#); + } +} diff --git a/crates/horizon-server/src/lists.rs b/crates/horizon-server/src/lists.rs index b0dc5a375..398ccfe10 100644 --- a/crates/horizon-server/src/lists.rs +++ b/crates/horizon-server/src/lists.rs @@ -1,6 +1,6 @@ -//! `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. +//! `op`, `deop` and `whitelist`. While the server runs, the game owns the lists: the command goes to its +//! console. While it 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. use crate::{config, supervisor}; use horizon_server_files::user_lists::{NameAndId, OpEntry, OpList, WhiteEntry, WhiteList}; @@ -9,12 +9,11 @@ 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 Ok(_lock) = supervisor::lock(dir) else { + let mut words = vec![command.to_owned()]; + words.extend_from_slice(args); + return crate::cli::command(dir, &words); + }; 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"); @@ -140,14 +139,15 @@ mod tests { .unwrap() .contains("Alex") ); - // A running server owns the lists. + // A running server owns the lists: without its API, nothing changes. let lock = supervisor::lock(&dir).unwrap(); - assert!( - run(&dir, "op", &s(&["Alex"])) - .unwrap_err() - .contains("running") - ); + assert!(run(&dir, "op", &s(&["Alex"])).is_err()); drop(lock); + assert!( + !std::fs::read_to_string(dir.join("ops.json")) + .unwrap() + .contains("Alex") + ); std::fs::remove_dir_all(&dir).unwrap(); } } diff --git a/crates/horizon-server/src/main.rs b/crates/horizon-server/src/main.rs index 43d08589b..94fcc5a69 100644 --- a/crates/horizon-server/src/main.rs +++ b/crates/horizon-server/src/main.rs @@ -1,8 +1,11 @@ //! `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 api; +mod cli; mod config; mod engine; +mod http; mod init; mod lists; mod signals; @@ -20,11 +23,18 @@ Usage: horizon-server [--dir DIR] --yes) run Run the server in the foreground; type console commands, Ctrl-C stops it cleanly. It restarts the game if it crashes. + start Run the server in the background (its output goes to logs/supervisor.log) + stop, restart + status [--json] + Up or not, TPS, MSPT, players, RAM and CPU + cmd COMMAND... + Run a console command on the running server and print what it answers + logs [-f] [-n N] + The last N lines of the log (default 50); -f follows it 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) + Who may join (on the running server, or in the files when it is stopped) --dir DIR The server folder (default: the current folder) @@ -53,6 +63,12 @@ fn main() -> ExitCode { } Some("init") => init_answers(&args[1..]).and_then(|a| init::run(&dir, a)), Some("run") => supervisor::run(&dir), + Some("start") => cli::start(&dir), + Some("stop") => cli::stop(&dir, false), + Some("restart") => cli::stop(&dir, true), + Some("status") => cli::status(&dir, args[1..].iter().any(|a| a == "--json")), + Some("cmd") => cli::command(&dir, &args[1..]), + Some("logs") => logs(&dir, &args[1..]), Some("import") => import(&dir, &args[1..]), Some(command @ ("op" | "deop" | "whitelist")) => lists::run(&dir, command, &args[1..]), Some(other) => Err(format!( @@ -68,6 +84,25 @@ fn main() -> ExitCode { } } +fn logs(dir: &std::path::Path, args: &[String]) -> Result<(), String> { + let mut follow = false; + let mut count = 50; + let mut it = args.iter(); + while let Some(arg) = it.next() { + match arg.as_str() { + "-f" | "--follow" => follow = true, + "-n" => { + count = it + .next() + .and_then(|n| n.parse().ok()) + .ok_or("-n needs a number of lines")?; + } + other => return Err(format!("logs: unknown option {other}")), + } + } + cli::logs(dir, follow, count) +} + fn init_answers(args: &[String]) -> Result { let mut answers = init::Answers::default(); let mut it = args.iter(); diff --git a/crates/horizon-server/src/supervisor.rs b/crates/horizon-server/src/supervisor.rs index 376c4835e..bd35624f1 100644 --- a/crates/horizon-server/src/supervisor.rs +++ b/crates/horizon-server/src/supervisor.rs @@ -1,14 +1,21 @@ //! `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). +//! stdin, serves the control API, stops the game cleanly on Ctrl-C, SIGTERM or `stop`, and restarts it when +//! it crashes (docs/server.md, sections 2 and 7). -use crate::{config, config::Config, engine, signals}; +use crate::{ + api::{self, Phase, Shared}, + config, + config::Config, + engine, signals, +}; use horizon_server_files::java_properties::now_millis; +use serde_json::json; use std::{ fs::File, io::{BufRead, BufReader, Read, Write}, path::Path, process::{Child, ExitStatus}, - sync::mpsc, + sync::{Arc, atomic::Ordering, mpsc}, thread, time::{Duration, Instant}, }; @@ -22,15 +29,18 @@ 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) { +/// A line from the supervisor, in the game's log format (`[HH:mm:ss] [thread/LEVEL]: message`, UTC), on +/// stdout and in the log the API serves. +fn note(shared: &Shared, level: &str, message: &str) { let secs = now_millis().div_euclid(1000).rem_euclid(86_400); - println!( + let line = format!( "[{:02}:{:02}:{:02}] [Supervisor/{level}]: {message}", secs / 3600, secs / 60 % 60, secs % 60 ); + println!("{line}"); + shared.log.lock().unwrap().push(line); } /// The folder's lock: one supervisor per server folder. Released when the process ends, even by a crash. @@ -56,6 +66,8 @@ 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, + /// Asked to restart (`horizon-server restart`). + Restart, Crashed(ExitStatus), } @@ -65,6 +77,9 @@ pub fn run(dir: &Path) -> Result<(), String> { let program = engine::program(&config, dir)?; let resources = engine::resources(&config, dir, Some(&program))?; let _lock = lock(dir)?; + let shared = Shared::new(dir); + let _endpoint = api::start(shared.clone())?; + sample(shared.clone()); let console = console_lines(); let mut crashes: Vec = Vec::new(); loop { @@ -74,6 +89,7 @@ pub fn run(dir: &Path) -> Result<(), String> { .write_properties(dir) .map_err(|e| format!("server.properties: {e}"))?; note( + &shared, "INFO", &format!( "Starting {} with the game files in {}", @@ -81,11 +97,23 @@ pub fn run(dir: &Path) -> Result<(), String> { resources.display() ), ); + shared.set_phase(Phase::Starting); let mut child = engine::spawn(&program, &resources, dir) .map_err(|e| format!("{}: {e}", program.display()))?; - let exit = supervise(&mut child, &console); + { + let mut state = shared.state.lock().unwrap(); + state.engine_pid = Some(child.id()); + state.engine_started = Some(Instant::now()); + } + let exit = supervise(&shared, &mut child, &console); + { + let mut state = shared.state.lock().unwrap(); + state.engine_pid = None; + state.engine_started = None; + } match config::sync_back(dir, &written) { Ok(keys) if !keys.is_empty() => note( + &shared, "INFO", &format!( "Copied into server.toml what the game changed: {}", @@ -93,12 +121,22 @@ pub fn run(dir: &Path) -> Result<(), String> { ), ), Ok(_) => {} - Err(e) => note("WARN", &format!("Could not update server.toml: {e}")), + Err(e) => note( + &shared, + "WARN", + &format!("Could not update server.toml: {e}"), + ), } let status = match exit { Exit::Stopped => return Ok(()), + Exit::Restart => continue, Exit::Crashed(status) => status, }; + { + let mut state = shared.state.lock().unwrap(); + state.crashes += 1; + state.last_crash = Some(status.to_string()); + } if !config.engine.restart_on_crash { return Err(format!( "the game stopped unexpectedly ({status}); engine.restart_on_crash is off" @@ -116,15 +154,17 @@ pub fn run(dir: &Path) -> Result<(), String> { } let wait = backoff(crashes.len()); note( + &shared, "WARN", &format!( "The game stopped unexpectedly ({status}); restarting in {} s", wait.as_secs() ), ); + shared.set_phase(Phase::Restarting); let until = Instant::now() + wait; while Instant::now() < until { - if signals::requests() > 0 { + if signals::requests() > 0 || shared.stop.load(Ordering::SeqCst) { return Ok(()); } thread::sleep(Duration::from_millis(100)); @@ -156,8 +196,10 @@ fn console_lines() -> mpsc::Receiver { rx } -/// Copies the game's output to ours, line by line. -fn pump(from: impl Read + Send + 'static, to_stderr: bool) { +/// Copies the game's output to ours and to the API's log, line by line; the game's `Done` line means it +/// is up. +fn pump(shared: &Arc, from: impl Read + Send + 'static, to_stderr: bool) { + let shared = shared.clone(); let _ = thread::Builder::new() .name("engine-log".into()) .spawn(move || { @@ -167,27 +209,86 @@ fn pump(from: impl Read + Send + 'static, to_stderr: bool) { eprintln!("{line}"); } else { println!("{line}"); + if line.contains("/INFO]: Done (") { + let mut state = shared.state.lock().unwrap(); + if state.phase == Phase::Starting { + state.phase = Phase::Running; + } + } } + shared.log.lock().unwrap().push(line); + } + }); +} + +/// Every second, the game's RAM, CPU and status, for `status` and (later) the panel's graphs. +fn sample(shared: Arc) { + let _ = thread::Builder::new() + .name("sampler".into()) + .spawn(move || { + let mut control: Option = None; + let mut previous: Option<(u32, Instant, f64)> = None; + loop { + thread::sleep(Duration::from_secs(1)); + let (pid, running) = { + let state = shared.state.lock().unwrap(); + (state.engine_pid, state.phase == Phase::Running) + }; + let Some(pid) = pid else { + control = None; + previous = None; + shared.state.lock().unwrap().sample = serde_json::Value::Null; + continue; + }; + let now = Instant::now(); + let cpu = horizon_bench::cpu_seconds(pid); + let cpu_percent = match (previous, cpu) { + (Some((p, at, before)), Some(cpu)) if p == pid => { + Some((cpu - before) / now.duration_since(at).as_secs_f64() * 100.0) + } + _ => None, + }; + previous = cpu.map(|c| (pid, now, c)); + if !running { + control = None; + } else if control.is_none() { + control = engine::Control::connect(&shared.dir).ok(); + } + let game = control + .as_mut() + .map(|c| c.ask("server-status")) + .transpose() + .unwrap_or_else(|_| { + control = None; + None + }); + shared.state.lock().unwrap().sample = json!({ + "rss_bytes": horizon_bench::rss_bytes(pid), + "cpu_percent": cpu_percent, + "game": game, + }); } }); } /// 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 { +fn supervise(shared: &Arc, child: &mut Child, console: &mpsc::Receiver) -> Exit { if let Some(out) = child.stdout.take() { - pump(out, false); + pump(shared, out, false); } if let Some(err) = child.stderr.take() { - pump(err, true); + pump(shared, err, true); } let mut stdin = child.stdin.take(); let mut stopping: Option = None; + let mut restart = false; 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()); + shared.set_phase(Phase::Stopping); } if let Some(input) = stdin.as_mut() && writeln!(input, "{line}") @@ -198,21 +299,30 @@ fn supervise(child: &mut Child, console: &mpsc::Receiver) -> Exit { } } let requests = signals::requests(); - if requests > handled { - handled = requests; + let asked = requests > handled || shared.stop.swap(false, Ordering::SeqCst); + handled = requests; + if shared.restart.swap(false, Ordering::SeqCst) && stopping.is_none() { + restart = true; + note(shared, "INFO", "Restarting the server"); + stopping = Some(Instant::now()); + shared.set_phase(Phase::Restarting); + send_stop(&mut stdin); + } + if asked { + restart = false; if stopping.is_none() { - note("INFO", "Stopping the server"); + note(shared, "INFO", "Stopping the server"); stopping = Some(Instant::now()); - if let Some(input) = stdin.as_mut() { - let _ = writeln!(input, "stop").and_then(|()| input.flush()); - } + shared.set_phase(Phase::Stopping); + send_stop(&mut stdin); } else { - note("WARN", "Stopping the game at once, without saving"); + note(shared, "WARN", "Stopping the game at once, without saving"); let _ = child.kill(); } } if stopping.is_some_and(|t| t.elapsed() > STOP_TIMEOUT) { note( + shared, "WARN", &format!( "The game did not stop within {} s: killing it", @@ -220,19 +330,27 @@ fn supervise(child: &mut Child, console: &mpsc::Receiver) -> Exit { ), ); let _ = child.kill(); + stopping = Some(Instant::now()); } match child.try_wait() { + Ok(Some(_)) if restart => return Exit::Restart, 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}")); + note(shared, "ERROR", &format!("Lost track of the game: {e}")); return Exit::Stopped; } } } } +fn send_stop(stdin: &mut Option) { + if let Some(input) = stdin.as_mut() { + let _ = writeln!(input, "stop").and_then(|()| input.flush()); + } +} + #[cfg(test)] mod tests { use super::*; From 3510764cc645989ca3cd993310cbcaa1787e7e94 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 16 Oct 2026 20:10:58 +0200 Subject: [PATCH 04/14] horizon-server: backups, restore and automatic backups `backup [NAME]` zips the world and the settings into backups/; on a running server it turns saving off, flushes, zips and turns saving back on, so the game stays up. `restore BACKUP` puts a backup's world in place and keeps the current one in backups/replaced-