Port server.properties, eula.txt and the server user lists
DedicatedServerProperties with every key, default, parser and serializer, java.util.Properties load/store, Eula and the four StoredUserList files, checked against the pinned server JAR by test_server_files_parity.py. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,365 @@
|
||||
//! The Rust side of tools/test_server_files_parity.py: reads each case
|
||||
//! directory the way VanillaServerFilesOracle does (server.properties,
|
||||
//! eula.txt, the four user lists and scripted list changes) and prints the
|
||||
//! same report. `server_files_probe CASES OUTPUT`.
|
||||
use horizon_client::server::{
|
||||
eula,
|
||||
java_properties::now_millis,
|
||||
properties::{DIFFICULTIES, GAME_MODES, ServerProperties, SystemEntropy},
|
||||
user_lists::{BanEntry, BanList, IpBanList, NameAndId, OpEntry, OpList, WhiteEntry, WhiteList},
|
||||
};
|
||||
use horizon_protocol::crypto::uuid_string;
|
||||
use std::{fmt::Write as _, path::Path};
|
||||
|
||||
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let mut args = std::env::args().skip(1);
|
||||
let root = std::path::PathBuf::from(args.next().ok_or("CASES OUTPUT")?);
|
||||
let output = args.next().ok_or("OUTPUT")?;
|
||||
let mut cases: Vec<_> = std::fs::read_dir(&root)?
|
||||
.filter_map(|e| e.ok().map(|e| e.path()))
|
||||
.filter(|p| p.is_dir())
|
||||
.collect();
|
||||
cases.sort();
|
||||
let mut out = String::new();
|
||||
for dir in cases {
|
||||
writeln!(out, "== {}", dir.file_name().unwrap().to_string_lossy())?;
|
||||
run_case(&dir, &mut out)?;
|
||||
}
|
||||
std::fs::write(output, out)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Files.readAllLines: split on \n, \r or \r\n.
|
||||
fn lines(text: &str) -> Vec<String> {
|
||||
let mut v: Vec<String> = text
|
||||
.replace("\r\n", "\n")
|
||||
.replace('\r', "\n")
|
||||
.split('\n')
|
||||
.map(str::to_owned)
|
||||
.collect();
|
||||
if v.last().is_some_and(String::is_empty) {
|
||||
v.pop();
|
||||
}
|
||||
v
|
||||
}
|
||||
fn latin1(bytes: &[u8]) -> String {
|
||||
bytes.iter().map(|&b| char::from(b)).collect()
|
||||
}
|
||||
fn has_key(text: &str, key: &str) -> bool {
|
||||
text.split('\n')
|
||||
.any(|l| l.trim_matches(|c: char| c <= ' ').starts_with(key))
|
||||
}
|
||||
|
||||
fn work(dir: &Path) -> std::io::Result<std::path::PathBuf> {
|
||||
let w = std::env::temp_dir().join(format!(
|
||||
"server-files-{}-{}",
|
||||
std::process::id(),
|
||||
dir.file_name().unwrap().to_string_lossy()
|
||||
));
|
||||
let _ = std::fs::remove_dir_all(&w);
|
||||
std::fs::create_dir_all(&w)?;
|
||||
for e in std::fs::read_dir(dir)? {
|
||||
let e = e?;
|
||||
std::fs::copy(e.path(), w.join(e.file_name()))?;
|
||||
}
|
||||
Ok(w)
|
||||
}
|
||||
|
||||
fn run_case(dir: &Path, out: &mut String) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let w = work(dir)?;
|
||||
let props = w.join("server.properties");
|
||||
if dir.join("server.properties").exists() || dir.join("properties.default").exists() {
|
||||
let before = std::fs::read(&props)
|
||||
.map(|b| latin1(&b))
|
||||
.unwrap_or_default();
|
||||
match ServerProperties::from_file(&props, &mut SystemEntropy::default()) {
|
||||
Ok(p) => {
|
||||
print_properties(&p, &before, out)?;
|
||||
p.store(&props)?;
|
||||
writeln!(out, "stored:")?;
|
||||
for (i, line) in lines(&std::fs::read_to_string(&props)?)
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
{
|
||||
let line = if i == 1 && line.starts_with('#') {
|
||||
"#DATE".to_owned()
|
||||
} else if line.starts_with("management-server-secret=")
|
||||
&& !has_key(&before, "management-server-secret")
|
||||
{
|
||||
"management-server-secret=<random>".to_owned()
|
||||
} else {
|
||||
line
|
||||
};
|
||||
writeln!(out, "{line}")?;
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
let class = e.split(':').next().unwrap_or("");
|
||||
writeln!(out, "ERROR {class}")?;
|
||||
}
|
||||
}
|
||||
}
|
||||
if dir.join("eula.txt").exists() || dir.join("eula.missing").exists() {
|
||||
let path = w.join("eula.txt");
|
||||
let agreed = eula::agreed(&path).unwrap_or(false);
|
||||
writeln!(out, "eula agreed={agreed}")?;
|
||||
if let Ok(bytes) = std::fs::read(&path) {
|
||||
for (i, line) in lines(&latin1(&bytes)).into_iter().enumerate() {
|
||||
if i == 1 && line.starts_with('#') {
|
||||
writeln!(out, "#DATE")?;
|
||||
} else {
|
||||
writeln!(out, "{line}")?;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut ops = OpList::new(w.join("ops.json"));
|
||||
let mut white = WhiteList::new(w.join("whitelist.json"));
|
||||
let mut bans = BanList::new(w.join("banned-players.json"));
|
||||
let mut ips = IpBanList::new(w.join("banned-ips.json"));
|
||||
let mut any = false;
|
||||
macro_rules! load {
|
||||
($list:expr, $name:literal) => {
|
||||
if $list.file.exists() {
|
||||
any = true;
|
||||
if let Err(_) = $list.load() {
|
||||
writeln!(
|
||||
out,
|
||||
"{} load ERROR com.google.gson.JsonSyntaxException",
|
||||
$name
|
||||
)?;
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
load!(ops, "ops");
|
||||
load!(white, "whitelist");
|
||||
load!(bans, "banned-players");
|
||||
load!(ips, "banned-ips");
|
||||
if let Ok(actions) = std::fs::read_to_string(dir.join("actions.txt")) {
|
||||
any = true;
|
||||
for line in actions.lines().filter(|l| !l.trim().is_empty()) {
|
||||
let a: Vec<&str> = line.split('\t').collect();
|
||||
let user = |n: &str, u: &str| NameAndId {
|
||||
id: horizon_client::server::properties::parse_uuid(u).unwrap(),
|
||||
name: n.to_owned(),
|
||||
};
|
||||
fn ban<T>(
|
||||
user: T,
|
||||
created: &str,
|
||||
source: &str,
|
||||
expires: &str,
|
||||
reason: &str,
|
||||
) -> BanEntry<T> {
|
||||
let date = |s: &str| (s != "-").then(|| s.parse::<i64>().unwrap());
|
||||
BanEntry {
|
||||
user,
|
||||
created: date(created).unwrap_or_else(now_millis),
|
||||
source: (source != "-")
|
||||
.then(|| source.to_owned())
|
||||
.unwrap_or_else(|| "(Unknown)".into()),
|
||||
expires: date(expires),
|
||||
reason: (reason != "-").then(|| reason.to_owned()),
|
||||
}
|
||||
}
|
||||
let r = match a[0] {
|
||||
"op" => ops.add(OpEntry {
|
||||
user: user(a[1], a[2]),
|
||||
level: a[3].parse::<i32>()?.clamp(0, 4),
|
||||
bypasses_player_limit: a[4].eq_ignore_ascii_case("true"),
|
||||
}),
|
||||
"deop" => ops.remove(&user(a[1], a[2])),
|
||||
"white" => white.add(WhiteEntry {
|
||||
user: user(a[1], a[2]),
|
||||
}),
|
||||
"unwhite" => white.remove(&user(a[1], a[2])),
|
||||
"ban" => bans.add(ban(user(a[1], a[2]), a[3], a[4], a[5], a[6])),
|
||||
"pardon" => bans.remove(&user(a[1], a[2])),
|
||||
"banip" => ips.add(ban(a[1].to_owned(), a[2], a[3], a[4], a[5])),
|
||||
"pardonip" => ips.remove(&a[1].to_owned()),
|
||||
"isbanned" => bans.contains(&user(a[1], a[2])),
|
||||
"isop" => ops.get(&user(a[1], a[2])).is_some(),
|
||||
other => return Err(format!("unknown action {other}").into()),
|
||||
};
|
||||
writeln!(out, "action {} {r}", a[0])?;
|
||||
}
|
||||
}
|
||||
if any {
|
||||
for (name, json) in [
|
||||
("ops", ops.to_json()),
|
||||
("whitelist", white.to_json()),
|
||||
("banned-players", bans.to_json()),
|
||||
("banned-ips", ips.to_json()),
|
||||
] {
|
||||
writeln!(out, "{name}:\n{json}")?;
|
||||
}
|
||||
let mut names: Vec<String> = ops.entries().iter().map(|e| e.user.name.clone()).collect();
|
||||
names.sort_by(|a, b| a.encode_utf16().cmp(b.encode_utf16()));
|
||||
writeln!(out, "op users {}", names.join(","))?;
|
||||
let mut names: Vec<String> = white
|
||||
.entries()
|
||||
.iter()
|
||||
.map(|e| e.user.name.clone())
|
||||
.collect();
|
||||
names.sort_by(|a, b| a.encode_utf16().cmp(b.encode_utf16()));
|
||||
writeln!(out, "white users {}", names.join(","))?;
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&w);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn print_properties(p: &ServerProperties, before: &str, out: &mut String) -> std::fmt::Result {
|
||||
let secret = if has_key(before, "management-server-secret") {
|
||||
p.management_server_secret.clone()
|
||||
} else {
|
||||
"<random>".into()
|
||||
};
|
||||
let pack = p.resource_pack.as_ref().map_or_else(
|
||||
|| "none".to_owned(),
|
||||
|i| {
|
||||
format!(
|
||||
"{} {} {} {} {}",
|
||||
uuid_string(i.id),
|
||||
i.url,
|
||||
i.hash,
|
||||
i.required,
|
||||
i.prompt.is_some()
|
||||
)
|
||||
},
|
||||
);
|
||||
let opt_bool = |b: Option<bool>| b.map_or_else(|| "null".to_owned(), |b| b.to_string());
|
||||
let rows: Vec<(&str, String)> = vec![
|
||||
("online-mode", p.online_mode.to_string()),
|
||||
(
|
||||
"prevent-proxy-connections",
|
||||
p.prevent_proxy_connections.to_string(),
|
||||
),
|
||||
("server-ip", p.server_ip.clone()),
|
||||
("allow-flight", p.allow_flight.to_string()),
|
||||
("motd", p.motd.clone()),
|
||||
("enable-code-of-conduct", p.code_of_conduct.to_string()),
|
||||
("bug-report-link", p.bug_report_link.clone()),
|
||||
("force-gamemode", p.force_game_mode.to_string()),
|
||||
("enforce-whitelist", p.enforce_whitelist.to_string()),
|
||||
("difficulty", DIFFICULTIES[p.difficulty as usize].to_owned()),
|
||||
("gamemode", GAME_MODES[p.game_mode as usize].to_owned()),
|
||||
("level-name", p.level_name.clone()),
|
||||
("server-port", p.server_port.to_string()),
|
||||
(
|
||||
"management-server-enabled",
|
||||
p.management_server_enabled.to_string(),
|
||||
),
|
||||
("management-server-host", p.management_server_host.clone()),
|
||||
(
|
||||
"management-server-port",
|
||||
p.management_server_port.to_string(),
|
||||
),
|
||||
("management-server-secret", secret),
|
||||
(
|
||||
"management-server-tls-enabled",
|
||||
p.management_server_tls_enabled.to_string(),
|
||||
),
|
||||
(
|
||||
"management-server-tls-keystore",
|
||||
p.management_server_tls_keystore.clone(),
|
||||
),
|
||||
(
|
||||
"management-server-tls-keystore-password",
|
||||
p.management_server_tls_keystore_password.clone(),
|
||||
),
|
||||
(
|
||||
"management-server-allowed-origins",
|
||||
p.management_server_allowed_origins.clone(),
|
||||
),
|
||||
(
|
||||
"announce-player-achievements",
|
||||
opt_bool(p.announce_player_achievements),
|
||||
),
|
||||
("enable-query", p.enable_query.to_string()),
|
||||
("query.port", p.query_port.to_string()),
|
||||
("enable-rcon", p.enable_rcon.to_string()),
|
||||
("rcon.port", p.rcon_port.to_string()),
|
||||
("rcon.password", p.rcon_password.clone()),
|
||||
("hardcore", p.hardcore.to_string()),
|
||||
("use-native-transport", p.use_native_transport.to_string()),
|
||||
("spawn-protection", p.spawn_protection.to_string()),
|
||||
("op-permission-level", p.op_permission_level.to_string()),
|
||||
(
|
||||
"function-permission-level",
|
||||
p.function_permission_level.to_string(),
|
||||
),
|
||||
("max-tick-time", p.max_tick_time.to_string()),
|
||||
(
|
||||
"max-chained-neighbor-updates",
|
||||
p.max_chained_neighbor_updates.to_string(),
|
||||
),
|
||||
("rate-limit", p.rate_limit.to_string()),
|
||||
(
|
||||
"command-spam-threshold-seconds",
|
||||
p.command_spam_threshold_seconds.to_string(),
|
||||
),
|
||||
(
|
||||
"chat-spam-threshold-seconds",
|
||||
p.chat_spam_threshold_seconds.to_string(),
|
||||
),
|
||||
("view-distance", p.view_distance.to_string()),
|
||||
("simulation-distance", p.simulation_distance.to_string()),
|
||||
("max-players", p.max_players.to_string()),
|
||||
(
|
||||
"network-compression-threshold",
|
||||
p.network_compression_threshold.to_string(),
|
||||
),
|
||||
("broadcast-rcon-to-ops", p.broadcast_rcon_to_ops.to_string()),
|
||||
(
|
||||
"broadcast-console-to-ops",
|
||||
p.broadcast_console_to_ops.to_string(),
|
||||
),
|
||||
("max-world-size", p.max_world_size.to_string()),
|
||||
("sync-chunk-writes", p.sync_chunk_writes.to_string()),
|
||||
("region-file-compression", p.region_file_compression.clone()),
|
||||
("enable-jmx-monitoring", p.enable_jmx_monitoring.to_string()),
|
||||
("enable-status", p.enable_status.to_string()),
|
||||
("hide-online-players", p.hide_online_players.to_string()),
|
||||
(
|
||||
"entity-broadcast-range-percentage",
|
||||
p.entity_broadcast_range_percentage.to_string(),
|
||||
),
|
||||
("text-filtering-config", p.text_filtering_config.clone()),
|
||||
(
|
||||
"text-filtering-version",
|
||||
p.text_filtering_version.to_string(),
|
||||
),
|
||||
("player-idle-timeout", p.player_idle_timeout.to_string()),
|
||||
(
|
||||
"status-heartbeat-interval",
|
||||
p.status_heartbeat_interval.to_string(),
|
||||
),
|
||||
("white-list", p.white_list.to_string()),
|
||||
(
|
||||
"enforce-secure-profile",
|
||||
p.enforce_secure_profile.to_string(),
|
||||
),
|
||||
("log-ips", p.log_ips.to_string()),
|
||||
(
|
||||
"pause-when-empty-seconds",
|
||||
p.pause_when_empty_seconds.to_string(),
|
||||
),
|
||||
("accepts-transfers", p.accepts_transfers.to_string()),
|
||||
(
|
||||
"seed",
|
||||
if p.random_seed {
|
||||
"<random>".into()
|
||||
} else {
|
||||
p.seed.to_string()
|
||||
},
|
||||
),
|
||||
("generate-structures", p.generate_structures.to_string()),
|
||||
("resource-pack", pack),
|
||||
("initial-enabled-packs", p.initial_enabled_packs.join("|")),
|
||||
("initial-disabled-packs", p.initial_disabled_packs.join("|")),
|
||||
];
|
||||
for (k, v) in rows {
|
||||
writeln!(out, "{k}={v}")?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -88,6 +88,7 @@ pub mod scoreboard;
|
||||
pub mod scoreboard_cmd;
|
||||
pub mod screen_effects;
|
||||
pub mod sculk;
|
||||
pub mod server;
|
||||
pub mod settings;
|
||||
pub mod shadows;
|
||||
pub mod signs;
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
//! 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()))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,447 @@
|
||||
//! `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 Some(&d) = chars.get(self.pos) else {
|
||||
return None;
|
||||
};
|
||||
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));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,385 @@
|
||||
//! 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());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
//! 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;
|
||||
@@ -0,0 +1,644 @@
|
||||
//! 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)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,448 @@
|
||||
//! 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() {
|
||||
eprintln!("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() {
|
||||
eprintln!("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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,248 @@
|
||||
package dev.horizonlab.parity;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.PrintWriter;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Stream;
|
||||
import net.minecraft.SharedConstants;
|
||||
import net.minecraft.server.Bootstrap;
|
||||
import net.minecraft.server.Eula;
|
||||
import net.minecraft.server.dedicated.DedicatedServerProperties;
|
||||
import net.minecraft.server.notifications.NotificationManager;
|
||||
import net.minecraft.server.permissions.LevelBasedPermissionSet;
|
||||
import net.minecraft.server.permissions.PermissionLevel;
|
||||
import net.minecraft.server.players.IpBanList;
|
||||
import net.minecraft.server.players.IpBanListEntry;
|
||||
import net.minecraft.server.players.NameAndId;
|
||||
import net.minecraft.server.players.ServerOpList;
|
||||
import net.minecraft.server.players.ServerOpListEntry;
|
||||
import net.minecraft.server.players.StoredUserList;
|
||||
import net.minecraft.server.players.UserBanList;
|
||||
import net.minecraft.server.players.UserBanListEntry;
|
||||
import net.minecraft.server.players.UserWhiteList;
|
||||
import net.minecraft.server.players.UserWhiteListEntry;
|
||||
|
||||
/**
|
||||
* The dedicated server's files read and written by vanilla's own classes:
|
||||
* server.properties through DedicatedServerProperties (every parsed value
|
||||
* and the file stored back), eula.txt through Eula, and the four user lists
|
||||
* through StoredUserList (load, scripted add/remove, save). Each case is a
|
||||
* directory under args[0]; the output (args[1]) has one "== case" section
|
||||
* per case. The random defaults (management secret, seed) and the stored
|
||||
* timestamp are printed as placeholders. Run with -Duser.timezone=UTC.
|
||||
*/
|
||||
public final class VanillaServerFilesOracle {
|
||||
public static void main(String[] args) throws Exception {
|
||||
SharedConstants.tryDetectVersion();
|
||||
Bootstrap.bootStrap();
|
||||
Path root = Path.of(args[0]);
|
||||
List<Path> cases;
|
||||
try (Stream<Path> s = Files.list(root)) {
|
||||
cases = s.filter(Files::isDirectory).sorted().toList();
|
||||
}
|
||||
try (PrintWriter out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8))) {
|
||||
for (Path dir : cases) {
|
||||
out.println("== " + dir.getFileName());
|
||||
runCase(dir, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static Path work(Path dir) throws Exception {
|
||||
Path work = Files.createTempDirectory("server-files");
|
||||
try (Stream<Path> s = Files.list(dir)) {
|
||||
for (Path f : s.toList()) Files.copy(f, work.resolve(f.getFileName()));
|
||||
}
|
||||
return work;
|
||||
}
|
||||
|
||||
private static void runCase(Path dir, PrintWriter out) throws Exception {
|
||||
Path w = work(dir);
|
||||
Path props = w.resolve("server.properties");
|
||||
if (Files.exists(dir.resolve("server.properties")) || Files.exists(dir.resolve("properties.default"))) {
|
||||
String before = Files.exists(props) ? Files.readString(props, StandardCharsets.ISO_8859_1) : "";
|
||||
try {
|
||||
DedicatedServerProperties p = DedicatedServerProperties.fromFile(props);
|
||||
printProperties(p, before, out);
|
||||
p.store(props);
|
||||
out.println("stored:");
|
||||
List<String> lines = Files.readAllLines(props, StandardCharsets.UTF_8);
|
||||
for (int i = 0; i < lines.size(); i++) {
|
||||
String line = lines.get(i);
|
||||
if (i == 1 && line.startsWith("#")) line = "#DATE";
|
||||
if (line.startsWith("management-server-secret=") && !hasKey(before, "management-server-secret")) {
|
||||
line = "management-server-secret=<random>";
|
||||
}
|
||||
out.println(line);
|
||||
}
|
||||
} catch (Throwable t) {
|
||||
out.println("ERROR " + t.getClass().getName());
|
||||
}
|
||||
}
|
||||
if (Files.exists(dir.resolve("eula.txt")) || Files.exists(dir.resolve("eula.missing"))) {
|
||||
Path eula = w.resolve("eula.txt");
|
||||
boolean agreed = new Eula(eula).hasAgreedToEULA();
|
||||
out.println("eula agreed=" + agreed);
|
||||
if (Files.exists(eula)) {
|
||||
List<String> lines = Files.readAllLines(eula, StandardCharsets.ISO_8859_1);
|
||||
for (int i = 0; i < lines.size(); i++) {
|
||||
out.println(i == 1 && lines.get(i).startsWith("#") ? "#DATE" : lines.get(i));
|
||||
}
|
||||
}
|
||||
}
|
||||
NotificationManager n = new NotificationManager();
|
||||
ServerOpList ops = new ServerOpList(w.resolve("ops.json").toFile(), n);
|
||||
UserWhiteList white = new UserWhiteList(w.resolve("whitelist.json").toFile(), n);
|
||||
UserBanList bans = new UserBanList(w.resolve("banned-players.json").toFile(), n);
|
||||
IpBanList ips = new IpBanList(w.resolve("banned-ips.json").toFile(), n);
|
||||
StoredUserList<?, ?>[] lists = {ops, white, bans, ips};
|
||||
String[] names = {"ops", "whitelist", "banned-players", "banned-ips"};
|
||||
boolean any = false;
|
||||
for (int i = 0; i < lists.length; i++) {
|
||||
if (Files.exists(lists[i].getFile().toPath())) {
|
||||
any = true;
|
||||
try {
|
||||
lists[i].load();
|
||||
} catch (Throwable t) {
|
||||
out.println(names[i] + " load ERROR " + t.getClass().getName());
|
||||
}
|
||||
}
|
||||
}
|
||||
Path actions = dir.resolve("actions.txt");
|
||||
if (Files.exists(actions)) {
|
||||
any = true;
|
||||
for (String line : Files.readAllLines(actions, StandardCharsets.UTF_8)) {
|
||||
if (line.isBlank()) continue;
|
||||
String[] a = line.split("\t", -1);
|
||||
boolean r = switch (a[0]) {
|
||||
case "op" -> ops.add(new ServerOpListEntry(user(a[1], a[2]),
|
||||
LevelBasedPermissionSet.forLevel(PermissionLevel.byId(Integer.parseInt(a[3]))), Boolean.parseBoolean(a[4])));
|
||||
case "deop" -> ops.remove(user(a[1], a[2]));
|
||||
case "white" -> white.add(new UserWhiteListEntry(user(a[1], a[2])));
|
||||
case "unwhite" -> white.remove(user(a[1], a[2]));
|
||||
case "ban" -> bans.add(new UserBanListEntry(user(a[1], a[2]), date(a[3]), opt(a[4]), date(a[5]), opt(a[6])));
|
||||
case "pardon" -> bans.remove(user(a[1], a[2]));
|
||||
case "banip" -> ips.add(new IpBanListEntry(a[1], date(a[2]), opt(a[3]), date(a[4]), opt(a[5])));
|
||||
case "pardonip" -> ips.remove(a[1]);
|
||||
case "isbanned" -> bans.isBanned(user(a[1], a[2]));
|
||||
case "isop" -> ops.get(user(a[1], a[2])) != null;
|
||||
default -> throw new IllegalArgumentException(a[0]);
|
||||
};
|
||||
out.println("action " + a[0] + " " + r);
|
||||
}
|
||||
}
|
||||
if (any) {
|
||||
for (int i = 0; i < lists.length; i++) {
|
||||
lists[i].save();
|
||||
out.println(names[i] + ":");
|
||||
out.println(Files.readString(lists[i].getFile().toPath(), StandardCharsets.UTF_8));
|
||||
}
|
||||
out.println("op users " + String.join(",", sorted(ops.getUserList())));
|
||||
out.println("white users " + String.join(",", sorted(white.getUserList())));
|
||||
}
|
||||
}
|
||||
|
||||
private static List<String> sorted(String[] names) {
|
||||
List<String> l = new ArrayList<>(List.of(names));
|
||||
l.sort(null);
|
||||
return l;
|
||||
}
|
||||
private static NameAndId user(String name, String uuid) {
|
||||
return new NameAndId(UUID.fromString(uuid), name);
|
||||
}
|
||||
private static Date date(String s) {
|
||||
return s.equals("-") ? null : new Date(Long.parseLong(s));
|
||||
}
|
||||
private static String opt(String s) {
|
||||
return s.equals("-") ? null : s;
|
||||
}
|
||||
private static boolean hasKey(String text, String key) {
|
||||
for (String line : text.split("\n")) {
|
||||
if (line.trim().startsWith(key)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static void printProperties(DedicatedServerProperties p, String before, PrintWriter out) {
|
||||
// The fields in declaration order.
|
||||
out.println("online-mode=" + p.onlineMode);
|
||||
out.println("prevent-proxy-connections=" + p.preventProxyConnections);
|
||||
out.println("server-ip=" + p.serverIp);
|
||||
out.println("allow-flight=" + p.allowFlight.get());
|
||||
out.println("motd=" + p.motd.get());
|
||||
out.println("enable-code-of-conduct=" + p.codeOfConduct);
|
||||
out.println("bug-report-link=" + p.bugReportLink);
|
||||
out.println("force-gamemode=" + p.forceGameMode.get());
|
||||
out.println("enforce-whitelist=" + p.enforceWhitelist.get());
|
||||
out.println("difficulty=" + p.difficulty.get().getSerializedName());
|
||||
out.println("gamemode=" + p.gameMode.get().getName());
|
||||
out.println("level-name=" + p.levelName);
|
||||
out.println("server-port=" + p.serverPort);
|
||||
out.println("management-server-enabled=" + p.managementServerEnabled);
|
||||
out.println("management-server-host=" + p.managementServerHost);
|
||||
out.println("management-server-port=" + p.managementServerPort);
|
||||
out.println("management-server-secret=" + (hasKey(before, "management-server-secret") ? p.managementServerSecret : "<random>"));
|
||||
out.println("management-server-tls-enabled=" + p.managementServerTlsEnabled);
|
||||
out.println("management-server-tls-keystore=" + p.managementServerTlsKeystore);
|
||||
out.println("management-server-tls-keystore-password=" + p.managementServerTlsKeystorePassword);
|
||||
out.println("management-server-allowed-origins=" + p.managementServerAllowedOrigins);
|
||||
out.println("announce-player-achievements=" + p.announcePlayerAchievements);
|
||||
out.println("enable-query=" + p.enableQuery);
|
||||
out.println("query.port=" + p.queryPort);
|
||||
out.println("enable-rcon=" + p.enableRcon);
|
||||
out.println("rcon.port=" + p.rconPort);
|
||||
out.println("rcon.password=" + p.rconPassword);
|
||||
out.println("hardcore=" + p.hardcore);
|
||||
out.println("use-native-transport=" + p.useNativeTransport);
|
||||
out.println("spawn-protection=" + p.spawnProtection.get());
|
||||
out.println("op-permission-level=" + p.opPermissions.get().level().id());
|
||||
out.println("function-permission-level=" + p.functionPermissions.level().id());
|
||||
out.println("max-tick-time=" + p.maxTickTime);
|
||||
out.println("max-chained-neighbor-updates=" + p.maxChainedNeighborUpdates);
|
||||
out.println("rate-limit=" + p.rateLimitPacketsPerSecond);
|
||||
out.println("command-spam-threshold-seconds=" + p.commandSpamThresholdSeconds);
|
||||
out.println("chat-spam-threshold-seconds=" + p.chatSpamThresholdSeconds);
|
||||
out.println("view-distance=" + p.viewDistance.get());
|
||||
out.println("simulation-distance=" + p.simulationDistance.get());
|
||||
out.println("max-players=" + p.maxPlayers.get());
|
||||
out.println("network-compression-threshold=" + p.networkCompressionThreshold);
|
||||
out.println("broadcast-rcon-to-ops=" + p.broadcastRconToOps);
|
||||
out.println("broadcast-console-to-ops=" + p.broadcastConsoleToOps);
|
||||
out.println("max-world-size=" + p.maxWorldSize);
|
||||
out.println("sync-chunk-writes=" + p.syncChunkWrites);
|
||||
out.println("region-file-compression=" + p.regionFileComression);
|
||||
out.println("enable-jmx-monitoring=" + p.enableJmxMonitoring);
|
||||
out.println("enable-status=" + p.enableStatus.get());
|
||||
out.println("hide-online-players=" + p.hideOnlinePlayers.get());
|
||||
out.println("entity-broadcast-range-percentage=" + p.entityBroadcastRangePercentage.get());
|
||||
out.println("text-filtering-config=" + p.textFilteringConfig);
|
||||
out.println("text-filtering-version=" + p.textFilteringVersion);
|
||||
out.println("player-idle-timeout=" + p.playerIdleTimeout.get());
|
||||
out.println("status-heartbeat-interval=" + p.statusHeartbeatInterval.get());
|
||||
out.println("white-list=" + p.whiteList.get());
|
||||
out.println("enforce-secure-profile=" + p.enforceSecureProfile);
|
||||
out.println("log-ips=" + p.logIPs);
|
||||
out.println("pause-when-empty-seconds=" + p.pauseWhenEmptySeconds.get());
|
||||
out.println("accepts-transfers=" + p.acceptsTransfers.get());
|
||||
String levelSeed;
|
||||
try {
|
||||
java.lang.reflect.Field f = net.minecraft.server.dedicated.Settings.class.getDeclaredField("properties");
|
||||
f.setAccessible(true);
|
||||
levelSeed = ((java.util.Properties) f.get(p)).getProperty("level-seed", "").trim();
|
||||
} catch (ReflectiveOperationException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
out.println("seed=" + (levelSeed.isEmpty() ? "<random>" : Long.toString(p.worldOptions.seed())));
|
||||
out.println("generate-structures=" + p.worldOptions.generateStructures());
|
||||
out.println("resource-pack=" + p.serverResourcePackInfo.map(i ->
|
||||
i.id() + " " + i.url() + " " + i.hash() + " " + i.isRequired() + " " + (i.prompt() != null)).orElse("none"));
|
||||
out.println("initial-enabled-packs=" + String.join("|", p.initialDataPackConfiguration.getEnabled()));
|
||||
out.println("initial-disabled-packs=" + String.join("|", p.initialDataPackConfiguration.getDisabled()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,224 @@
|
||||
#!/usr/bin/env python3
|
||||
"""The dedicated server's files against vanilla's own classes.
|
||||
|
||||
server.properties is read through DedicatedServerProperties (every key, its
|
||||
default, parser and serializer, the legacy keys, the Java Properties syntax
|
||||
and the UTF-8/ISO-8859-1 fallback) and stored back; eula.txt through Eula;
|
||||
ops.json, whitelist.json, banned-players.json and banned-ips.json through
|
||||
StoredUserList (Gson, Java HashMap order, ban dates, expiry, scripted adds and
|
||||
removals). VanillaServerFilesOracle runs on the pinned server JAR, the
|
||||
`server_files_probe` example on Horizon's port; the outputs must be identical.
|
||||
Random defaults (the management secret, an empty level seed) and the stored
|
||||
timestamps are placeholders on both sides."""
|
||||
import os
|
||||
from pathlib import Path
|
||||
import platform
|
||||
import subprocess
|
||||
|
||||
try:
|
||||
from . import lab, oracle_harness as oh, test_rust_parity as base
|
||||
except ImportError:
|
||||
import lab
|
||||
import oracle_harness as oh
|
||||
import test_rust_parity as base
|
||||
|
||||
NAME = 'server-files-parity'
|
||||
U1 = '069a79f4-44e9-4726-a5be-fca90e38aaf5'
|
||||
U2 = '853c80ef-3c37-49fd-aa49-938b674adae6'
|
||||
U3 = '61699b2e-d327-4a01-9f1e-0ea8c3f06bc6'
|
||||
T0 = 1_760_000_000_000
|
||||
|
||||
|
||||
def properties_cases():
|
||||
yield 'props-missing', None
|
||||
yield 'props-empty', b''
|
||||
yield 'props-vanilla-defaults', (
|
||||
b'#Minecraft server properties\n#Mon Oct 12 15:20:50 GMT 2026\n'
|
||||
b'level-type=minecraft\\:normal\nmotd=A Minecraft Server\nmanagement-server-secret=abc\n')
|
||||
yield 'props-numbers', '\n'.join([
|
||||
'difficulty=3', 'gamemode=1', 'server-port=+25570', 'max-players=-5', 'view-distance= 12',
|
||||
'simulation-distance=99999999999', 'max-tick-time=-1', 'spawn-protection=abc', 'rate-limit=',
|
||||
'max-world-size=0', 'op-permission-level=9', 'function-permission-level=-3',
|
||||
'network-compression-threshold=-1', 'entity-broadcast-range-percentage=5000',
|
||||
'player-idle-timeout=30', 'pause-when-empty-seconds=-1', 'query.port=25599', 'rcon.port=1',
|
||||
'text-filtering-version=2', 'management-server-port=8080']).encode()
|
||||
yield 'props-names', '\n'.join([
|
||||
'difficulty=hard', 'gamemode=spectator', 'online-mode=FALSE', 'white-list=yes',
|
||||
'enforce-whitelist=True', 'hardcore=tRuE', 'allow-flight=1', 'level-type=FLAT',
|
||||
'level-name=My World', 'motd=\\u00a7aHello \\u00e9 World', 'enable-status=false',
|
||||
'hide-online-players=true', 'enforce-secure-profile=false', 'accepts-transfers=true']).encode()
|
||||
yield 'props-bad-enums', b'difficulty=Hard\ngamemode=bogus\nop-permission-level=x\n'
|
||||
yield 'props-wrapping', b'difficulty=-1\ngamemode=7\nop-permission-level=2\n'
|
||||
yield 'props-syntax', (
|
||||
b'# comment\n ! bang comment\n\n key\\ with\\ space = value with space \n'
|
||||
b'a:b\nc d\ne = f\nmulti=one\\\n two\\\r\n three\ncrlf=1\r\ncr=2\rnext=3\n'
|
||||
b'esc=\\t\\n\\r\\f\\x\\\\\ncolon\\:key=v\\=w\nempty\nlast=1\nlast=2\nmotd=dup\nmotd=final\n'
|
||||
b'trailing=back\\')
|
||||
yield 'props-latin1', b'motd=caf\xe9 \xff\nlevel-name=w\xf6rld\n'
|
||||
yield 'props-utf8', 'motd=日本語 ✓ ü\nlevel-name=wörld\nbug-report-link=https://example.com/ü\n'.encode()
|
||||
yield 'props-legacy', b'announce-player-achievements=false\nresource-pack=http://x/p.zip\nresource-pack-hash=0123456789abcdef0123456789abcdef01234567\n'
|
||||
yield 'props-pack', ('resource-pack=https://example.com/pack.zip\nresource-pack-sha1=0123456789ABCDEF0123456789ABCDEF01234567\n'
|
||||
'resource-pack-id=1-2-3-4-5\nrequire-resource-pack=true\n'
|
||||
'resource-pack-prompt={"text":"Please","color":"red"}\nresource-pack-hash=ffff\n').encode()
|
||||
yield 'props-pack-bad', b'resource-pack=https://example.com/a.zip\nresource-pack-id=not-a-uuid\n'
|
||||
yield 'props-pack-noid', b'resource-pack=https://example.com/b.zip\nresource-pack-sha1=bad\nresource-pack-prompt=[1,\n'
|
||||
yield 'props-pack-prompt-string', b'resource-pack=x\nresource-pack-prompt="hi"\n'
|
||||
yield 'props-seeds-number', b'level-seed=-12345\n'
|
||||
yield 'props-seeds-text', b'level-seed= Minecraft \n'
|
||||
yield 'props-seeds-blank', b'level-seed= \n'
|
||||
yield 'props-generator', b'level-type=minecraft:flat\ngenerator-settings= { "layers" : [ {"block":"stone","height":1.50} ], "biome": "minecraft:plains", "s":"a<b\\u00e9" }\n'
|
||||
yield 'props-generator-bad', b'generator-settings={layers}\n'
|
||||
yield 'props-generator-array', b'generator-settings=[]\n'
|
||||
yield 'props-broadcast-bad', b'entity-broadcast-range-percentage=lots\n'
|
||||
yield 'props-packs', b'initial-enabled-packs=vanilla, minecart_improvements ,,\ninitial-disabled-packs= trade_rebalance\n'
|
||||
yield 'props-custom-keys', b'zzz=1\n#c\nAAA=2\n\xc3\xa9=3\n~=4\n'
|
||||
yield 'props-spaces', b'motd= leading\nserver-ip = 127.0.0.1\nrcon.password=p#s!w=d:\n'
|
||||
|
||||
|
||||
def eula_cases():
|
||||
yield 'eula-missing', None
|
||||
yield 'eula-true', b'eula=true\n'
|
||||
yield 'eula-TRUE', b'#comment\neula = TRUE\n'
|
||||
yield 'eula-false', b'eula=false\n'
|
||||
yield 'eula-garbage', b'eula=yes\n'
|
||||
yield 'eula-malformed', b'eula=\\uzzzz\n'
|
||||
|
||||
|
||||
def list_cases():
|
||||
ops = ('[{"uuid":"%s","name":"Notch","level":4,"bypassesPlayerLimit":true},'
|
||||
'{"uuid":"%s","name":"jeb_","level":9},{"uuid":"bad","name":"x"},{"name":"nouuid"},'
|
||||
'{"uuid":"%s","name":"Dinnerbone","level":"2","bypassesPlayerLimit":"true"}]') % (U1, U2, U3)
|
||||
yield 'lists-load', {'ops.json': ops,
|
||||
'whitelist.json': '[{"uuid":"%s","name":"Notch"},{"uuid":"%s","name":"<b>&\'=x"}]' % (U1, U2),
|
||||
'banned-players.json': '[{"uuid":"%s","name":"griefer","created":"2025-01-02 03:04:05 +0100",'
|
||||
'"source":"Server","expires":"forever","reason":"Banned by an operator."},'
|
||||
'{"uuid":"%s","name":"temp","created":"2025-13-40 25:61:61 -0530","expires":"2099-01-01 00:00:00 +0000"}]' % (U2, U3),
|
||||
'banned-ips.json': '[{"ip":"10.0.0.1","created":"2025-06-07 08:09:10 +0000","source":"Console","expires":"forever","reason":"spam"},'
|
||||
'{"ip":"192.168.1.2","created":"2025-06-07 08:09:10 +0000"}]'}
|
||||
yield 'lists-empty-files', {'ops.json': '', 'whitelist.json': '[]', 'banned-players.json': ' \n',
|
||||
'banned-ips.json': '[]'}
|
||||
yield 'lists-bad-json', {'ops.json': '{"not":"an array"}', 'whitelist.json': '[1,2]'}
|
||||
names = ['Alex', 'Steve', 'Notch', 'jeb_', 'Dinnerbone', 'Grumm', 'Ä', 'player_%d']
|
||||
actions = []
|
||||
import uuid as _uuid
|
||||
for i in range(40):
|
||||
name = names[i % len(names)].replace('%d', str(i))
|
||||
u = str(_uuid.UUID(int=(i * 0x9E3779B97F4A7C15 * 0x1F) % (1 << 128), version=4))
|
||||
actions.append('\t'.join(['op', name, u, str(i % 6), 'true' if i % 3 == 0 else 'false']))
|
||||
actions.append('\t'.join(['white', name, u]))
|
||||
actions.append('\t'.join(['ban', name, u, str(T0 + i * 1000), '-' if i % 4 == 0 else 'Server',
|
||||
'-' if i % 2 else str(T0 + 10**12), '-' if i % 5 == 0 else 'reason <%d> & \'x\'' % i]))
|
||||
actions.append('\t'.join(['banip', '10.0.%d.%d' % (i // 7, i), str(T0 + i), 'Console', '-', 'flood']))
|
||||
if i % 7 == 3:
|
||||
actions.append('\t'.join(['deop', name, u]))
|
||||
actions.append('\t'.join(['unwhite', name, u]))
|
||||
actions.append('\t'.join(['pardon', name, u]))
|
||||
actions.append('\t'.join(['pardonip', '10.0.%d.%d' % (i // 7, i)]))
|
||||
if i % 9 == 0:
|
||||
actions.append('\t'.join(['op', name, u, str(i % 6), 'true' if i % 3 == 0 else 'false']))
|
||||
actions.append('\t'.join(['isbanned', name, u]))
|
||||
actions.append('\t'.join(['isop', name, u]))
|
||||
actions.append('\t'.join(['ban', 'expired', U1, str(T0), 'X', str(T0 + 1), '-']))
|
||||
actions.append('\t'.join(['isbanned', 'expired', U1]))
|
||||
actions.append('\t'.join(['op', 'expiredop', U1, '4', 'false']))
|
||||
yield 'lists-actions', {'actions.txt': '\n'.join(actions) + '\n'}
|
||||
|
||||
|
||||
def make_cases(build):
|
||||
root = build / 'cases'
|
||||
if root.exists():
|
||||
import shutil
|
||||
shutil.rmtree(root)
|
||||
root.mkdir(parents=True)
|
||||
count = 0
|
||||
for name, data in properties_cases():
|
||||
d = root / name
|
||||
d.mkdir()
|
||||
if data is None:
|
||||
(d / 'properties.default').write_bytes(b'')
|
||||
else:
|
||||
(d / 'server.properties').write_bytes(data)
|
||||
count += 1
|
||||
for name, data in eula_cases():
|
||||
d = root / name
|
||||
d.mkdir()
|
||||
if data is None:
|
||||
(d / 'eula.missing').write_bytes(b'')
|
||||
else:
|
||||
(d / 'eula.txt').write_bytes(data)
|
||||
count += 1
|
||||
for name, files in list_cases():
|
||||
d = root / name
|
||||
d.mkdir()
|
||||
for f, text in files.items():
|
||||
(d / f).write_text(text, encoding='utf-8')
|
||||
count += 1
|
||||
return root, count
|
||||
|
||||
|
||||
def explain(build):
|
||||
"""The first differing lines of each differing case."""
|
||||
def sections(path):
|
||||
out, name = {}, None
|
||||
for line in path.read_text(encoding='utf-8', errors='replace').splitlines():
|
||||
if line.startswith('== '):
|
||||
name = line[3:]
|
||||
out[name] = []
|
||||
elif name is not None:
|
||||
out[name].append(line)
|
||||
return out
|
||||
left, right = sections(build / 'server.txt'), sections(build / 'rust.txt')
|
||||
text = ''
|
||||
for name in left:
|
||||
a, b = left[name], right.get(name, [])
|
||||
if a != b:
|
||||
diffs = [(x, y) for x, y in zip(a, b) if x != y][:4]
|
||||
if len(a) != len(b):
|
||||
diffs.append((f'<{len(a)} lines>', f'<{len(b)} lines>'))
|
||||
text += f'\n {name}: (vanilla, horizon) {diffs}'
|
||||
return text
|
||||
|
||||
|
||||
def main():
|
||||
lock, jars, libraries = base.verify_artifacts()
|
||||
build = lab.LOCAL / NAME
|
||||
build.mkdir(parents=True, exist_ok=True)
|
||||
report = build / 'report.json'
|
||||
report.unlink(missing_ok=True)
|
||||
oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaServerFilesOracle.java'
|
||||
sources = [Path(__file__).resolve(), oracle, lab.ROOT / 'tools/oracle_harness.py', lab.ROOT / 'tools/lab.py',
|
||||
lab.ROOT / 'tools/test_rust_parity.py', lab.ROOT / 'Cargo.lock',
|
||||
lab.ROOT / 'crates/horizon-client/examples/server_files_probe.rs',
|
||||
*sorted((lab.ROOT / 'crates/horizon-client/src/server').glob('*.rs'))]
|
||||
tested = base.source_hashes(sources)
|
||||
cases, count = make_cases(build)
|
||||
classes = build / 'classes'
|
||||
classes.mkdir(exist_ok=True)
|
||||
dependencies = os.pathsep.join(map(str, [jars['server'], *libraries]))
|
||||
oh.run_logged(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-sourcepath',
|
||||
lab.ROOT / 'mods/horizon/src/test/java', '-cp', dependencies, '-d', classes, oracle],
|
||||
build, 'compile-java')
|
||||
binary = oh.build_probe(build, 'server_files_probe')
|
||||
oh.run_logged([binary, cases, build / 'rust.txt'], build, 'rust')
|
||||
oh.run_logged(['java', '-Xmx1g', '-Duser.timezone=UTC', '-Djava.awt.headless=true', '-cp',
|
||||
str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaServerFilesOracle',
|
||||
cases, build / 'server.txt'], build, 'server')
|
||||
try:
|
||||
matched = base.compare(build / 'server.txt', build / 'rust.txt')
|
||||
except AssertionError as error:
|
||||
raise AssertionError(str(error) + explain(build)) from None
|
||||
base.ensure_sources_unchanged(sources, tested)
|
||||
lab.write_json(report, dict(
|
||||
schema=1, minecraft=lock['minecraft']['version'], manifest_sha1=lock['minecraft']['manifest_sha1'],
|
||||
platform=platform.platform(), rustc=subprocess.check_output(['rustc', '--version'], text=True).strip(),
|
||||
java=subprocess.check_output(['java', '--version'], text=True).splitlines()[0], cases=count,
|
||||
sources_sha256=tested, server_jar_sha256=lab.digest(jars['server'], 'sha256'),
|
||||
matched_output_lines=matched, output_sha256=lab.digest(build / 'rust.txt', 'sha256'),
|
||||
scope='DedicatedServerProperties (all keys, defaults, parsers, serializers, legacy keys, Java Properties '
|
||||
'syntax and encoding fallback, stored file), Eula, and the four StoredUserList files (load, '
|
||||
'add/remove, expiry, save order and Gson output).'))
|
||||
print(f'{count} server file cases match the pinned server ({matched:,} output lines): {report}', flush=True)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Reference in New Issue
Block a user