Check Horizon player files in vanilla with a bare protocol client

tools/vanilla_login.py joins an offline 26.3 server (login and
configuration phases) so the server loads players/data/<uuid>.dat;
vanilla_world_check.py gains 'login NAME SECONDS' and 'sleep S' steps and
disables the whitelist. With it, vanilla loads a Horizon player with its
position, rotation, inventory, selected slot and abilities, and Horizon
reads the file vanilla writes back.

A new world's first spawn becomes its world spawn (no bogus respawn
point), the player UUID is kept across saves, the selected hotbar slot is
restored, and game_rules.dat only holds rules vanilla knows.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-08 15:49:59 +02:00
parent 5c69e0521a
commit caefa43483
4 changed files with 204 additions and 26 deletions
+1
View File
@@ -2909,6 +2909,7 @@ impl Game<'_> {
let (yaw, pitch) = self.options.look.unwrap_or((level.rotation[0], level.rotation[1]));
self.yaw = yaw;
self.pitch = pitch;
self.selected = level.selected_slot.clamp(0, 8) as usize;
self.streaming = streaming;
self.world = world;
self.inventory = inventory;
+24 -22
View File
@@ -1015,19 +1015,20 @@ impl Level {
// file of a server world, or the legacy Data.Player.
let uuid = uuid_from_tag(data.get("singleplayer_uuid"));
let player_dir = dir.join("players").join("data");
let player = match uuid {
Some(u) => read_dat(&player_dir.join(format!("{}.dat", uuid_text(u)))),
None => fs::read_dir(&player_dir)
.ok()
.and_then(|d| {
d.flatten()
.filter(|e| e.path().extension().is_some_and(|x| x == "dat"))
.max_by_key(|e| e.metadata().and_then(|m| m.modified()).ok())
})
.and_then(|e| read_dat(&e.path())),
}
.or_else(|| data.get("Player").cloned());
level.player_uuid = uuid.or_else(|| uuid_from_tag(player.as_ref().and_then(|p| p.get("UUID"))));
let owner = uuid.and_then(|u| read_dat(&player_dir.join(format!("{}.dat", uuid_text(u)))));
let player = owner
.or_else(|| {
fs::read_dir(&player_dir)
.ok()
.and_then(|d| {
d.flatten()
.filter(|e| e.path().extension().is_some_and(|x| x == "dat"))
.max_by_key(|e| e.metadata().and_then(|m| m.modified()).ok())
})
.and_then(|e| read_dat(&e.path()))
})
.or_else(|| data.get("Player").cloned());
level.player_uuid = uuid_from_tag(player.as_ref().and_then(|p| p.get("UUID"))).or(uuid);
let spawn = level.world_spawn.map(|s| [f64::from(s[0]), f64::from(s[1]), f64::from(s[2])]);
level.spawn = spawn;
if let Some(p) = &player {
@@ -1182,7 +1183,8 @@ impl Level {
}
p
}
pub fn write(&self, dir: &Path) -> Result<()> {
/// Write every file; a world without a player UUID gets a random one.
pub fn write(&mut self, dir: &Path) -> Result<()> {
fs::create_dir_all(dir)?;
let existing = read_dat(&dir.join("level.dat")).and_then(|r| r.get("Data").cloned());
let legacy = existing.as_ref().is_some_and(|d| d.get("Player").is_some() || d.get("WorldGenSettings").is_some());
@@ -1199,11 +1201,12 @@ impl Level {
map.remove(&JavaString::from(key));
}
}
let uuid = self.player_uuid.unwrap_or_else(random_uuid);
let spawn = self.world_spawn.unwrap_or_else(|| {
let s = self.spawn.unwrap_or([0.0, 64.0, 0.0]);
[s[0].floor() as i32, s[1].floor() as i32, s[2].floor() as i32]
});
let uuid = *self.player_uuid.get_or_insert_with(random_uuid);
// A new world's first spawn point is its world spawn.
if self.world_spawn.is_none() {
self.world_spawn = self.spawn.map(|s| [s[0].floor() as i32, s[1].floor() as i32, s[2].floor() as i32]);
}
let spawn = self.world_spawn.unwrap_or([0, 64, 0]);
let mut history: Vec<Tag> = match data.get("version_history") {
Some(Tag::List(l)) => l.clone(),
_ => Vec::new(),
@@ -1325,8 +1328,7 @@ impl Level {
}
write_saved_data(dir, "game_rules", rules)?;
}
let player_level = Self { player_uuid: Some(uuid), ..self.clone() };
write_dat(&dir.join("players").join("data").join(format!("{}.dat", uuid_text(uuid))), player_level.player_tag())?;
write_dat(&dir.join("players").join("data").join(format!("{}.dat", uuid_text(uuid))), self.player_tag())?;
write_dat(&dir.join("level.dat"), Tag::compound([("Data", data)]))?;
Ok(())
}
@@ -1437,7 +1439,7 @@ mod tests {
// Unknown player data survives another save.
let mut extra = back.player_extra.clone().unwrap();
put(&mut extra, "EnderItems", Tag::List(vec![Tag::compound([("Slot", Tag::Byte(0)), ("id", string("minecraft:diamond")), ("count", Tag::Int(2))])]));
let again = Level { player_extra: Some(extra), ..back };
let mut again = Level { player_extra: Some(extra), ..back };
again.write(&dir).unwrap();
let third = Level::read(&dir).unwrap();
assert!(matches!(third.player_extra.as_ref().and_then(|p| p.get("EnderItems")), Some(Tag::List(l)) if l.len() == 1));
+160
View File
@@ -0,0 +1,160 @@
#!/usr/bin/env python3
"""Join an offline-mode vanilla 26.3 server as a bare protocol client, stay
connected for a while (answering keep-alives) and leave.
vanilla_login.py [--host H] [--port P] [--seconds S] NAME
vanilla_login.py --uuid NAME print the offline UUID the server uses
The server loads and saves the player's file (players/data/<uuid>.dat), so
this checks that player data written by Horizon is accepted by vanilla:
its log reports the position it read, and console commands such as
`data get entity NAME` can inspect the loaded player meanwhile.
"""
import argparse
import hashlib
import socket
import struct
import sys
import time
import uuid
import zlib
PROTOCOL = 777 # 26.3
def offline_uuid(name):
digest = bytearray(hashlib.md5(('OfflinePlayer:' + name).encode()).digest())
digest[6] = (digest[6] & 0x0F) | 0x30
digest[8] = (digest[8] & 0x3F) | 0x80
return uuid.UUID(bytes=bytes(digest))
def varint(v):
out = b''
v &= 0xFFFFFFFF
while True:
b = v & 0x7F
v >>= 7
out += bytes([b | (0x80 if v else 0)])
if not v:
return out
def string(s):
data = s.encode()
return varint(len(data)) + data
class Connection:
def __init__(self, host, port):
self.sock = socket.create_connection((host, port), timeout=30)
self.threshold = -1
self.buffer = b''
def read_exact(self, n):
while len(self.buffer) < n:
chunk = self.sock.recv(65536)
if not chunk:
raise EOFError('server closed the connection')
self.buffer += chunk
out, self.buffer = self.buffer[:n], self.buffer[n:]
return out
def read_varint(self):
value = shift = 0
while True:
b = self.read_exact(1)[0]
value |= (b & 0x7F) << shift
shift += 7
if not b & 0x80:
return value
def send(self, packet_id, payload=b''):
body = varint(packet_id) + payload
if self.threshold >= 0:
if len(body) >= self.threshold:
body = varint(len(body)) + zlib.compress(body)
else:
body = varint(0) + body
self.sock.sendall(varint(len(body)) + body)
def receive(self):
length = self.read_varint()
body = self.read_exact(length)
if self.threshold >= 0:
pos, size = parse_varint(body, 0)
body = zlib.decompress(body[pos:]) if size else body[pos:]
pos, packet_id = parse_varint(body, 0)
return packet_id, body[pos:]
def parse_varint(data, pos):
value = shift = 0
while True:
b = data[pos]
pos += 1
value |= (b & 0x7F) << shift
shift += 7
if not b & 0x80:
return pos, value
def join(host, port, name, seconds):
c = Connection(host, port)
c.send(0, varint(PROTOCOL) + string(host) + struct.pack('>H', port) + varint(2))
c.send(0, string(name) + offline_uuid(name).bytes)
# Login: compression, then login finished.
while True:
pid, data = c.receive()
if pid == 3:
c.threshold = parse_varint(data, 0)[1]
elif pid == 2:
break
elif pid == 0:
raise RuntimeError(f'login refused: {data!r}')
c.send(3) # login acknowledged -> configuration
while True:
pid, data = c.receive()
if pid == 15: # select known packs: claim none, receive full registries
c.send(7, varint(0))
elif pid == 4: # keep alive
c.send(4, data)
elif pid == 5: # ping
c.send(5, data)
elif pid == 3: # finish configuration
c.send(3)
break
elif pid == 2:
raise RuntimeError(f'disconnected during configuration: {data!r}')
deadline = time.time() + seconds
c.sock.settimeout(1.0)
while time.time() < deadline:
try:
c.receive()
except socket.timeout:
continue
except EOFError:
break # the server stopped
# Play packets are not decoded: the server's first keep-alive comes
# after 15 seconds and it waits 15 more for the answer, so a session
# under 30 seconds needs none.
c.sock.close()
def main():
p = argparse.ArgumentParser()
p.add_argument('name')
p.add_argument('--host', default='127.0.0.1')
p.add_argument('--port', type=int, default=25565)
p.add_argument('--seconds', type=float, default=5, help='at most 25')
p.add_argument('--uuid', action='store_true')
args = p.parse_args()
if args.uuid:
print(offline_uuid(args.name))
return 0
join(args.host, args.port, args.name, args.seconds)
return 0
if __name__ == '__main__':
sys.exit(main())
+19 -4
View File
@@ -1,6 +1,8 @@
#!/usr/bin/env python3
"""Run the vanilla 26.3 dedicated server headless on a world folder, optionally
send console commands (`sleep SECONDS` pauses between them), then stop it cleanly and report problems from its log.
send console commands (`sleep SECONDS` pauses between them; `login NAME
SECONDS` joins with tools/vanilla_login.py in the background), then stop it
cleanly and report problems from its log.
vanilla_world_check.py --jar server.jar --dir RUN_DIR [--world NAME]
[--seed N] [--port P] [--command CMD ...]
@@ -21,10 +23,10 @@ import threading
import time
SUSPICIOUS = re.compile(
r'(ERROR|Exception|Couldn\'t load|Failed to|Skipping|Invalid|Unknown|corrupt|'
r'(ERROR|login failed|Exception|Couldn\'t load|Failed to|Skipping|Invalid|Unknown|corrupt|'
r'Recreating|upgrad|DataFix|out of bounds|missing|Mismatch)', re.IGNORECASE)
# Benign lines the server prints on every start.
BENIGN = re.compile(r'(OFFLINE/INSECURE|online-mode|authenticate usernames|hackers|'
BENIGN = re.compile(r'(Unpacking |OFFLINE/INSECURE|online-mode|authenticate usernames|hackers|'
r'Failed to load properties|Failed to load eula)')
@@ -47,7 +49,7 @@ def main():
'level-name': args.world, 'spawn-protection': '0', 'view-distance': '4',
'simulation-distance': '4', 'sync-chunk-writes': 'true', 'enable-query': 'false',
'enable-rcon': 'false', 'management-server-enabled': 'false',
'pause-when-empty-seconds': '-1',
'pause-when-empty-seconds': '-1', 'white-list': 'false', 'enforce-whitelist': 'false',
}
with open(os.path.join(args.dir, 'server.properties'), 'w') as f:
f.writelines(f'{k}={v}\n' for k, v in props.items())
@@ -74,6 +76,19 @@ def main():
if command.startswith('sleep '):
time.sleep(float(command.split()[1]))
continue
if command.startswith('login '):
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import vanilla_login
_, name, seconds = command.split()
def run(name=name, seconds=float(seconds)):
try:
vanilla_login.join('127.0.0.1', int(args.port), name, seconds)
except Exception as e: # reported in the log check below
lines.append(f'login failed: {e}')
threading.Thread(target=run, daemon=True).start()
continue
proc.stdin.write(command + '\n')
proc.stdin.flush()
time.sleep(0.5)