Merge perf/sp-open-to-lan (with main) into perf/sp-server-state

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-17 03:41:08 +02:00
60 changed files with 6774 additions and 131 deletions
+39
View File
@@ -74,6 +74,10 @@ pub struct DebugCharts {
pub bandwidth: SampleLogger,
/// `MinecraftServer.smoothedTickTimeMillis`.
pub smoothed_tick_ms: f32,
/// Connection's smoothed packets per second, sent then received.
pub packet_rates: [f32; 2],
packet_totals: [i64; 2],
packet_tick: u8,
previous_tick: Option<Instant>,
bytes_seen: Option<i64>,
}
@@ -113,6 +117,9 @@ impl DebugCharts {
self.previous_tick = None;
self.bytes_seen = None;
self.smoothed_tick_ms = 0.0;
self.packet_rates = [0.0; 2];
self.packet_totals = [0; 2];
self.packet_tick = 0;
}
/// One integrated server tick that started at `started` and ran its
/// tick method for `method` (`MinecraftServer.logFullTickTime` and
@@ -136,6 +143,17 @@ impl DebugCharts {
}
self.bytes_seen = Some(total);
}
/// `Connection.tickSecond`: sampled on the first tick, then every 20 ticks.
pub fn log_packets(&mut self, totals: [i64; 2]) {
if self.packet_tick == 0 {
for (i, total) in totals.into_iter().enumerate() {
let count = (total - self.packet_totals[i]).max(0) as f32;
self.packet_rates[i] = count + 0.75 * (self.packet_rates[i] - count);
}
self.packet_totals = totals;
}
self.packet_tick = (self.packet_tick + 1) % 20;
}
/// The charts along the bottom of the screen (`extractRenderState`):
/// frame times left and tick times right, or bandwidth left (remote
/// servers only) and ping right. `mspt` is the level's milliseconds
@@ -524,6 +542,27 @@ mod tests {
assert!(draws.contains(&fill(361, 174, 365, 178, 0xFF0A_141E)));
}
#[test]
fn packet_rates_follow_connection_smoothing_and_reset_between_worlds() {
let mut charts = DebugCharts::default();
charts.log_packets([80, 400]);
assert_eq!(charts.packet_rates, [20.0, 100.0]);
for _ in 1..20 {
charts.log_packets([180, 800]);
}
assert_eq!(charts.packet_rates, [20.0, 100.0]);
charts.log_packets([180, 800]);
assert_eq!(charts.packet_rates, [40.0, 175.0]);
for _ in 0..20 {
charts.log_packets([180, 800]);
}
assert_eq!(charts.packet_rates, [30.0, 131.25]);
charts.reset();
assert_eq!(charts.packet_rates, [0.0, 0.0]);
charts.log_packets([4, 8]);
assert_eq!(charts.packet_rates, [1.0, 2.0]);
}
#[test]
fn ticks_and_bandwidth_log_their_differences() {
let mut c = DebugCharts::default();
+38 -7
View File
@@ -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 {
+192
View File
@@ -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<Impact> {
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::<Vec<_>>();
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);
}
}
+24 -1
View File
@@ -318,6 +318,7 @@ impl Title {
x: f32,
y: f32,
) -> Action {
self.remember_direct_address();
if self.skip_opening() {
return Action::None;
}
@@ -472,7 +473,7 @@ impl Title {
_ => None,
};
if let Some(id) = id {
match screen.click(Some(id), 0.0, 0.0, (0.0, 0.0), &saves) {
match self.multiplayer_click(Some(id), 0.0, 0.0, (0.0, 0.0)) {
Outcome::Back => self.mode = Mode::Main,
Outcome::Connect(address) => return Action::Connect { address },
Outcome::None => {}
@@ -1432,6 +1433,28 @@ mod tests {
}
}
#[test]
fn horizon_direct_connection_remembers_the_address_after_leaving() {
let atlas =
HudAtlas::build(std::path::Path::new("/nonexistent/horizon-test-assets")).unwrap();
let saves =
std::env::temp_dir().join(format!("horizon-front-direct-{}", std::process::id()));
let mut title = Title::new(saves.clone(), &saves);
title.last_server = "localhost:25566".into();
title.mode = Mode::Multiplayer(Screen::list(&saves));
press(&mut title, &atlas, DIRECT);
assert_eq!(title.focused_field().unwrap().1, "localhost:25566");
*title.focused_field().unwrap().1 = "example.org:25567".into();
press(&mut title, &atlas, BACK);
press(&mut title, &atlas, DIRECT);
assert_eq!(title.focused_field().unwrap().1, "example.org:25567");
*title.focused_field().unwrap().1 = "localhost:25568".into();
press(&mut title, &atlas, NAV);
press(&mut title, &atlas, NAV + 2);
press(&mut title, &atlas, DIRECT);
assert_eq!(title.focused_field().unwrap().1, "localhost:25568");
}
#[test]
fn horizon_world_delete_confirms_and_keeps_the_selection_in_place() {
let atlas =
+33 -33
View File
@@ -41,6 +41,7 @@ mod entity_culling;
mod events;
mod explosion;
mod extras;
mod falling_damage;
mod fangs;
mod fireworks;
mod fishing;
@@ -652,6 +653,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<Box<([i32; 4], horizon_world::nbt::Tag)>>,
}
@@ -1970,6 +1972,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,
@@ -2022,6 +2025,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,
});
}
@@ -2277,14 +2285,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 {
@@ -2318,30 +2331,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()
}
@@ -3659,6 +3650,9 @@ impl Game<'_> {
) || self.book.is_some())
}
fn capture(&mut self, capture: bool) {
if !capture {
self.stop_mining();
}
// The real pointer takes over from an agent's.
self.agent_pointer = false;
let Some(window) = &self.window else { return };
@@ -6648,6 +6642,9 @@ impl Game<'_> {
std::env::current_dir()?.join("saves"),
&self.options.resources,
));
if let Some(title) = &mut self.title {
title.last_server = self.settings.file.string("lastServer");
}
self.capture(false);
Ok(())
}
@@ -9301,6 +9298,7 @@ impl ApplicationHandler for Game<'_> {
clicked
}
});
self.save_title_options();
if sound {
self.audio.play_button_click();
}
@@ -9539,6 +9537,7 @@ impl ApplicationHandler for Game<'_> {
if let Some(t) = self.title.as_mut() {
t.escape();
}
self.save_title_options();
}
_ => self.title_edit(event.text.as_deref(), false),
}
@@ -10323,10 +10322,11 @@ pub fn run() -> Result<()> {
game.open_world(&folder, None, Some(seed), creative, None)?;
}
None => {
let title = Title::new(
let mut title = Title::new(
std::env::current_dir()?.join("saves"),
&game.options.resources,
);
title.last_server = game.settings.file.string("lastServer");
// The launcher's opening, once per session and only in Horizon's style.
if horizon_client::ui_theme::horizon() && game.options.frames.is_none() {
title
@@ -2985,6 +2985,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",
+30 -15
View File
@@ -194,15 +194,17 @@ impl Game<'_> {
}
return;
};
let received = r
.session
.counters
.lock()
.unwrap()
.as_ref()
.map(|c| c.bytes_in.load(std::sync::atomic::Ordering::Relaxed));
if let Some(total) = received {
self.debug_charts.log_bandwidth(total);
let received = r.session.counters.lock().unwrap().as_ref().map(|c| {
let order = std::sync::atomic::Ordering::Relaxed;
[
c.bytes_in.load(order),
c.sent.load(order),
c.received.load(order),
]
});
if let Some([bytes, sent, received]) = received {
self.debug_charts.log_bandwidth(bytes);
self.debug_charts.log_packets([sent, received]);
}
if shown {
use horizon_protocol::packets::{play::Serverbound, status::Ping};
@@ -403,8 +405,9 @@ impl Game<'_> {
],
);
}
// tps: DebugEntryTps for the integrated server (it counts no packets).
if self.player.is_some() && self.remote.is_none() {
// tps: DebugEntryTps for local and remote connections.
if self.player.is_some() {
let [tx, rx] = self.debug_charts.packet_rates.map(|n| n.round() as i64);
let (target, status) = if self.clock.sprinting() {
("-".to_owned(), " (sprinting)")
} else if self.clock.stepping() {
@@ -417,10 +420,22 @@ impl Game<'_> {
} else {
(format!("{:.1}", 1000.0 / self.clock.rate()), "")
};
d.line(format!(
"Integrated server @ {:.1}/{target} ms{status}, 0 tx, 0 rx",
self.debug_charts.smoothed_tick_ms
));
if self.remote.is_none() || self.integrated.is_some() {
let tick_ms = self
.integrated
.as_ref()
.map_or(self.debug_charts.smoothed_tick_ms, |server| {
server.smoothed_tick_ms()
});
d.line(format!(
"Integrated server @ {tick_ms:.1}/{target} ms{status}, {tx} tx, {rx} rx",
));
} else if let Some(remote) = &self.remote {
d.line(format!(
"\"{}\" server{status}, {tx} tx, {rx} rx",
remote.brand
));
}
}
let (left, right) = d.columns(&self.debug_chart_lines());
let atlas = &self.atlas;
@@ -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<Option<Vec<String>>> = const { std::cell::RefCell::new(None) };
}
/// Runs `f` and returns the lines it logged.
fn capture_log(f: impl FnOnce()) -> Vec<String> {
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<bool> {
@@ -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<Instant>,
paused: bool,
}
impl Game<'_> {
@@ -471,14 +493,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 {
@@ -488,6 +514,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",
@@ -513,6 +540,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();
@@ -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 <line>` 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<String> = 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,
})
}
}
@@ -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::<Vec<_>>();
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.pack.assets.registry.state(block.state).cloned()
{
if falling_block::wear_anvil(&mut state) {
block.state = self
.pack
.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);
}
}
}
+12
View File
@@ -30,6 +30,18 @@ fn attack_range_contains(range: &serde_json::Value, distance: f64, creative: boo
}
impl Game<'_> {
/// Opening a screen stops breaking before the next game tick (which may pause).
pub(super) fn stop_mining(&mut self) {
let mut destroying = std::mem::take(&mut self.clicks.destroying);
destroying.stop(&mut GameHands {
game: self,
error: None,
});
self.clicks.destroying = destroying;
self.attack_clicks = 0;
self.stop_remote_mining();
self.mining = None;
}
/// `LivingEntity.swing` with `getModifiedSwingDuration`.
pub(super) fn swing_hand(&mut self, hand: Hand, animation: SwingAnimation) {
let effects = &self.potions.effects;
+11 -1
View File
@@ -31,7 +31,7 @@ use std::{
path::Path,
sync::{
Arc,
atomic::{AtomicBool, AtomicU16, Ordering},
atomic::{AtomicBool, AtomicU16, AtomicU32, Ordering},
mpsc::{Receiver, Sender, channel, sync_channel},
},
thread::JoinHandle,
@@ -47,6 +47,7 @@ struct Flags {
/// `IntegratedServer.getPort`: the port it is open to the LAN on, 0
/// while it is not.
published: AtomicU16,
smoothed_tick_ms: AtomicU32,
}
/// Work the window hands its server thread (`MinecraftServer.execute`).
@@ -61,6 +62,9 @@ pub(super) struct Integrated {
pub world_name: String,
}
impl Integrated {
pub fn smoothed_tick_ms(&self) -> f32 {
f32::from_bits(self.flags.smoothed_tick_ms.load(Ordering::Relaxed))
}
/// `IntegratedServer.tickServer` skips the world while the game is paused.
pub fn set_paused(&self, paused: bool) {
self.flags.paused.store(paused, Ordering::Relaxed);
@@ -322,7 +326,13 @@ impl Game<'_> {
// Only the connections run.
self.tick_lan();
} else {
let started = Instant::now();
self.tick()?;
self.debug_charts.log_tick(started, started.elapsed());
flags.smoothed_tick_ms.store(
self.debug_charts.smoothed_tick_ms.to_bits(),
Ordering::Relaxed,
);
}
self.apply_publish();
let rate = self.clock.rate().max(1.0);
+11
View File
@@ -17,6 +17,17 @@ pub(super) const CONTROL_HELP: &[&str] = &[
];
impl Game<'_> {
pub(super) fn save_title_options(&mut self) {
if let Some(title) = &self.title
&& title.last_server != self.settings.file.string("lastServer")
{
self.settings.file.set(
"lastServer",
horizon_client::options_file::V::Str(title.last_server.clone()),
);
self.settings.save(&Self::options_path());
}
}
/// `options-get` and `options-set`; None for other commands.
pub(super) fn options_control(&mut self, words: &[&str], line: &str) -> Result<Option<Value>> {
match words[0] {
+1
View File
@@ -354,6 +354,7 @@ impl Game<'_> {
}
if let Some(title) = self.title.as_mut() {
title.escape();
self.save_title_options();
return Ok(());
}
if self.sign_edit.is_some() {
+9 -12
View File
@@ -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))
+35 -10
View File
@@ -68,6 +68,7 @@ struct Lerp {
pub(super) struct Remote {
pub session: Session,
pub brand: String,
builtin: Arc<Builtin>,
lang: Arc<Language>,
registries: Arc<Dynamic>,
@@ -153,7 +154,20 @@ fn number_format(f: &play::NumberFormat) -> horizon_client::scoreboard::NumberFo
impl Game<'_> {
/// Leave the title for a server (ConnectScreen): an empty world fed by the connection.
pub(super) fn connect_server(&mut self, address: &str, name: &str) -> Result<()> {
self.join_server(address, name, None)
if let Err(error) = self.join_server(address, name, None) {
log::warn!("Horizon: could not join server: {error}");
if self.title.is_none() {
self.title = Some(horizon_client::title::Title::new(
std::env::current_dir()?.join("saves"),
&self.options.resources,
));
}
if let Some(title) = &mut self.title {
title.failed(error);
}
self.capture(false);
}
Ok(())
}
/// Join single player's integrated server through memory.
pub(super) fn connect_local(
@@ -173,7 +187,7 @@ impl Game<'_> {
let root = self.options.resources.clone();
let builtin = Builtin::find(&root)
.and_then(|p| Builtin::load(&p).ok())
.ok_or("registries.json not found next to the resources; run the data generator reports (horizon-prepare)")?;
.ok_or("Resources are incomplete: registries.json is missing or invalid. Click \"Prepare again\" in the launcher (or run horizon-prepare), then try again.")?;
let lang = Arc::new(horizon_client::net::load_language(&root));
let view = self.settings.render_distance.clamp(2, 32) as i8;
if local.is_none() {
@@ -238,6 +252,7 @@ impl Game<'_> {
self.apply_settings();
self.remote = Some(Remote {
session,
brand: "unknown".into(),
builtin: Arc::new(builtin),
lang,
registries: Arc::new(Dynamic::default()),
@@ -330,6 +345,7 @@ impl Game<'_> {
}
let saves = std::env::current_dir()?.join("saves");
let mut title = horizon_client::title::Title::new(saves.clone(), &self.options.resources);
title.last_server = self.settings.file.string("lastServer");
if single_player && reason.is_none() {
self.title = Some(title);
self.capture(false);
@@ -467,6 +483,11 @@ impl Game<'_> {
r.status = format!("Joined as {name}; loading terrain...");
}
}
Event::Brand(brand) => {
if let Some(remote) = &mut self.remote {
remote.brand = brand;
}
}
Event::Reconfigured(registries) => self.set_registries(registries),
Event::DecodeError(e) => {
if let Some(r) = self.remote.as_mut() {
@@ -2101,6 +2122,17 @@ impl Game<'_> {
}
}
pub(super) fn stop_remote_mining(&mut self) {
if let Some((pos, _, _)) = self.remote.as_mut().and_then(|r| r.destroying.take()) {
self.send(S::PlayerAction(play::PlayerAction {
action: 2,
pos,
direction: 0,
sequence: 0,
}));
}
}
/// MultiPlayerGameMode.startDestroyBlock / continueDestroyBlock.
fn remote_mining(&mut self) {
let Some(r) = self.remote.as_mut() else {
@@ -2111,14 +2143,7 @@ impl Game<'_> {
}
let chatting = r.chat_input.is_some();
if !self.left || self.screen != Screen::Playing || chatting {
if let Some((pos, _, _)) = r.destroying.take() {
self.send(S::PlayerAction(play::PlayerAction {
action: 2,
pos,
direction: 0,
sequence: 0,
}));
}
self.stop_remote_mining();
self.mining = None;
return;
}
+6 -6
View File
@@ -146,9 +146,6 @@ impl Game<'_> {
.find(|b| b.5 && ui::hovered(self.cursor, b.0, b.1, b.2, 20.0))
.map(|b| b.4)
};
if hit.is_some() && !horizon_client::ui_theme::horizon() {
self.audio.play_button_click();
}
match hit {
Some(0) => {
self.screen = Screen::Playing;
@@ -168,6 +165,9 @@ impl Game<'_> {
Some(2) => self.close_world()?,
_ => {}
}
if hit.is_some() && !horizon_client::ui_theme::horizon() {
self.audio.play_button_click();
}
Ok(())
}
/// DeathScreen: gradient, the title at double size, the cause and score.
@@ -260,9 +260,6 @@ impl Game<'_> {
.into_iter()
.find(|d| ui::hovered(self.cursor, d.0, d.1, 200.0, 20.0))
.map(|d| d.3);
if hit.is_some() {
self.audio.play_button_click();
}
match hit {
Some(0) if self.remote.is_some() => {
self.ui.death_text = None;
@@ -292,6 +289,9 @@ impl Game<'_> {
Some(1) => self.close_world()?,
_ => {}
}
if hit.is_some() {
self.audio.play_button_click();
}
Ok(())
}
}
+2 -1
View File
@@ -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;
@@ -147,7 +148,7 @@ pub mod screen_draw;
pub mod screen_effects;
pub mod screen_layout;
pub mod sculk;
pub mod server;
pub use horizon_server_files as server;
pub mod settings;
pub mod shader_pack;
pub mod shadows;
+7
View File
@@ -509,6 +509,7 @@ pub enum DamageKind {
Fireball,
Explosion,
Fall,
FallingBlock,
OnFire,
InFire,
Lava,
@@ -1614,6 +1615,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
+42 -2
View File
@@ -29,6 +29,8 @@ use std::{
pub enum Event {
/// Progress text for the connecting screen.
Status(String),
/// The server's `minecraft:brand` custom payload.
Brand(String),
/// Configuration finished: the play state begins with these registries.
Joined {
registries: Arc<Dynamic>,
@@ -374,7 +376,7 @@ fn run(
.map_err(e)?;
let (mut reader, writer) = c.split();
*shared_writer.lock().unwrap() = Some(writer);
let registries = configure(&mut reader, shared_writer, lang)?;
let registries = configure(&mut reader, shared_writer, lang, send)?;
let _ = send.send(Event::Joined {
registries: Arc::new(registries),
uuid: profile.uuid,
@@ -413,10 +415,13 @@ fn run(
}
play::Clientbound::StartConfiguration(_) => {
reply(play::Serverbound::ConfigurationAcknowledged(Empty));
let registries = configure(&mut reader, shared_writer, lang)?;
let registries = configure(&mut reader, shared_writer, lang, send)?;
let _ = send.send(Event::Reconfigured(Arc::new(registries)));
}
play::Clientbound::Disconnect(d) => return Ok(plain(&d.reason, lang)),
play::Clientbound::CustomPayload(p) if p.channel == "minecraft:brand" => {
receive_brand(&p, send);
}
other => {
if send.send(Event::Packet(Box::new(other))).is_err() {
return Ok("Disconnected".into());
@@ -432,6 +437,7 @@ fn configure(
reader: &mut ConnReader,
writer: &Mutex<Option<ConnWriter>>,
lang: &Language,
send: &Sender<Event>,
) -> Result<Dynamic, String> {
let mut registries = Dynamic::default();
let reply = |p: cfg::Serverbound| -> Result<(), String> {
@@ -444,6 +450,7 @@ fn configure(
let (id, payload) = reader.recv().map_err(|e| e.to_string())?;
match cfg::Clientbound::decode(id, &payload).map_err(|e| e.to_string())? {
cfg::Clientbound::KeepAlive(k) => reply(cfg::Serverbound::KeepAlive(k))?,
cfg::Clientbound::CustomPayload(p) => receive_brand(&p, send),
cfg::Clientbound::Ping(p) => reply(cfg::Serverbound::Pong(p))?,
// Know no packs: the server then sends every registry entry in full.
cfg::Clientbound::SelectKnownPacks(_) => {
@@ -477,6 +484,14 @@ fn configure(
}
}
fn receive_brand(payload: &cfg::CustomPayload, send: &Sender<Event>) {
if payload.channel == "minecraft:brand"
&& let Ok(brand) = horizon_protocol::buf::Reader::new(&payload.data).string(32767)
{
let _ = send.send(Event::Brand(brand));
}
}
/// The minecraft:brand payload: a string naming the client.
fn brand() -> Vec<u8> {
let mut w = horizon_protocol::buf::Writer::new();
@@ -565,3 +580,28 @@ pub fn ping(address: &str, timeout: Duration) -> Result<(serde_json::Value, u128
let _ = c.recv().map_err(e)?;
Ok((json, start.elapsed().as_millis()))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn server_brand_payload_is_decoded_and_invalid_or_unrelated_payloads_are_ignored() {
let (send, events) = channel();
let mut writer = horizon_protocol::buf::Writer::new();
writer.string("vanilla");
let mut payload = cfg::CustomPayload {
channel: "minecraft:brand".into(),
data: writer.data,
};
receive_brand(&payload, &send);
assert!(matches!(events.try_recv(), Ok(Event::Brand(brand)) if brand == "vanilla"));
payload.channel = "example:other".into();
receive_brand(&payload, &send);
assert!(events.try_recv().is_err());
payload.channel = "minecraft:brand".into();
payload.data = vec![0xff];
receive_brand(&payload, &send);
assert!(events.try_recv().is_err());
}
}
-38
View File
@@ -1,38 +0,0 @@
//! eula.txt (net.minecraft.server.Eula): the server runs only once the file
//! says `eula=true`; a file that is missing or unreadable is replaced with
//! the default one and counts as not agreed.
use super::java_properties::{Properties, date_string, now_millis};
use std::path::Path;
/// CommonLinks.EULA.
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 {
let mut p = Properties::default();
p.put("eula", "false".into());
p.store(
Some(&format!(
"By changing the setting below to TRUE you are indicating your agreement to our EULA ({EULA_LINK})."
)),
&date_string(millis),
true,
)
}
/// Eula.readFile; `Err` carries the warning vanilla logs.
pub fn agreed(path: &Path) -> Result<bool, String> {
let read = std::fs::read(path)
.map_err(|e| e.to_string())
.and_then(|b| Properties::load_latin1(&b).map_err(|e| e.to_string()));
match read {
Ok(p) => Ok(p
.get("eula")
.unwrap_or("false")
.eq_ignore_ascii_case("true")),
Err(_) => {
let _ = std::fs::write(path, default_file(now_millis()));
Err(format!("Failed to load {}", path.display()))
}
}
}
@@ -1,445 +0,0 @@
//! `java.util.Properties` as the dedicated server uses it: `load` (the
//! LineReader and loadConvert of the JDK), `store` with the sorted entries the
//! JDK writes since Java 18, and `java.util.Date.toString` for the timestamp
//! comment. Values are kept in a map keyed like Java's Hashtable; iteration
//! for storing sorts by `String.compareTo` (UTF-16 code units).
use std::collections::HashMap;
/// A malformed `\uxxxx` escape: Properties.load throws IllegalArgumentException.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Malformed;
impl std::fmt::Display for Malformed {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("Malformed \\uxxxx encoding.")
}
}
impl std::error::Error for Malformed {}
/// The key/value pairs, last occurrence winning (Hashtable.put).
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Properties {
pub map: HashMap<String, String>,
}
impl Properties {
pub fn get(&self, key: &str) -> Option<&str> {
self.map.get(key).map(String::as_str)
}
pub fn put(&mut self, key: &str, value: String) {
self.map.insert(key.to_owned(), value);
}
pub fn remove(&mut self, key: &str) -> Option<String> {
self.map.remove(key)
}
/// Properties.load(Reader) over already decoded characters.
pub fn load(text: &[char]) -> Result<Self, Malformed> {
let mut out = Self::default();
let mut reader = LineReader {
chars: text,
pos: 0,
};
while let Some(line) = reader.read_line() {
let mut key_len = 0;
let mut value_start = line.len();
let mut has_sep = false;
let mut preceding_backslash = false;
while key_len < line.len() {
let c = line[key_len];
if (c == '=' || c == ':') && !preceding_backslash {
value_start = key_len + 1;
has_sep = true;
break;
} else if (c == ' ' || c == '\t' || c == '\u{c}') && !preceding_backslash {
value_start = key_len + 1;
break;
}
if c == '\\' {
preceding_backslash = !preceding_backslash;
} else {
preceding_backslash = false;
}
key_len += 1;
}
while value_start < line.len() {
let c = line[value_start];
if c != ' ' && c != '\t' && c != '\u{c}' {
if !has_sep && (c == '=' || c == ':') {
has_sep = true;
} else {
break;
}
}
value_start += 1;
}
let key = load_convert(&line[..key_len])?;
let value = load_convert(&line[value_start..])?;
out.map.insert(key, value);
}
Ok(out)
}
/// Settings.loadFromFile: UTF-8 with errors reported, falling back to
/// ISO-8859-1 for the whole file. A missing file is an empty set.
pub fn load_file(bytes: &[u8]) -> Result<Self, Malformed> {
match std::str::from_utf8(bytes) {
Ok(s) => Self::load(&s.chars().collect::<Vec<_>>()),
Err(_) => Self::load(&bytes.iter().map(|&b| char::from(b)).collect::<Vec<_>>()),
}
}
/// Properties.load(InputStream): ISO-8859-1.
pub fn load_latin1(bytes: &[u8]) -> Result<Self, Malformed> {
Self::load(&bytes.iter().map(|&b| char::from(b)).collect::<Vec<_>>())
}
/// Properties.store(Writer, comments): comment, date, then the entries
/// sorted by key, with `escUnicode` off (the Writer variant) or on (the
/// OutputStream variant, whose bytes are ISO-8859-1).
pub fn store(&self, comment: Option<&str>, date: &str, esc_unicode: bool) -> String {
let nl = line_separator();
let mut out = String::new();
if let Some(c) = comment {
write_comments(&mut out, c, nl);
}
out.push('#');
out.push_str(date);
out.push_str(nl);
let mut keys: Vec<&String> = self.map.keys().collect();
keys.sort_by(|a, b| a.encode_utf16().cmp(b.encode_utf16()));
for key in keys {
out.push_str(&save_convert(key, true, esc_unicode));
out.push('=');
out.push_str(&save_convert(&self.map[key], false, esc_unicode));
out.push_str(nl);
}
out
}
}
/// System.lineSeparator().
pub fn line_separator() -> &'static str {
if cfg!(windows) { "\r\n" } else { "\n" }
}
struct LineReader<'a> {
chars: &'a [char],
pos: usize,
}
impl LineReader<'_> {
/// LineReader.readLine: one logical line, leading whitespace skipped,
/// comments and blank lines dropped, backslash-newline continuations joined.
fn read_line(&mut self) -> Option<Vec<char>> {
let mut line: Vec<char> = Vec::new();
let mut skip_white = true;
let mut appended = false;
let mut backslash = false;
let chars = self.chars;
loop {
if self.pos >= chars.len() {
if line.is_empty() {
return None;
}
if backslash {
line.pop();
}
return Some(line);
}
let c = chars[self.pos];
self.pos += 1;
if skip_white {
if c == ' ' || c == '\t' || c == '\u{c}' {
continue;
}
if !appended && (c == '\r' || c == '\n') {
continue;
}
skip_white = false;
appended = false;
}
if line.is_empty() && (c == '#' || c == '!') {
loop {
let &d = chars.get(self.pos)?;
self.pos += 1;
if d == '\r' || d == '\n' {
break;
}
}
skip_white = true;
continue;
}
if c != '\n' && c != '\r' {
line.push(c);
backslash = if c == '\\' { !backslash } else { false };
continue;
}
if line.is_empty() {
skip_white = true;
continue;
}
if self.pos >= chars.len() {
if backslash {
line.pop();
}
return Some(line);
}
if backslash {
line.pop();
skip_white = true;
appended = true;
backslash = false;
if c == '\r' && chars[self.pos] == '\n' {
self.pos += 1;
}
} else {
return Some(line);
}
}
}
}
fn load_convert(input: &[char]) -> Result<String, Malformed> {
let mut out = String::with_capacity(input.len());
let mut units: Vec<u16> = Vec::new();
let flush = |units: &mut Vec<u16>, out: &mut String| {
if !units.is_empty() {
out.extend(char::decode_utf16(units.drain(..)).map(|r| r.unwrap_or('\u{fffd}')));
}
};
let mut i = 0;
while i < input.len() {
let c = input[i];
i += 1;
if c != '\\' {
flush(&mut units, &mut out);
out.push(c);
continue;
}
let Some(&next) = input.get(i) else {
// A trailing lone backslash is dropped.
break;
};
i += 1;
if next == 'u' {
if i + 4 > input.len() {
return Err(Malformed);
}
let mut value = 0u32;
for &h in &input[i..i + 4] {
value = value * 16 + h.to_digit(16).ok_or(Malformed)?;
}
i += 4;
units.push(value as u16);
continue;
}
flush(&mut units, &mut out);
out.push(match next {
't' => '\t',
'r' => '\r',
'n' => '\n',
'f' => '\u{c}',
other => other,
});
}
flush(&mut units, &mut out);
Ok(out)
}
fn save_convert(s: &str, escape_space: bool, esc_unicode: bool) -> String {
let mut out = String::with_capacity(s.len() * 2);
for (index, c) in s.encode_utf16().enumerate() {
if c > 61 && c < 127 {
if c == u16::from(b'\\') {
out.push_str("\\\\");
} else {
out.push(char::from(c as u8));
}
continue;
}
match c {
0x20 => {
if index == 0 || escape_space {
out.push('\\');
}
out.push(' ');
}
0x09 => out.push_str("\\t"),
0x0a => out.push_str("\\n"),
0x0d => out.push_str("\\r"),
0x0c => out.push_str("\\f"),
0x3d | 0x3a | 0x23 | 0x21 => {
out.push('\\');
out.push(char::from(c as u8));
}
_ => {
if (!(0x20..=0x7e).contains(&c)) && esc_unicode {
out.push_str(&format!("\\u{c:04X}"));
} else {
push_unit(&mut out, c);
}
}
}
}
fix_surrogates(out)
}
/// Units are pushed one at a time; surrogate halves are joined afterwards.
fn push_unit(out: &mut String, unit: u16) {
match char::from_u32(u32::from(unit)) {
Some(c) => out.push(c),
None => out.push_str(&format!("\u{0}{unit:04x}\u{0}")),
}
}
fn fix_surrogates(s: String) -> String {
if !s.contains('\u{0}') {
return s;
}
let mut units: Vec<u16> = Vec::new();
let mut parts = s.split('\u{0}');
let mut odd = false;
for part in parts.by_ref() {
if odd {
units.push(u16::from_str_radix(part, 16).unwrap_or(0xfffd));
} else {
units.extend(part.encode_utf16());
}
odd = !odd;
}
String::from_utf16_lossy(&units)
}
/// Properties.writeComments.
fn write_comments(out: &mut String, comments: &str, nl: &str) {
out.push('#');
let units: Vec<u16> = comments.encode_utf16().collect();
let mut current = 0;
let mut last = 0;
let len = units.len();
while current < len {
let c = units[current];
if c > 0x00ff || c == u16::from(b'\n') || c == u16::from(b'\r') {
if last != current {
out.push_str(&String::from_utf16_lossy(&units[last..current]));
}
if c > 0x00ff {
out.push_str(&format!("\\u{c:04X}"));
} else {
out.push_str(nl);
if c == u16::from(b'\r')
&& current != len - 1
&& units[current + 1] == u16::from(b'\n')
{
current += 1;
}
if current == len - 1
|| units[current + 1] != u16::from(b'#')
&& units[current + 1] != u16::from(b'!')
{
out.push('#');
}
}
last = current + 1;
}
current += 1;
}
if last != current {
out.push_str(&String::from_utf16_lossy(&units[last..current]));
}
out.push_str(nl);
}
/// Civil date from days since 1970-01-01 (proleptic Gregorian).
pub fn civil_from_days(days: i64) -> (i64, u32, u32) {
let z = days + 719_468;
let era = z.div_euclid(146_097);
let doe = z - era * 146_097;
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
let y = yoe + era * 400;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let d = (doy - (153 * mp + 2) / 5 + 1) as u32;
let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
(if m <= 2 { y + 1 } else { y }, m, d)
}
/// Days since 1970-01-01 of a civil date.
pub fn days_from_civil(y: i64, m: u32, d: u32) -> i64 {
let y = if m <= 2 { y - 1 } else { y };
let era = y.div_euclid(400);
let yoe = y - era * 400;
let m = i64::from(m);
let doy = (153 * (if m > 2 { m - 3 } else { m + 9 }) + 2) / 5 + i64::from(d) - 1;
let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
era * 146_097 + doe - 719_468
}
/// Milliseconds since the epoch, now.
pub fn now_millis() -> i64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_millis() as i64)
}
/// java.util.Date.toString in UTC: "EEE MMM dd HH:mm:ss zzz yyyy".
pub fn date_string(millis: i64) -> String {
const DAYS: [&str; 7] = ["Thu", "Fri", "Sat", "Sun", "Mon", "Tue", "Wed"];
const MONTHS: [&str; 12] = [
"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
];
let secs = millis.div_euclid(1000);
let days = secs.div_euclid(86_400);
let rem = secs.rem_euclid(86_400);
let (y, m, d) = civil_from_days(days);
format!(
"{} {} {:02} {:02}:{:02}:{:02} UTC {}",
DAYS[days.rem_euclid(7) as usize],
MONTHS[m as usize - 1],
d,
rem / 3600,
rem / 60 % 60,
rem % 60,
y
)
}
#[cfg(test)]
mod tests {
use super::*;
fn load(s: &str) -> Properties {
Properties::load(&s.chars().collect::<Vec<_>>()).unwrap()
}
#[test]
fn parses_like_java() {
let p = load(
"# comment\n ! other\nkey=value\na:b\nc d\n e = f g \nmulti=one\\\n two\nesc=\\u00e9\\t\\x\nempty\nlast=1\nlast=2\r\ncr=1\rnext=2",
);
assert_eq!(p.get("key"), Some("value"));
assert_eq!(p.get("a"), Some("b"));
assert_eq!(p.get("c"), Some("d"));
assert_eq!(p.get("e"), Some("f g "));
assert_eq!(p.get("multi"), Some("onetwo"));
assert_eq!(p.get("esc"), Some("é\tx"));
assert_eq!(p.get("empty"), Some(""));
assert_eq!(p.get("last"), Some("2"));
assert_eq!(p.get("cr"), Some("1"));
assert_eq!(p.get("next"), Some("2"));
}
#[test]
fn stores_sorted_and_escaped() {
let mut p = Properties::default();
p.put("level-type", "minecraft:normal".into());
p.put("motd", " A=B#".into());
p.put("b key", "é".into());
let s = p.store(Some("Minecraft server properties"), "DATE", false);
assert_eq!(
s,
"#Minecraft server properties\n#DATE\nb\\ key=é\nlevel-type=minecraft\\:normal\nmotd=\\ A\\=B\\#\n"
);
assert!(p.store(None, "D", true).contains("b\\ key=\\u00E9"));
}
#[test]
fn dates() {
assert_eq!(date_string(0), "Thu Jan 01 00:00:00 UTC 1970");
assert_eq!(days_from_civil(2026, 10, 12), 20_738);
assert_eq!(civil_from_days(20_738), (2026, 10, 12));
}
}
-385
View File
@@ -1,385 +0,0 @@
//! The JSON the dedicated server reads and writes through Gson: a tree that
//! keeps object member order and the literal text of numbers (Gson's
//! LazilyParsedNumber), a strict parser (`Strictness.STRICT`), and Gson's
//! compact (`JsonElement.toString`) and pretty, HTML-safe writers.
#[derive(Clone, Debug, PartialEq)]
pub enum Json {
Null,
Bool(bool),
/// The number's literal text.
Number(String),
String(String),
Array(Vec<Json>),
/// Members in insertion order; a repeated name replaces the value in place.
Object(Vec<(String, Json)>),
}
impl Json {
pub fn get(&self, key: &str) -> Option<&Json> {
match self {
Json::Object(m) => m.iter().find(|(k, _)| k == key).map(|(_, v)| v),
_ => None,
}
}
/// JsonElement.getAsString for primitives.
pub fn as_string(&self) -> Option<String> {
match self {
Json::String(s) | Json::Number(s) => Some(s.clone()),
Json::Bool(b) => Some(b.to_string()),
_ => None,
}
}
/// JsonObject.addProperty: a null value is JsonNull, which the writers skip.
pub fn add(&mut self, key: &str, value: Json) {
if let Json::Object(m) = self {
if let Some(slot) = m.iter_mut().find(|(k, _)| k == key) {
slot.1 = value;
} else {
m.push((key.to_owned(), value));
}
}
}
/// JsonElement.toString: compact, not HTML-safe, nulls in objects written.
pub fn compact(&self) -> String {
let mut out = String::new();
self.write_compact(&mut out);
out
}
fn write_compact(&self, out: &mut String) {
match self {
Json::Null => out.push_str("null"),
Json::Bool(b) => out.push_str(if *b { "true" } else { "false" }),
Json::Number(n) => out.push_str(n),
Json::String(s) => quote(out, s, false),
Json::Array(items) => {
out.push('[');
for (i, v) in items.iter().enumerate() {
if i > 0 {
out.push(',');
}
v.write_compact(out);
}
out.push(']');
}
Json::Object(m) => {
out.push('{');
for (i, (k, v)) in m.iter().enumerate() {
if i > 0 {
out.push(',');
}
quote(out, k, false);
out.push(':');
v.write_compact(out);
}
out.push('}');
}
}
}
/// `new GsonBuilder().setPrettyPrinting().create().toJson(element, writer)`:
/// two-space indents, HTML-safe strings, null members skipped.
pub fn pretty(&self) -> String {
let mut out = String::new();
self.write_pretty(&mut out, 0);
out
}
fn write_pretty(&self, out: &mut String, depth: usize) {
let indent = |out: &mut String, d: usize| {
out.push('\n');
for _ in 0..d {
out.push_str(" ");
}
};
match self {
Json::Array(items) => {
out.push('[');
if items.is_empty() {
out.push(']');
return;
}
for (i, v) in items.iter().enumerate() {
if i > 0 {
out.push(',');
}
indent(out, depth + 1);
v.write_pretty(out, depth + 1);
}
indent(out, depth);
out.push(']');
}
Json::Object(m) => {
out.push('{');
let members: Vec<_> = m.iter().filter(|(_, v)| *v != Json::Null).collect();
if members.is_empty() {
out.push('}');
return;
}
for (i, (k, v)) in members.iter().enumerate() {
if i > 0 {
out.push(',');
}
indent(out, depth + 1);
quote(out, k, true);
out.push_str(": ");
v.write_pretty(out, depth + 1);
}
indent(out, depth);
out.push('}');
}
Json::String(s) => quote(out, s, true),
other => other.write_compact(out),
}
}
}
/// JsonWriter.string.
fn quote(out: &mut String, s: &str, html_safe: bool) {
out.push('"');
for c in s.chars() {
match c {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
'\t' => out.push_str("\\t"),
'\u{8}' => out.push_str("\\b"),
'\n' => out.push_str("\\n"),
'\r' => out.push_str("\\r"),
'\u{c}' => out.push_str("\\f"),
'\u{2028}' => out.push_str("\\u2028"),
'\u{2029}' => out.push_str("\\u2029"),
'<' | '>' | '&' | '=' | '\'' if html_safe => {
out.push_str(&format!("\\u{:04x}", c as u32));
}
c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
c => out.push(c),
}
}
out.push('"');
}
/// A strict JSON document: one value, optionally followed only by whitespace
/// when `whole` is set.
pub fn parse(text: &str, whole: bool) -> Result<Json, String> {
let chars: Vec<char> = text.chars().collect();
let mut p = Parser { c: &chars, i: 0 };
let v = p.value()?;
if whole {
p.ws();
if p.i != chars.len() {
return Err("Did not consume the entire document.".into());
}
}
Ok(v)
}
struct Parser<'a> {
c: &'a [char],
i: usize,
}
impl Parser<'_> {
fn ws(&mut self) {
while self
.c
.get(self.i)
.is_some_and(|c| matches!(c, ' ' | '\t' | '\n' | '\r'))
{
self.i += 1;
}
}
fn value(&mut self) -> Result<Json, String> {
self.ws();
match self.c.get(self.i) {
None => Err("End of input".into()),
Some('{') => {
self.i += 1;
let mut m: Vec<(String, Json)> = Vec::new();
self.ws();
if self.c.get(self.i) == Some(&'}') {
self.i += 1;
return Ok(Json::Object(m));
}
loop {
self.ws();
if self.c.get(self.i) != Some(&'"') {
return Err("Expected name".into());
}
let k = self.string()?;
self.ws();
if self.c.get(self.i) != Some(&':') {
return Err("Expected ':'".into());
}
self.i += 1;
let v = self.value()?;
if let Some(slot) = m.iter_mut().find(|(n, _)| *n == k) {
slot.1 = v;
} else {
m.push((k, v));
}
self.ws();
match self.c.get(self.i) {
Some(',') => self.i += 1,
Some('}') => {
self.i += 1;
return Ok(Json::Object(m));
}
_ => return Err("Unterminated object".into()),
}
}
}
Some('[') => {
self.i += 1;
let mut items = Vec::new();
self.ws();
if self.c.get(self.i) == Some(&']') {
self.i += 1;
return Ok(Json::Array(items));
}
loop {
items.push(self.value()?);
self.ws();
match self.c.get(self.i) {
Some(',') => self.i += 1,
Some(']') => {
self.i += 1;
return Ok(Json::Array(items));
}
_ => return Err("Unterminated array".into()),
}
}
}
Some('"') => Ok(Json::String(self.string()?)),
Some(_) => {
let start = self.i;
while self
.c
.get(self.i)
.is_some_and(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '+' | '.'))
{
self.i += 1;
}
let word: String = self.c[start..self.i].iter().collect();
match word.as_str() {
"true" => Ok(Json::Bool(true)),
"false" => Ok(Json::Bool(false)),
"null" => Ok(Json::Null),
w if is_number(w) => Ok(Json::Number(w.to_owned())),
_ => Err(format!("Malformed JSON at {start}")),
}
}
}
}
fn string(&mut self) -> Result<String, String> {
self.i += 1;
let mut out = String::new();
let mut units: Vec<u16> = Vec::new();
loop {
let Some(&c) = self.c.get(self.i) else {
return Err("Unterminated string".into());
};
self.i += 1;
if c != '\\' && !units.is_empty() {
out.push_str(&String::from_utf16_lossy(&units));
units.clear();
}
match c {
'"' => {
out.push_str(&String::from_utf16_lossy(&units));
return Ok(out);
}
'\\' => {
let Some(&e) = self.c.get(self.i) else {
return Err("Unterminated escape".into());
};
self.i += 1;
if e == 'u' {
let hex: String = self
.c
.get(self.i..self.i + 4)
.ok_or("bad escape")?
.iter()
.collect();
let v = u16::from_str_radix(&hex, 16).map_err(|e| e.to_string())?;
self.i += 4;
units.push(v);
continue;
}
if !units.is_empty() {
out.push_str(&String::from_utf16_lossy(&units));
units.clear();
}
out.push(match e {
't' => '\t',
'b' => '\u{8}',
'n' => '\n',
'r' => '\r',
'f' => '\u{c}',
'"' | '\\' | '/' => e,
_ => return Err("Invalid escape sequence".into()),
});
}
c if (c as u32) < 0x20 => return Err("Unescaped control character".into()),
c => out.push(c),
}
}
}
}
/// JSON number syntax (JsonReader.peekNumber in strict mode).
fn is_number(w: &str) -> bool {
let b = w.as_bytes();
let mut i = 0;
if b.get(i) == Some(&b'-') {
i += 1;
}
match b.get(i) {
Some(b'0') => i += 1,
Some(b'1'..=b'9') => {
while b.get(i).is_some_and(u8::is_ascii_digit) {
i += 1;
}
}
_ => return false,
}
if b.get(i) == Some(&b'.') {
i += 1;
if !b.get(i).is_some_and(u8::is_ascii_digit) {
return false;
}
while b.get(i).is_some_and(u8::is_ascii_digit) {
i += 1;
}
}
if matches!(b.get(i), Some(b'e' | b'E')) {
i += 1;
if matches!(b.get(i), Some(b'+' | b'-')) {
i += 1;
}
if !b.get(i).is_some_and(u8::is_ascii_digit) {
return false;
}
while b.get(i).is_some_and(u8::is_ascii_digit) {
i += 1;
}
}
i == b.len()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn round_trips() {
let v = parse(r#" { "a" : 1.50 , "b":[true,null,"x<"] , "a": 2 } "#, true).unwrap();
assert_eq!(v.compact(), r#"{"a":2,"b":[true,null,"x<"]}"#);
let mut o = Json::Object(vec![]);
o.add("name", Json::String("a=b".into()));
o.add("reason", Json::Null);
assert_eq!(
Json::Array(vec![o]).pretty(),
"[\n {\n \"name\": \"a\\u003db\"\n }\n]"
);
assert_eq!(Json::Array(vec![]).pretty(), "[]");
assert!(parse("{a:1}", true).is_err());
}
}
-10
View File
@@ -1,10 +0,0 @@
//! 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).
pub mod eula;
pub mod java_properties;
pub mod json;
pub mod properties;
pub mod user_lists;
@@ -1,644 +0,0 @@
//! server.properties (DedicatedServerProperties over Settings): every key with
//! vanilla's default, parser and serializer. Reading a value writes its
//! normalized form back, so storing afterwards rewrites the file the way the
//! vanilla server does on start; the legacy keys are dropped.
use super::{
java_properties::{Properties, date_string, now_millis},
json::{self, Json},
};
use horizon_core::random::java_string_hash;
use horizon_protocol::crypto::md5;
/// MinecraftServer.ServerResourcePackInfo.
#[derive(Clone, Debug, PartialEq)]
pub struct ResourcePackInfo {
pub id: u128,
pub url: String,
pub hash: String,
pub required: bool,
/// The prompt component, as JSON, when it parsed.
pub prompt: Option<Json>,
}
/// Every value DedicatedServerProperties reads, in declaration order.
#[derive(Clone, Debug)]
pub struct ServerProperties {
pub online_mode: bool,
pub prevent_proxy_connections: bool,
pub server_ip: String,
pub allow_flight: bool,
pub motd: String,
pub code_of_conduct: bool,
pub bug_report_link: String,
pub force_game_mode: bool,
pub enforce_whitelist: bool,
/// Difficulty id (0 peaceful .. 3 hard).
pub difficulty: i32,
/// GameType id (0 survival .. 3 spectator).
pub game_mode: i32,
pub level_name: String,
pub server_port: i32,
pub management_server_enabled: bool,
pub management_server_host: String,
pub management_server_port: i32,
pub management_server_secret: String,
pub management_server_tls_enabled: bool,
pub management_server_tls_keystore: String,
pub management_server_tls_keystore_password: String,
pub management_server_allowed_origins: String,
pub announce_player_achievements: Option<bool>,
pub enable_query: bool,
pub query_port: i32,
pub enable_rcon: bool,
pub rcon_port: i32,
pub rcon_password: String,
pub hardcore: bool,
pub use_native_transport: bool,
pub spawn_protection: i32,
pub op_permission_level: i32,
pub function_permission_level: i32,
pub max_tick_time: i64,
pub max_chained_neighbor_updates: i32,
pub rate_limit: i32,
pub command_spam_threshold_seconds: i32,
pub chat_spam_threshold_seconds: i32,
pub view_distance: i32,
pub simulation_distance: i32,
pub max_players: i32,
pub network_compression_threshold: i32,
pub broadcast_rcon_to_ops: bool,
pub broadcast_console_to_ops: bool,
pub max_world_size: i32,
pub sync_chunk_writes: bool,
pub region_file_compression: String,
pub enable_jmx_monitoring: bool,
pub enable_status: bool,
pub hide_online_players: bool,
pub entity_broadcast_range_percentage: i32,
pub text_filtering_config: String,
pub text_filtering_version: i32,
pub player_idle_timeout: i32,
pub status_heartbeat_interval: i32,
pub white_list: bool,
pub enforce_secure_profile: bool,
pub log_ips: bool,
pub pause_when_empty_seconds: i32,
pub accepts_transfers: bool,
pub level_seed: String,
pub seed: i64,
/// WorldOptions.randomSeed was used (empty level-seed).
pub random_seed: bool,
pub generate_structures: bool,
pub generator_settings: Json,
pub level_type: String,
pub resource_pack: Option<ResourcePackInfo>,
pub initial_enabled_packs: Vec<String>,
pub initial_disabled_packs: Vec<String>,
/// The properties as they are stored back.
pub raw: Properties,
/// What vanilla logs while reading (resource pack warnings).
pub warnings: Vec<String>,
}
pub const DIFFICULTIES: [&str; 4] = ["peaceful", "easy", "normal", "hard"];
pub const GAME_MODES: [&str; 4] = ["survival", "creative", "adventure", "spectator"];
/// Sources of the values vanilla draws at random.
pub trait Entropy {
/// RandomSource.create().nextLong() (WorldOptions.randomSeed).
fn next_long(&mut self) -> i64;
/// SecureRandom.nextInt(bound).
fn next_int(&mut self, bound: u32) -> u32;
}
/// Entropy from the operating system (/dev/urandom), else the clock.
pub struct SystemEntropy(u64);
impl Default for SystemEntropy {
fn default() -> Self {
let mut seed = [0u8; 8];
let ok = std::fs::File::open("/dev/urandom")
.and_then(|mut f| std::io::Read::read_exact(&mut f, &mut seed))
.is_ok();
let mut s = u64::from_le_bytes(seed);
if !ok || s == 0 {
s = now_millis() as u64 ^ 0x9E37_79B9_7F4A_7C15;
}
Self(s)
}
}
impl SystemEntropy {
fn next(&mut self) -> u64 {
// splitmix64
self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15);
let mut z = self.0;
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
z ^ (z >> 31)
}
}
impl Entropy for SystemEntropy {
fn next_long(&mut self) -> i64 {
self.next() as i64
}
fn next_int(&mut self, bound: u32) -> u32 {
(self.next() % u64::from(bound)) as u32
}
}
/// SecurityConfig.generateSecretKey.
pub fn generate_secret_key(entropy: &mut dyn Entropy) -> String {
const ALPHABET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
(0..40)
.map(|_| char::from(ALPHABET[entropy.next_int(ALPHABET.len() as u32) as usize]))
.collect()
}
/// UUID.nameUUIDFromBytes.
pub fn name_uuid(bytes: &[u8]) -> u128 {
let mut h = md5(bytes);
h[6] = (h[6] & 0x0f) | 0x30;
h[8] = (h[8] & 0x3f) | 0x80;
u128::from_be_bytes(h)
}
/// UUID.fromString (the lenient JDK parser: five dash-separated hex groups).
pub fn parse_uuid(s: &str) -> Option<u128> {
let parts: Vec<&str> = s.split('-').collect();
if parts.len() != 5 || s.len() > 36 {
return None;
}
let mut v = [0u64; 5];
for (i, p) in parts.iter().enumerate() {
if p.is_empty() || p.len() > 16 {
return None;
}
v[i] = u64::from_str_radix(p, 16).ok()?;
}
let msb = (v[0] & 0xffff_ffff) << 32 | (v[1] & 0xffff) << 16 | (v[2] & 0xffff);
let lsb = (v[3] & 0xffff) << 48 | (v[4] & 0xffff_ffff_ffff);
Some(u128::from(msb) << 64 | u128::from(lsb))
}
/// Boolean.valueOf.
fn java_bool(s: &str) -> bool {
s.eq_ignore_ascii_case("true")
}
struct Reader {
p: Properties,
}
impl Reader {
fn raw(&self, key: &str) -> Option<String> {
self.p.get(key).map(str::to_owned)
}
fn get<V>(
&mut self,
key: &str,
de: impl Fn(&str) -> Option<V>,
ser: impl Fn(&V) -> String,
default: V,
) -> V {
let v = self.raw(key).and_then(|s| de(&s)).unwrap_or(default);
self.p.put(key, ser(&v));
v
}
fn string(&mut self, key: &str, default: &str) -> String {
self.get(
key,
|s| Some(s.to_owned()),
String::clone,
default.to_owned(),
)
}
fn int(&mut self, key: &str, default: i32) -> i32 {
self.get(key, |s| s.parse().ok(), i32::to_string, default)
}
fn long(&mut self, key: &str, default: i64) -> i64 {
self.get(key, |s| s.parse().ok(), i64::to_string, default)
}
fn boolean(&mut self, key: &str, default: bool) -> bool {
self.get(key, |s| Some(java_bool(s)), bool::to_string, default)
}
fn legacy(&mut self, key: &str) -> Option<String> {
self.p.remove(key)
}
fn permission(&mut self, key: &str, default: i32) -> i32 {
self.get(
key,
|s| s.parse::<i32>().ok().map(|v| v.clamp(0, 4)),
i32::to_string,
default,
)
}
}
impl ServerProperties {
/// DedicatedServerProperties.fromFile; a file that cannot be read is an
/// empty set (Settings.loadFromFile logs and continues).
pub fn from_file(path: &std::path::Path, entropy: &mut dyn Entropy) -> Result<Self, String> {
let p = match std::fs::read(path) {
Ok(bytes) => Properties::load_file(&bytes).map_err(|e| e.to_string())?,
Err(_) => Properties::default(),
};
Self::new(p, entropy)
}
/// The constructor: field initializers, then the constructor body.
pub fn new(properties: Properties, entropy: &mut dyn Entropy) -> Result<Self, String> {
let mut r = Reader { p: properties };
let mut warnings = Vec::new();
let online_mode = r.boolean("online-mode", true);
let prevent_proxy_connections = r.boolean("prevent-proxy-connections", false);
let server_ip = r.string("server-ip", "");
let allow_flight = r.boolean("allow-flight", false);
let motd = r.string("motd", "A Minecraft Server");
let code_of_conduct = r.boolean("enable-code-of-conduct", false);
let bug_report_link = r.string("bug-report-link", "");
let force_game_mode = r.boolean("force-gamemode", false);
let enforce_whitelist = r.boolean("enforce-whitelist", false);
let difficulty = r.get(
"difficulty",
|s| match s.parse::<i32>() {
Ok(id) => Some(id.rem_euclid(4)),
Err(_) => DIFFICULTIES.iter().position(|n| *n == s).map(|i| i as i32),
},
|d| DIFFICULTIES[*d as usize].to_owned(),
1,
);
let game_mode = r.get(
"gamemode",
|s| match s.parse::<i32>() {
Ok(id) => Some(if (0..4).contains(&id) { id } else { 0 }),
Err(_) => Some(GAME_MODES.iter().position(|n| *n == s).unwrap_or(0) as i32),
},
|g| GAME_MODES[*g as usize].to_owned(),
0,
);
let level_name = r.string("level-name", "world");
let server_port = r.int("server-port", 25565);
let management_server_enabled = r.boolean("management-server-enabled", false);
let management_server_host = r.string("management-server-host", "localhost");
let management_server_port = r.int("management-server-port", 0);
let secret = generate_secret_key(entropy);
let management_server_secret = r.string("management-server-secret", &secret);
let management_server_tls_enabled = r.boolean("management-server-tls-enabled", true);
let management_server_tls_keystore = r.string("management-server-tls-keystore", "");
let management_server_tls_keystore_password =
r.string("management-server-tls-keystore-password", "");
let management_server_allowed_origins = r.string("management-server-allowed-origins", "");
let announce_player_achievements = r
.legacy("announce-player-achievements")
.map(|s| java_bool(&s));
let enable_query = r.boolean("enable-query", false);
let query_port = r.int("query.port", 25565);
let enable_rcon = r.boolean("enable-rcon", false);
let rcon_port = r.int("rcon.port", 25575);
let rcon_password = r.string("rcon.password", "");
let hardcore = r.boolean("hardcore", false);
let use_native_transport = r.boolean("use-native-transport", true);
let spawn_protection = r.int("spawn-protection", 16);
let op_permission_level = r.permission("op-permission-level", 4);
let function_permission_level = r.permission("function-permission-level", 2);
let max_tick_time = r.long("max-tick-time", 60_000);
let max_chained_neighbor_updates = r.int("max-chained-neighbor-updates", 1_000_000);
let rate_limit = r.int("rate-limit", 0);
let command_spam_threshold_seconds = r.int("command-spam-threshold-seconds", 10);
let chat_spam_threshold_seconds = r.int("chat-spam-threshold-seconds", 10);
let view_distance = r.int("view-distance", 10);
let simulation_distance = r.int("simulation-distance", 10);
let max_players = r.int("max-players", 20);
let network_compression_threshold = r.int("network-compression-threshold", 256);
let broadcast_rcon_to_ops = r.boolean("broadcast-rcon-to-ops", true);
let broadcast_console_to_ops = r.boolean("broadcast-console-to-ops", true);
let max_world_size = r.get(
"max-world-size",
|s| s.parse::<i32>().ok().map(|v| v.clamp(1, 29_999_984)),
i32::to_string,
29_999_984,
);
let sync_chunk_writes = r.boolean("sync-chunk-writes", true);
let region_file_compression = r.string("region-file-compression", "deflate");
let enable_jmx_monitoring = r.boolean("enable-jmx-monitoring", false);
let enable_status = r.boolean("enable-status", true);
let hide_online_players = r.boolean("hide-online-players", false);
// Its deserializer is not wrapped: a non-number throws out of the constructor.
let entity_broadcast_range_percentage = match r.raw("entity-broadcast-range-percentage") {
Some(s) => s.parse::<i32>().map(|v| v.clamp(10, 1000)).map_err(|_| {
format!("java.lang.NumberFormatException: For input string: \"{s}\"")
})?,
None => 100,
};
r.p.put(
"entity-broadcast-range-percentage",
entity_broadcast_range_percentage.to_string(),
);
let text_filtering_config = r.string("text-filtering-config", "");
let text_filtering_version = r.int("text-filtering-version", 0);
let player_idle_timeout = r.int("player-idle-timeout", 0);
let status_heartbeat_interval = r.int("status-heartbeat-interval", 0);
let white_list = r.boolean("white-list", true);
let enforce_secure_profile = r.boolean("enforce-secure-profile", true);
let log_ips = r.boolean("log-ips", true);
let pause_when_empty_seconds = r.int("pause-when-empty-seconds", 60);
let accepts_transfers = r.boolean("accepts-transfers", false);
// The constructor body.
let level_seed = r.string("level-seed", "");
let generate_structures = r.boolean("generate-structures", true);
let (seed, random_seed) = match parse_seed(&level_seed) {
Some(s) => (s, false),
None => (entropy.next_long(), true),
};
let generator_settings = match r.raw("generator-settings") {
Some(s) => {
let text = if s.is_empty() { "{}" } else { s.as_str() };
match json::parse(text, false) {
Ok(v @ Json::Object(_)) => v,
Ok(_) => return Err("com.google.gson.JsonSyntaxException: Expected a com.google.gson.JsonObject".into()),
Err(e) => return Err(format!("com.google.gson.JsonParseException: {e}")),
}
}
None => Json::Object(Vec::new()),
};
r.p.put("generator-settings", generator_settings.compact());
let level_type = r.get(
"level-type",
|s| Some(s.to_lowercase()),
String::clone,
"minecraft:normal".to_owned(),
);
let pack_id = r.string("resource-pack-id", "");
let pack_url = r.string("resource-pack", "");
let pack_sha1 = r.string("resource-pack-sha1", "");
let pack_hash = r.legacy("resource-pack-hash");
let pack_required = r.boolean("require-resource-pack", false);
let pack_prompt = r.string("resource-pack-prompt", "");
let resource_pack = server_pack_info(
&pack_id,
&pack_url,
&pack_sha1,
pack_hash.as_deref(),
pack_required,
&pack_prompt,
&mut warnings,
);
let enabled = r.string("initial-enabled-packs", "vanilla");
let disabled = r.string("initial-disabled-packs", "");
let split = |s: &str| {
s.split(',')
.map(|p| p.trim().to_owned())
.collect::<Vec<_>>()
};
Ok(Self {
online_mode,
prevent_proxy_connections,
server_ip,
allow_flight,
motd,
code_of_conduct,
bug_report_link,
force_game_mode,
enforce_whitelist,
difficulty,
game_mode,
level_name,
server_port,
management_server_enabled,
management_server_host,
management_server_port,
management_server_secret,
management_server_tls_enabled,
management_server_tls_keystore,
management_server_tls_keystore_password,
management_server_allowed_origins,
announce_player_achievements,
enable_query,
query_port,
enable_rcon,
rcon_port,
rcon_password,
hardcore,
use_native_transport,
spawn_protection,
op_permission_level,
function_permission_level,
max_tick_time,
max_chained_neighbor_updates,
rate_limit,
command_spam_threshold_seconds,
chat_spam_threshold_seconds,
view_distance,
simulation_distance,
max_players,
network_compression_threshold,
broadcast_rcon_to_ops,
broadcast_console_to_ops,
max_world_size,
sync_chunk_writes,
region_file_compression,
enable_jmx_monitoring,
enable_status,
hide_online_players,
entity_broadcast_range_percentage,
text_filtering_config,
text_filtering_version,
player_idle_timeout,
status_heartbeat_interval,
white_list,
enforce_secure_profile,
log_ips,
pause_when_empty_seconds,
accepts_transfers,
level_seed,
seed,
random_seed,
generate_structures,
generator_settings,
level_type,
resource_pack,
initial_enabled_packs: split(&enabled),
initial_disabled_packs: split(&disabled),
raw: r.p,
warnings,
})
}
/// Settings.store: the file the server writes back.
pub fn stored(&self, millis: i64) -> String {
self.raw.store(
Some("Minecraft server properties"),
&date_string(millis),
false,
)
}
pub fn store(&self, path: &std::path::Path) -> std::io::Result<()> {
std::fs::write(path, self.stored(now_millis()))
}
/// MutableValue.update: change one key and re-read everything (the
/// random defaults are drawn again only for keys still absent, which
/// never happens after the first read).
pub fn update(&self, key: &str, value: String) -> Result<Self, String> {
let mut p = self.raw.clone();
p.put(key, value);
Self::new(p, &mut SystemEntropy::default())
}
}
/// WorldOptions.parseSeed: empty is none, a long is itself, anything else
/// hashes as a Java string.
pub fn parse_seed(s: &str) -> Option<i64> {
let s = s.trim_matches(|c: char| c <= ' ');
if s.is_empty() {
return None;
}
Some(
s.parse::<i64>()
.unwrap_or_else(|_| i64::from(java_string_hash(s.encode_utf16()))),
)
}
fn server_pack_info(
id: &str,
url: &str,
sha1: &str,
legacy_hash: Option<&str>,
required: bool,
prompt: &str,
warnings: &mut Vec<String>,
) -> Option<ResourcePackInfo> {
if url.is_empty() {
return None;
}
let hash = if !sha1.is_empty() {
if legacy_hash.is_some_and(|h| !h.is_empty()) {
warnings.push("resource-pack-hash is deprecated and found along side resource-pack-sha1. resource-pack-hash will be ignored.".into());
}
sha1.to_owned()
} else if let Some(h) = legacy_hash.filter(|h| !h.is_empty()) {
warnings.push(
"resource-pack-hash is deprecated. Please use resource-pack-sha1 instead.".into(),
);
h.to_owned()
} else {
String::new()
};
if hash.is_empty() {
warnings.push("You specified a resource pack without providing a sha1 hash. Pack will be updated on the client only if you change the name of the pack.".into());
} else if !(hash.len() == 40 && hash.chars().all(|c| c.is_ascii_hexdigit())) {
warnings.push("Invalid sha1 for resource-pack-sha1".into());
}
let prompt = parse_prompt(prompt, warnings);
let id = if id.is_empty() {
let uuid = name_uuid(url.as_bytes());
warnings.push(format!(
"resource-pack-id missing, using default of {}",
horizon_protocol::crypto::uuid_string(uuid)
));
uuid
} else {
match parse_uuid(id) {
Some(u) => u,
None => {
warnings.push(format!("Failed to parse '{id}' into UUID"));
return None;
}
}
};
Some(ResourcePackInfo {
id,
url: url.to_owned(),
hash,
required,
prompt,
})
}
/// DedicatedServerProperties.parseResourcePackPrompt: strict JSON decoded as
/// a component (a string, an array of components, or an object with content).
fn parse_prompt(prompt: &str, warnings: &mut Vec<String>) -> Option<Json> {
if prompt.is_empty() {
return None;
}
match json::parse(prompt, true) {
Ok(v) if is_component(&v) => Some(v),
Ok(_) => {
warnings.push(format!("Failed to parse resource pack prompt '{prompt}'"));
None
}
Err(_) => {
warnings.push(format!("Failed to parse resource pack prompt '{prompt}'"));
None
}
}
}
fn is_component(v: &Json) -> bool {
match v {
Json::String(_) | Json::Number(_) | Json::Bool(_) => true,
Json::Array(items) => !items.is_empty() && items.iter().all(is_component),
Json::Object(m) => [
"text",
"translate",
"score",
"selector",
"keybind",
"nbt",
"object",
]
.iter()
.any(|k| m.iter().any(|(n, _)| n == k)),
Json::Null => false,
}
}
#[cfg(test)]
mod tests {
use super::*;
struct Fixed;
impl Entropy for Fixed {
fn next_long(&mut self) -> i64 {
7
}
fn next_int(&mut self, _: u32) -> u32 {
0
}
}
#[test]
fn defaults_match_vanilla_init_settings() {
let p = ServerProperties::new(Properties::default(), &mut Fixed).unwrap();
let stored = p.stored(0);
assert!(stored.starts_with(
"#Minecraft server properties\n#Thu Jan 01 00:00:00 UTC 1970\naccepts-transfers=false\n"
));
assert!(stored.contains("\nlevel-type=minecraft\\:normal\n"));
assert!(
stored
.contains("\nmanagement-server-secret=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n")
);
assert!(stored.ends_with("\nview-distance=10\nwhite-list=true\n"));
assert_eq!(stored.lines().count(), 71);
assert!(p.random_seed);
assert_eq!(p.seed, 7);
}
#[test]
fn parses_like_vanilla() {
let mut raw = Properties::default();
raw.put("difficulty", "-1".into());
raw.put("gamemode", "bogus".into());
raw.put("op-permission-level", "9".into());
raw.put("level-seed", "hello".into());
raw.put("level-type", "FLAT".into());
raw.put("announce-player-achievements", "true".into());
let p = ServerProperties::new(raw, &mut Fixed).unwrap();
assert_eq!(
(p.difficulty, p.game_mode, p.op_permission_level),
(3, 0, 4)
);
assert_eq!(p.seed, 99_162_322);
assert_eq!(p.level_type, "flat");
assert_eq!(p.announce_player_achievements, Some(true));
assert!(p.raw.get("announce-player-achievements").is_none());
assert_eq!(
parse_uuid("1-2-3-4-5"),
Some(0x0000_0001_0002_0003_0004_0000_0000_0005)
);
}
}
@@ -1,448 +0,0 @@
//! ops.json, whitelist.json, banned-players.json and banned-ips.json
//! (StoredUserList and its entries): a Java HashMap keyed by the UUID string
//! or the address, saved as a pretty-printed Gson array in that map's order.
use super::{
java_properties::{civil_from_days, days_from_civil, now_millis},
json::{self, Json},
properties::parse_uuid,
};
use horizon_core::random::java_string_hash;
use horizon_protocol::crypto::uuid_string;
use horizon_world::java_hash_map::{JavaHashMap, JavaKey};
use std::{cmp::Ordering, path::PathBuf};
/// A map key: a Java String.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct JKey(pub String);
impl JavaKey for JKey {
fn java_hash(&self) -> i32 {
java_string_hash(self.0.encode_utf16())
}
fn comparable_compare(&self, other: &Self) -> Option<Ordering> {
Some(self.0.encode_utf16().cmp(other.0.encode_utf16()))
}
fn tie_break(&self, _: &Self) -> Ordering {
Ordering::Less
}
}
/// NameAndId.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct NameAndId {
pub id: u128,
pub name: String,
}
impl NameAndId {
pub fn offline(name: &str) -> Self {
Self {
id: horizon_protocol::crypto::offline_uuid(name),
name: name.to_owned(),
}
}
fn from_json(o: &Json) -> Option<Self> {
let uuid = o.get("uuid")?.as_string()?;
let name = o.get("name")?.as_string()?;
Some(Self {
id: parse_uuid(&uuid)?,
name,
})
}
fn append_to(&self, o: &mut Json) {
o.add("uuid", Json::String(uuid_string(self.id)));
o.add("name", Json::String(self.name.clone()));
}
}
/// BanListEntry.DATE_FORMAT ("yyyy-MM-dd HH:mm:ss Z"), written in UTC.
pub fn format_date(millis: i64) -> String {
let secs = millis.div_euclid(1000);
let (y, m, d) = civil_from_days(secs.div_euclid(86_400));
let rem = secs.rem_euclid(86_400);
format!(
"{y:04}-{m:02}-{d:02} {:02}:{:02}:{:02} +0000",
rem / 3600,
rem / 60 % 60,
rem % 60
)
}
/// The lenient SimpleDateFormat parse of that pattern: fields may overflow
/// into the next (month 13 is January of the next year).
pub fn parse_date(s: &str) -> Option<i64> {
let s = s.trim_start();
let (date, rest) = s.split_once(' ')?;
let (time, zone) = rest.trim_start().split_once(' ')?;
let num = |p: &str| -> Option<i64> {
let p = p.trim();
if p.is_empty()
|| !p
.bytes()
.all(|b| b.is_ascii_digit() || b == b'-' || b == b'+')
{
return None;
}
p.parse().ok()
};
let d: Vec<&str> = date.splitn(3, '-').collect();
let t: Vec<&str> = time.splitn(3, ':').collect();
if d.len() != 3 || t.len() != 3 {
return None;
}
let (y, mo, da) = (num(d[0])?, num(d[1])?, num(d[2])?);
let (h, mi, se) = (num(t[0])?, num(t[1])?, num(t[2])?);
let zone = zone.trim();
let sign = match zone.as_bytes().first()? {
b'+' => 1,
b'-' => -1,
_ => return None,
};
let digits = &zone[1..];
if digits.len() != 4 || !digits.bytes().all(|b| b.is_ascii_digit()) {
return None;
}
let offset =
sign * (digits[..2].parse::<i64>().ok()? * 60 + digits[2..].parse::<i64>().ok()?);
// Lenient month and day arithmetic.
let months = y * 12 + (mo - 1);
let (year, month) = (months.div_euclid(12), months.rem_euclid(12) + 1);
let days = days_from_civil(year, month as u32, 1) + da - 1;
Some(((days * 86_400 + h * 3600 + mi * 60 + se) - offset * 60) * 1000)
}
/// One list entry kind.
pub trait Entry: Clone {
type User: Clone;
fn user(&self) -> &Self::User;
fn key(user: &Self::User) -> String;
fn from_json(o: &Json) -> Option<Self>;
fn serialize(&self, o: &mut Json);
fn expired(&self, _now: i64) -> bool {
false
}
/// `infos.equals(previous)` in StoredUserList.add: only ban entries
/// override equals; the others compare by identity, so a new entry is
/// never equal to the stored one.
fn same(&self, _other: &Self) -> bool {
false
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct OpEntry {
pub user: NameAndId,
pub level: i32,
pub bypasses_player_limit: bool,
}
impl Entry for OpEntry {
type User = NameAndId;
fn user(&self) -> &NameAndId {
&self.user
}
fn key(user: &NameAndId) -> String {
uuid_string(user.id)
}
fn from_json(o: &Json) -> Option<Self> {
let user = NameAndId::from_json(o)?;
let level = o
.get("level")
.and_then(json_int)
.map_or(0, |l| l.clamp(0, 4));
let bypasses_player_limit = o.get("bypassesPlayerLimit").is_some_and(json_bool);
Some(Self {
user,
level,
bypasses_player_limit,
})
}
fn serialize(&self, o: &mut Json) {
self.user.append_to(o);
o.add("level", Json::Number(self.level.to_string()));
o.add(
"bypassesPlayerLimit",
Json::Bool(self.bypasses_player_limit),
);
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct WhiteEntry {
pub user: NameAndId,
}
impl Entry for WhiteEntry {
type User = NameAndId;
fn user(&self) -> &NameAndId {
&self.user
}
fn key(user: &NameAndId) -> String {
uuid_string(user.id)
}
fn from_json(o: &Json) -> Option<Self> {
Some(Self {
user: NameAndId::from_json(o)?,
})
}
fn serialize(&self, o: &mut Json) {
self.user.append_to(o);
}
}
/// BanListEntry for players (NameAndId) or addresses (String).
#[derive(Clone, Debug)]
pub struct BanEntry<T> {
pub user: T,
pub created: i64,
pub source: String,
pub expires: Option<i64>,
pub reason: Option<String>,
}
impl<T: PartialEq> PartialEq for BanEntry<T> {
fn eq(&self, o: &Self) -> bool {
self.source == o.source
&& self.expires == o.expires
&& self.reason == o.reason
&& self.user == o.user
}
}
impl<T> BanEntry<T> {
pub fn new(
user: T,
source: Option<String>,
expires: Option<i64>,
reason: Option<String>,
) -> Self {
Self {
user,
created: now_millis(),
source: source.unwrap_or_else(|| "(Unknown)".into()),
expires,
reason,
}
}
fn fields(user: T, o: &Json) -> Self {
let date = |k: &str| {
o.get(k)
.and_then(Json::as_string)
.and_then(|s| parse_date(&s))
};
Self {
user,
created: date("created").unwrap_or_else(now_millis),
source: o
.get("source")
.and_then(Json::as_string)
.unwrap_or_else(|| "(Unknown)".into()),
expires: date("expires"),
reason: o.get("reason").and_then(Json::as_string),
}
}
fn serialize_ban(&self, o: &mut Json) {
o.add("created", Json::String(format_date(self.created)));
o.add("source", Json::String(self.source.clone()));
o.add(
"expires",
Json::String(self.expires.map_or_else(|| "forever".into(), format_date)),
);
o.add(
"reason",
self.reason.clone().map_or(Json::Null, Json::String),
);
}
}
impl Entry for BanEntry<NameAndId> {
type User = NameAndId;
fn same(&self, other: &Self) -> bool {
self == other
}
fn user(&self) -> &NameAndId {
&self.user
}
fn key(user: &NameAndId) -> String {
uuid_string(user.id)
}
fn from_json(o: &Json) -> Option<Self> {
Some(Self::fields(NameAndId::from_json(o)?, o))
}
fn serialize(&self, o: &mut Json) {
self.user.append_to(o);
self.serialize_ban(o);
}
fn expired(&self, now: i64) -> bool {
self.expires.is_some_and(|e| e < now)
}
}
impl Entry for BanEntry<String> {
type User = String;
fn same(&self, other: &Self) -> bool {
self == other
}
fn user(&self) -> &String {
&self.user
}
fn key(user: &String) -> String {
user.clone()
}
fn from_json(o: &Json) -> Option<Self> {
Some(Self::fields(o.get("ip")?.as_string()?, o))
}
fn serialize(&self, o: &mut Json) {
o.add("ip", Json::String(self.user.clone()));
self.serialize_ban(o);
}
fn expired(&self, now: i64) -> bool {
self.expires.is_some_and(|e| e < now)
}
}
/// JsonElement.getAsInt / getAsBoolean on primitives.
fn json_int(v: &Json) -> Option<i32> {
match v {
Json::Number(n) => n
.parse::<i64>()
.ok()
.map(|v| v as i32)
.or_else(|| n.parse::<f64>().ok().map(|f| f as i32)),
Json::String(s) => s.trim().parse::<i32>().ok(),
_ => None,
}
}
fn json_bool(v: &Json) -> bool {
match v {
Json::Bool(b) => *b,
Json::String(s) => s.eq_ignore_ascii_case("true"),
_ => false,
}
}
/// StoredUserList.
pub struct UserList<E: Entry> {
pub file: PathBuf,
map: JavaHashMap<JKey, E>,
}
impl<E: Entry> UserList<E> {
pub fn new(file: impl Into<PathBuf>) -> Self {
Self {
file: file.into(),
map: JavaHashMap::default(),
}
}
/// The entries in the map's iteration order.
pub fn entries(&self) -> Vec<&E> {
self.map.entries().map(|(_, v)| v).collect()
}
pub fn is_empty(&self) -> bool {
self.map.is_empty()
}
pub fn contains(&self, user: &E::User) -> bool {
self.map.get(&JKey(E::key(user))).is_some()
}
/// StoredUserList.get: expired entries are dropped first.
pub fn get(&mut self, user: &E::User) -> Option<&E> {
let now = now_millis();
let expired: Vec<JKey> = self
.map
.entries()
.filter(|(_, e)| e.expired(now))
.map(|(k, _)| k.clone())
.collect();
for k in expired {
self.map.remove(&k);
}
self.map.get(&JKey(E::key(user)))
}
/// Returns false when an equal entry is already there; saves otherwise.
pub fn add(&mut self, entry: E) -> bool {
let key = JKey(E::key(entry.user()));
if self.map.get(&key).is_some_and(|old| entry.same(old)) {
return false;
}
self.map.put(key, entry);
if let Err(e) = self.save() {
log::warn!("Could not save the list after adding a user. {e}");
}
true
}
pub fn remove(&mut self, user: &E::User) -> bool {
if self.map.remove(&JKey(E::key(user))).is_none() {
return false;
}
if let Err(e) = self.save() {
log::warn!("Could not save the list after removing a user. {e}");
}
true
}
pub fn to_json(&self) -> String {
let items = self
.map
.entries()
.map(|(_, e)| {
let mut o = Json::Object(Vec::new());
e.serialize(&mut o);
o
})
.collect();
Json::Array(items).pretty()
}
pub fn save(&self) -> std::io::Result<()> {
std::fs::write(&self.file, self.to_json())
}
/// StoredUserList.load: a missing file leaves the list as it is.
pub fn load(&mut self) -> Result<(), String> {
let Ok(text) = std::fs::read_to_string(&self.file) else {
return Ok(());
};
self.load_str(&text)
}
pub fn load_str(&mut self, text: &str) -> Result<(), String> {
self.map = JavaHashMap::default();
if text.trim().is_empty() {
return Ok(());
}
let Json::Array(items) = json::parse(text, false)? else {
return Err("Expected a JSON array".into());
};
for item in items {
if !matches!(item, Json::Object(_)) {
return Err("Expected entry to be an object".into());
}
if let Some(e) = E::from_json(&item) {
self.map.put(JKey(E::key(e.user())), e);
}
}
Ok(())
}
}
pub type OpList = UserList<OpEntry>;
pub type WhiteList = UserList<WhiteEntry>;
pub type BanList = UserList<BanEntry<NameAndId>>;
pub type IpBanList = UserList<BanEntry<String>>;
/// IpBanList.getIpFromAddress.
pub fn ip_of(address: &std::net::SocketAddr) -> String {
address.ip().to_string()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn saves_like_gson() {
let mut ops = OpList::new("/nonexistent/ops.json");
ops.load_str(
r#"[{"uuid":"069a79f4-44e9-4726-a5be-fca90e38aaf5","name":"Notch","level":3}]"#,
)
.unwrap();
assert_eq!(
ops.to_json(),
"[\n {\n \"uuid\": \"069a79f4-44e9-4726-a5be-fca90e38aaf5\",\n \"name\": \"Notch\",\n \"level\": 3,\n \"bypassesPlayerLimit\": false\n }\n]"
);
assert_eq!(
parse_date("2026-10-12 10:00:00 +0200"),
parse_date("2026-10-12 08:00:00 +0000")
);
assert_eq!(
format_date(parse_date("2026-10-12 08:00:00 +0000").unwrap()),
"2026-10-12 08:00:00 +0000"
);
assert_eq!(parse_date("forever"), None);
}
}
+36 -10
View File
@@ -125,6 +125,8 @@ pub enum Action {
}
pub struct Title {
pub mode: Mode,
/// Direct Connection's address, synchronized with `options.txt`'s `lastServer`.
pub last_server: String,
pub saves: PathBuf,
pub started: std::time::Instant,
search: String,
@@ -232,6 +234,7 @@ impl Title {
Self {
shown: std::cell::Cell::new((std::mem::discriminant(&mode), now)),
mode,
last_server: String::new(),
saves,
started: now,
search: String::new(),
@@ -397,7 +400,7 @@ impl Title {
scroll.wheel(delta, ROW_HEIGHT / 2.0, top, bottom, content);
self.scroll.set(scroll);
}
fn failed(&mut self, error: impl std::fmt::Display) {
pub fn failed(&mut self, error: impl std::fmt::Display) {
let return_to = Box::new(self.mode.clone());
self.mode = Mode::Error {
message: error.to_string(),
@@ -1162,6 +1165,7 @@ impl Title {
/// The action and whether to play `AbstractWidget.playButtonClickSound`.
/// Navigation buttons can return `Action::None` while still sounding.
pub fn click(&mut self, x: f32, y: f32, size: (f32, f32)) -> (Action, bool) {
self.remember_direct_address();
let (w, h) = (size.0.ceil(), size.1.ceil());
// MenuTabBar: a new tab clears the focus and clicks.
if let Mode::Create { focus, options, .. } = &mut self.mode
@@ -1195,16 +1199,14 @@ impl Title {
self.mode = Mode::Multiplayer(crate::multiplayer::Screen::list(&self.saves));
Action::None
}
(Mode::Multiplayer(screen), hit) => {
match screen.click(hit, x, y, (w, h), &self.saves) {
crate::multiplayer::Outcome::Back => {
self.mode = Mode::Main;
Action::None
}
crate::multiplayer::Outcome::Connect(address) => Action::Connect { address },
crate::multiplayer::Outcome::None => Action::None,
(Mode::Multiplayer(_), hit) => match self.multiplayer_click(hit, x, y, (w, h)) {
crate::multiplayer::Outcome::Back => {
self.mode = Mode::Main;
Action::None
}
}
crate::multiplayer::Outcome::Connect(address) => Action::Connect { address },
crate::multiplayer::Outcome::None => Action::None,
},
(Mode::Main, Some(3)) => Action::Options,
(Mode::Main, Some(7)) => Action::Accessibility,
(Mode::Main, Some(6)) => Action::Language,
@@ -1512,7 +1514,31 @@ impl Title {
_ => None,
}
}
pub(crate) fn remember_direct_address(&mut self) {
if let Mode::Multiplayer(crate::multiplayer::Screen::Direct { address }) = &self.mode {
self.last_server.clone_from(address);
}
}
pub(crate) fn multiplayer_click(
&mut self,
hit: Option<u8>,
x: f32,
y: f32,
size: (f32, f32),
) -> crate::multiplayer::Outcome {
let Mode::Multiplayer(screen) = &mut self.mode else {
return crate::multiplayer::Outcome::None;
};
let outcome = screen.click(hit, x, y, size, &self.saves);
if hit == Some(41)
&& let crate::multiplayer::Screen::Direct { address } = screen
{
address.clone_from(&self.last_server);
}
outcome
}
pub fn escape(&mut self) {
self.remember_direct_address();
if let Mode::Multiplayer(screen) = &mut self.mode
&& !screen.escape(&self.saves)
{
+35
View File
@@ -82,6 +82,41 @@ impl Drop for Fixture {
}
}
#[test]
fn direct_connection_remembers_the_address_on_cancel_escape_and_join() {
let mut f = Fixture::new();
f.title.last_server = "localhost:25566".into();
f.click("Multiplayer");
f.click("Direct Connection");
assert_eq!(f.title.focused_field().unwrap().1, "localhost:25566");
*f.title.focused_field().unwrap().1 = "example.org:25567".into();
f.click("Cancel");
f.click("Direct Connection");
assert_eq!(f.title.focused_field().unwrap().1, "example.org:25567");
*f.title.focused_field().unwrap().1 = "[::1]:25568".into();
f.title.escape();
f.title.escape();
f.click("Multiplayer");
f.click("Direct Connection");
assert_eq!(f.title.focused_field().unwrap().1, "[::1]:25568");
*f.title.focused_field().unwrap().1 = "localhost:25569".into();
assert_eq!(
f.click("Join Server"),
Action::Connect {
address: "localhost:25569".into(),
}
);
assert_eq!(f.title.last_server, "localhost:25569");
f.title.focused_field().unwrap().1.clear();
f.title.escape();
f.click("Direct Connection");
assert!(f.title.focused_field().unwrap().1.is_empty());
}
#[test]
fn empty_singleplayer_opens_creation_and_cancel_returns_to_title() {
let mut f = Fixture::new();