LAN: offline players get a kept generated name instead of Player (#195)

Every offline Horizon player joined as Player, the LAN host's own offline
profile, so the host refused every guest with "You logged in from another
location". Vanilla's client defaults --username to Player + millis % 1000
and the launcher passes the account's name. Horizon now generates
Player + five digits once and keeps it in horizon-player.txt next to
options.txt (same name, same offline UUID, same inventory on a friend's
world). --name, HORIZON_PLAYER_NAME and a signed-in account still win.

tools/test_lan_lifecycle.py: two default guests join one host together,
keep their names across rejoins, and a guest named Player is refused.

Fixes #195

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-15 00:20:06 +02:00
parent 830e8adbe5
commit dacdf69293
6 changed files with 237 additions and 22 deletions
+21 -7
View File
@@ -208,12 +208,24 @@ struct Options {
offscreen: bool,
/// Multiplayer: `--server HOST[:PORT]` joins at start; `--name` is the offline player name.
server: Option<String>,
player_name: String,
/// `--name`, `HORIZON_PLAYER_NAME` or the signed-in account's name; else
/// [`Options::player_name`] uses the kept offline name.
player_name: Option<String>,
/// `--dedicated`: run as a dedicated server; vanilla's server arguments
/// (`--nogui`, `--port`, `--world`, `--universe`, `--initSettings`) follow.
dedicated: Option<Vec<String>>,
}
impl Options {
/// The name to join servers with: the one given, else the offline name kept
/// next to options.txt (created on first use).
fn player_name(&self) -> String {
self.player_name.clone().unwrap_or_else(|| {
std::env::current_dir().map_or_else(
|_| horizon_client::offline_name::generate(0),
|dir| horizon_client::offline_name::load_or_create(&dir),
)
})
}
fn read() -> Result<Option<Self>> {
let sibling = std::env::current_exe()?
.parent()
@@ -246,7 +258,9 @@ impl Options {
.ok()
.and_then(|v| v.parse().ok()),
server: None,
player_name: std::env::var("HORIZON_PLAYER_NAME").unwrap_or_else(|_| "Player".into()),
player_name: std::env::var("HORIZON_PLAYER_NAME")
.ok()
.filter(|n| !n.is_empty()),
dedicated: None,
};
let mut session_file = std::env::var("HORIZON_SESSION_FILE").ok();
@@ -255,7 +269,7 @@ impl Options {
match arg.as_str() {
"--help" | "-h" => {
println!(
"Horizon — Minecraft Java Edition 26.3 in Rust\n\n --resources PATH Prepared resources (horizon-prepare)\n --render-distance N Chunks, 2..64 (default 12)\n --world NAME World folder under saves/ (default \"New World\")\n --seed N World seed for new worlds (default 0)\n --creative Creative mode (default survival)\n --test-terrain Simple test terrain instead of vanilla generation\n --frames N Exit after N frames (testing)\n --smoke-report PATH Write a JSON report on exit\n --control Accept horizon-ctl commands on a local socket\n --control-socket PATH Control socket path (default $XDG_RUNTIME_DIR/horizon-control.sock)\n --server HOST[:PORT] Join a multiplayer server (offline mode) at start\n --name NAME Player name for multiplayer (default Player)\n --session-file PATH Signed-in account from the launcher (read once, then deleted)\n\nControls: mouse look, WASD move, Space jump, Left Shift sneak, Left Ctrl sprint,\nleft click break, right click place/use, 1-9/scroll hotbar, E inventory,\nQ drop, F3 debug, Esc pause."
"Horizon — Minecraft Java Edition 26.3 in Rust\n\n --resources PATH Prepared resources (horizon-prepare)\n --render-distance N Chunks, 2..64 (default 12)\n --world NAME World folder under saves/ (default \"New World\")\n --seed N World seed for new worlds (default 0)\n --creative Creative mode (default survival)\n --test-terrain Simple test terrain instead of vanilla generation\n --frames N Exit after N frames (testing)\n --smoke-report PATH Write a JSON report on exit\n --control Accept horizon-ctl commands on a local socket\n --control-socket PATH Control socket path (default $XDG_RUNTIME_DIR/horizon-control.sock)\n --server HOST[:PORT] Join a multiplayer server (offline mode) at start\n --name NAME Player name for multiplayer (default: generated once, kept in horizon-player.txt)\n --session-file PATH Signed-in account from the launcher (read once, then deleted)\n\nControls: mouse look, WASD move, Space jump, Left Shift sneak, Left Ctrl sprint,\nleft click break, right click place/use, 1-9/scroll hotbar, E inventory,\nQ drop, F3 debug, Esc pause."
);
return Ok(None);
}
@@ -298,7 +312,7 @@ impl Options {
"--screenshot-after" => o.screenshot_after = Some(value.parse()?),
"--world" => o.world = Some(value),
"--server" => o.server = Some(value),
"--name" => o.player_name = value,
"--name" => o.player_name = Some(value),
"--session-file" => session_file = Some(value),
"--control-socket" => o.control = Some(value.into()),
"--time" => o.time = Some(value.parse()?),
@@ -324,7 +338,7 @@ impl Options {
if let Some(path) = session_file.filter(|p| !p.is_empty()) {
match horizon_client::auth::AuthSession::load(path.as_ref()) {
Ok(session) => {
o.player_name = session.name.clone();
o.player_name = Some(session.name.clone());
horizon_client::auth::set_current(session);
}
Err(e) => eprintln!("Horizon: not signed in: {e}"),
@@ -8444,7 +8458,7 @@ impl ApplicationHandler for Game<'_> {
creative,
} => self.open_world(&folder, Some(&name), seed, creative)?,
Action::Connect { address } => {
self.connect_server(&address, &self.options.player_name.clone())?
self.connect_server(&address, &self.options.player_name())?
}
Action::None => {}
}
@@ -9283,7 +9297,7 @@ pub fn run() -> Result<()> {
_ if game.options.server.is_some() => {
let (address, name) = (
game.options.server.clone().unwrap_or_default(),
game.options.player_name.clone(),
game.options.player_name(),
);
game.connect_server(&address, &name)?;
if let Some(report) = std::env::var_os("HORIZON_NET_REPORT") {
+5
View File
@@ -506,6 +506,11 @@ impl Game<'_> {
Mode::Error { message, .. } => {
json!({ "mode": "world-operation-error", "message": message })
}
Mode::Multiplayer(horizon_client::multiplayer::Screen::Disconnected {
reason, ..
}) => {
json!({ "mode": "multiplayer", "disconnected": reason })
}
Mode::Multiplayer(_) => json!({ "mode": "multiplayer" }),
}
}
+1 -1
View File
@@ -484,7 +484,7 @@ impl Game<'_> {
}
let name = words
.get(2)
.map_or_else(|| self.options.player_name.clone(), |n| (*n).to_owned());
.map_or_else(|| self.options.player_name(), |n| (*n).to_owned());
self.connect_server(arg(1)?, &name)?;
ok()
}
+1
View File
@@ -100,6 +100,7 @@ pub mod music;
pub mod nbt_path;
pub mod net;
pub mod nether_portal;
pub mod offline_name;
pub mod options_file;
pub mod options_fixes;
pub mod options_horizon;
+122
View File
@@ -0,0 +1,122 @@
//! The offline player name, when neither `--name`, `HORIZON_PLAYER_NAME` nor a
//! signed-in account gives one. Vanilla's client defaults `--username` to
//! `"Player" + System.currentTimeMillis() % 1000` (net.minecraft.client.main.Main)
//! and the official launcher always passes the account's name, so two players
//! rarely share one. Horizon used plain `Player` for everyone, which is also
//! the LAN host's own profile: every guest got the host's offline UUID and was
//! refused with "You logged in from another location". The generated name is
//! kept in `horizon-player.txt` next to `options.txt` so the same player gets
//! the same offline UUID (and inventory on a friend's world) every time.
use std::{fs, path::Path};
pub const FILE: &str = "horizon-player.txt";
const KEY: &str = "name:";
/// StringUtil.isValidPlayerName, plus not empty (the login screen sends at least one character).
pub fn is_valid(name: &str) -> bool {
crate::lan::conn::valid_name(name)
}
/// `Player` and five digits (vanilla's default has three: one shared name in a
/// thousand pairs is too many for a game that keeps it).
pub fn generate(seed: u64) -> String {
format!("Player{:05}", seed % 100_000)
}
/// The name kept in `dir`, created on first use. A file that can't be written
/// still yields a name for this run.
pub fn load_or_create(dir: &Path) -> String {
let path = dir.join(FILE);
if let Some(name) = fs::read_to_string(&path).ok().and_then(|text| parse(&text)) {
return name;
}
let name = generate(seed());
if let Err(e) = fs::write(&path, format!("{KEY}{name}\n")) {
log::warn!(
"Horizon: could not keep the player name in {}: {e}",
path.display()
);
}
name
}
fn parse(text: &str) -> Option<String> {
text.lines()
.find_map(|line| line.trim_end_matches('\r').strip_prefix(KEY))
.filter(|name| is_valid(name))
.map(str::to_owned)
}
fn seed() -> u64 {
let nanos = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_nanos() as u64);
// Two players starting the game in the same millisecond still differ.
let mut x = nanos ^ u64::from(std::process::id()).rotate_left(32);
x ^= x >> 33;
x = x.wrapping_mul(0xff51_afd7_ed55_8ccd);
x ^ (x >> 33)
}
#[cfg(test)]
mod tests {
use super::*;
fn dir(name: &str) -> std::path::PathBuf {
let d = std::env::temp_dir().join(format!(
"horizon-offline-name-{name}-{}",
std::process::id()
));
let _ = fs::remove_dir_all(&d);
fs::create_dir_all(&d).unwrap();
d
}
#[test]
fn generated_names_are_valid_and_never_the_hosts_profile() {
for seed in [0, 7, 99_999, 100_000, u64::MAX] {
let name = generate(seed);
assert!(is_valid(&name), "{name}");
// The LAN host's own profile (game/chat.rs PLAYER_NAME).
assert_ne!(name, "Player");
assert_eq!(name.len(), 11);
}
assert_eq!(generate(42), "Player00042");
}
#[test]
fn the_name_is_kept_and_reused() {
let d = dir("kept");
let first = load_or_create(&d);
assert_eq!(
fs::read_to_string(d.join(FILE)).unwrap(),
format!("name:{first}\n")
);
assert_eq!(load_or_create(&d), first);
// An edited name is used as it is.
fs::write(d.join(FILE), "name:Alex_2\r\n").unwrap();
assert_eq!(load_or_create(&d), "Alex_2");
let _ = fs::remove_dir_all(&d);
}
#[test]
fn invalid_names_are_replaced() {
for text in [
"",
"name:",
"name:has space",
"name:ThisNameIsTooLong17",
"name:été",
] {
let d = dir("invalid");
fs::write(d.join(FILE), text).unwrap();
let name = load_or_create(&d);
assert!(
name.starts_with("Player") && is_valid(&name),
"{text:?} -> {name}"
);
assert_eq!(load_or_create(&d), name);
let _ = fs::remove_dir_all(&d);
}
}
}
+87 -14
View File
@@ -1,5 +1,7 @@
#!/usr/bin/env python3
"""Check LAN shutdown when leaving a singleplayer world through the pause menu.
"""Check LAN shutdown when leaving a singleplayer world through the pause menu,
and that offline guests joining with their default names are not refused as the
host's profile (#195: everyone was "Player").
Requires a built horizon-client, prepared resources and a display on Unix:
xvfb-run -a python3 tools/test_lan_lifecycle.py --client target/fast/horizon-client
@@ -101,6 +103,45 @@ def scenario(endpoint, scanner):
command(endpoint, 'quit')
def start_client(client, resources, home, endpoint, log, *extra):
return subprocess.Popen([
str(client), '--resources', str(resources), '--render-distance', '2',
'--test-terrain', '--control-socket', str(endpoint), '--timeout-seconds', '180', *extra,
], cwd=home, env=dict(os.environ, HORIZON_HOME=str(home), HORIZON_NO_AUDIO='1',
HORIZON_MENU_STYLE='classic', HORIZON_PLAYER_NAME=''),
stdout=log, stderr=subprocess.STDOUT)
def guest_names(endpoint, port, guests):
"""Two guests with default names join together; a guest named like the host is refused."""
names = []
for home, guest in guests:
wait_for(guest, 'screen', lambda value: value['screen'] == 'title')
command(guest, f'connect 127.0.0.1:{port}')
wait_for(guest, 'status', lambda value: (value.get('server') or {}).get('joined'))
kept = (home / 'horizon-player.txt').read_text()
assert kept.startswith('name:Player') and kept.strip() != 'name:Player', kept
names.append(kept.strip().removeprefix('name:'))
assert names[0] != names[1], names
status = wait_for(endpoint, 'lan status', lambda value: len(value['guests']) == 2)
assert sorted(g['name'] for g in status['guests']) == sorted(names), status
# The same home keeps its name: leave and join again as the same profile.
home, guest = guests[0]
command(guest, 'disconnect')
wait_for(endpoint, 'lan status', lambda value: len(value['guests']) == 1)
command(guest, f'connect 127.0.0.1:{port}')
wait_for(guest, 'status', lambda value: (value.get('server') or {}).get('joined'))
assert (home / 'horizon-player.txt').read_text().strip() == f'name:{names[0]}'
# A guest that really is the host's offline profile is refused, the others stay.
command(guest, 'disconnect')
command(guest, f'connect 127.0.0.1:{port} Player')
refused = wait_for(guest, 'screen', lambda value: (value.get('menu') or {}).get('disconnected'))
assert 'another location' in refused['menu']['disconnected'], refused
status = command(endpoint, 'lan status')
assert [g['name'] for g in status['guests']] == [names[1]], status
return names
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--client', type=Path, required=True)
@@ -116,12 +157,7 @@ def main():
scanner.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP,
socket.inet_aton(GROUP) + socket.inet_aton('0.0.0.0'))
with (work / 'client.log').open('w+') as log:
process = subprocess.Popen([
str(client), '--resources', str(resources), '--render-distance', '2',
'--test-terrain', '--control-socket', str(endpoint), '--timeout-seconds', '180',
], cwd=work, env=dict(os.environ, HORIZON_HOME=str(work), HORIZON_NO_AUDIO='1',
HORIZON_MENU_STYLE='classic'),
stdout=log, stderr=subprocess.STDOUT)
process = start_client(client, resources, work, endpoint, log)
try:
scenario(endpoint, scanner)
assert process.wait(timeout=20) == 0, 'client exited unsuccessfully'
@@ -130,14 +166,51 @@ def main():
print('\n'.join(log.read().splitlines()[-20:]))
raise
finally:
if process.poll() is None:
process.terminate()
try:
process.wait(timeout=10)
except subprocess.TimeoutExpired:
process.kill()
process.wait(timeout=10)
stop(process)
names = guests_scenario(client, resources, work)
print('LAN lifecycle passed: leaving stops hosting and discovery; reopening stays private')
print(f'LAN guests passed: default names {names[0]} and {names[1]} joined together and kept; '
'"Player" refused as the host\'s profile')
def stop(process):
if process.poll() is None:
process.terminate()
try:
process.wait(timeout=10)
except subprocess.TimeoutExpired:
process.kill()
process.wait(timeout=10)
def guests_scenario(client, resources, work):
host_home = work / 'host'
homes = [work / 'guest-a', work / 'guest-b']
processes, logs = [], []
try:
for home in [host_home, *homes]:
home.mkdir()
log = (home / 'client.log').open('w+')
logs.append(log)
processes.append(start_client(client, resources, home, home / 'control.sock', log))
endpoint = host_home / 'control.sock'
wait_for(endpoint, 'screen', lambda value: value['screen'] == 'title')
command(endpoint, 'open LanGuests 0 creative')
wait_for(endpoint, 'status', lambda value: value['player'] is not None
and value['pending_chunks'] == 0)
port = command(endpoint, 'lan open 0')['port']
return guest_names(endpoint, port, [(home, home / 'control.sock') for home in homes])
except Exception:
for log in logs:
log.seek(0)
print(f'--- {log.name}')
print('\n'.join(log.read().splitlines()[-20:]))
raise
finally:
for process in processes:
stop(process)
for log in logs:
log.close()
if __name__ == '__main__':