diff --git a/src/server/properties-file.test.ts b/src/server/properties-file.test.ts new file mode 100644 index 0000000..cd9bcce --- /dev/null +++ b/src/server/properties-file.test.ts @@ -0,0 +1,33 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// Copyright (C) 2026 Antônio Miranda + +import { describe, expect, test } from "bun:test"; +import { parsePropertiesText, unescapePropertyValue } from "./properties-file"; + +describe("unescapePropertyValue", () => { + test("undoes unicode, control and literal escapes", () => { + expect(unescapePropertyValue(String.raw`João`)).toBe("João"); + expect(unescapePropertyValue(String.raw`a\tb\nc\\d\:e\=f`)).toBe("a\tb\nc\\d:e=f"); + expect(unescapePropertyValue(String.raw`bad\u00zz`)).toBe("badu00zz"); + }); +}); + +describe("parsePropertiesText", () => { + test("reads =, : and whitespace separators and skips comments", () => { + const values = parsePropertiesText("# c\n! c\na=1\nb : 2\nc 3\n d= spaced\n"); + expect([...values.entries()]).toEqual([ + ["a", "1"], + ["b", "2"], + ["c", "3"], + ["d", "spaced"], + ]); + }); + + test("joins continuation lines and keeps the last value of a repeated key", () => { + const text = ["motd=one\\", " two", "motd=three", "pvp=true", ""].join("\r\n"); + const values = parsePropertiesText(text); + expect(values.get("motd")).toBe("three"); + expect(values.get("pvp")).toBe("true"); + expect(parsePropertiesText("motd=one\\\n two\n").get("motd")).toBe("onetwo"); + }); +}); diff --git a/src/server/properties-file.ts b/src/server/properties-file.ts new file mode 100644 index 0000000..c41a33f --- /dev/null +++ b/src/server/properties-file.ts @@ -0,0 +1,93 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// Copyright (C) 2026 Antônio Miranda + +/** + * Reads `server.properties` text the way the game does (`java.util.Properties`): + * `#`/`!` comments, `=`, `:` or whitespace between key and value, a trailing + * backslash continues the value on the next line, escapes such as `\uXXXX`, and + * when a key repeats the last one wins. + */ + +function isWhitespace(char: string | undefined): boolean { + return char === " " || char === "\t" || char === "\f"; +} + +function stripLeading(line: string): string { + let i = 0; + while (isWhitespace(line[i])) i += 1; + return line.slice(i); +} + +/** A line continues on the next one when it ends with an odd number of backslashes. */ +function continues(line: string): boolean { + let count = 0; + for (let i = line.length - 1; i >= 0 && line[i] === "\\"; i -= 1) count += 1; + return count % 2 === 1; +} + +/** Undoes the escapes of a properties key or value (`\uXXXX`, `\t`, `\n`, `\r`, `\f`, `\\`, `\=`...). */ +export function unescapePropertyValue(text: string): string { + let out = ""; + for (let i = 0; i < text.length; i += 1) { + const char = text[i] ?? ""; + if (char !== "\\") { + out += char; + continue; + } + i += 1; + const next = text[i]; + if (next === undefined) break; + if (next === "t") out += "\t"; + else if (next === "n") out += "\n"; + else if (next === "r") out += "\r"; + else if (next === "f") out += "\f"; + else if (next === "u") { + const hex = text.slice(i + 1, i + 5); + if (/^[0-9a-fA-F]{4}$/.test(hex)) { + out += String.fromCharCode(Number.parseInt(hex, 16)); + i += 4; + } else { + out += "u"; + } + } else out += next; + } + return out; +} + +function splitEntry(logical: string): { key: string; value: string } { + let i = 0; + while (i < logical.length) { + const char = logical[i]; + if (char === "\\") { + i += 2; + continue; + } + if (char === "=" || char === ":" || isWhitespace(char)) break; + i += 1; + } + const rawKey = logical.slice(0, Math.min(i, logical.length)); + while (isWhitespace(logical[i])) i += 1; + if (logical[i] === "=" || logical[i] === ":") { + i += 1; + while (isWhitespace(logical[i])) i += 1; + } + return { key: unescapePropertyValue(rawKey), value: unescapePropertyValue(logical.slice(i)) }; +} + +/** Every key of the text with the value the game reads for it. */ +export function parsePropertiesText(text: string): Map { + const values = new Map(); + const lines = text.split(/\r?\n/); + for (let i = 0; i < lines.length; i += 1) { + let logical = stripLeading(lines[i] ?? ""); + if (logical === "" || logical.startsWith("#") || logical.startsWith("!")) continue; + while (continues(logical) && i + 1 < lines.length) { + i += 1; + logical = logical.slice(0, -1) + stripLeading(lines[i] ?? ""); + } + if (continues(logical)) logical = logical.slice(0, -1); + const { key, value } = splitEntry(logical); + if (key !== "") values.set(key, value); + } + return values; +} diff --git a/src/server/runtime.test.ts b/src/server/runtime.test.ts index 49b7313..852e7b7 100644 --- a/src/server/runtime.test.ts +++ b/src/server/runtime.test.ts @@ -196,10 +196,11 @@ describe("ServerManager lifecycle and command integration", () => { expect((err as ProtocolError).code).toBe("eula_not_accepted"); } - // Even if someone manually enables RCON in server.properties, update_settings forces it back to false + // Even if someone manually enables RCON in server.properties, update_settings forces it + // back to false, while online-mode stays as the owner left it. writeFileSync( join(srvDir, "server.properties"), - "server-port=25565\nenable-rcon=true\nmotd=Hi\n", + "server-port=25565\nenable-rcon=true\nonline-mode=false\nmotd=Hi\n", ); const updated = manager.updateServerSettings({ @@ -215,6 +216,8 @@ describe("ServerManager lifecycle and command integration", () => { expect(updatedProps).toContain("server-port=25570"); expect(updatedProps).toContain("enable-rcon=false"); expect(updatedProps).toContain("motd=Hi"); + expect(updatedProps).toContain("online-mode=false"); + expect(updatedProps).not.toContain("online-mode=true"); const updatedStart = readFileSync(join(srvDir, "start.sh"), "utf8"); expect(updatedStart).toContain("-Xms3072M -Xmx3072M"); @@ -643,6 +646,7 @@ describe("sleep settings", () => { return { manager, + serversDir, sleepDir, async send(type: string, body: unknown): Promise { counter++; @@ -705,6 +709,24 @@ describe("sleep settings", () => { expect(status.whitelist_count).toBeNull(); }); + test("server.status reads the MOTD from server.properties like the game does", async () => { + const f = makeSleepFixture(); + await f.manager.createServer(CREATE); + // Escaped as the launcher and the game write it, and repeated: the last one wins. + writeFileSync( + join(f.serversDir, "sleepy", "server.properties"), + [ + "motd=old", + "motd=Servidor do Jo\\u00e3o\\: \\u00a7aol\\u00e1", + "server-port=25565", + "", + ].join("\n"), + ); + + await f.send("server.status", { server_id: "sleepy" }); + expect(f.eventBody("server.status.result").motd).toBe("Servidor do João: olá"); + }); + test("update_settings stores the sleep settings and status reports them back", async () => { const f = makeSleepFixture(); await f.manager.createServer(CREATE); diff --git a/src/server/runtime.ts b/src/server/runtime.ts index 15e96c5..444b44a 100644 --- a/src/server/runtime.ts +++ b/src/server/runtime.ts @@ -64,6 +64,7 @@ import { secureTree, } from "./permissions"; import { type ListeningPorts, nextFreeServerPort } from "./ports"; +import { parsePropertiesText } from "./properties-file"; import { getEffectiveLaunchTarget, isEulaAccepted, @@ -113,19 +114,12 @@ function readMotdFromProperties(serverDir: string): string | null { } catch { return null; } - for (const line of content.split(/\r?\n/)) { - const trimmed = line.trim(); - if (trimmed.length === 0 || trimmed.startsWith("#") || trimmed.startsWith("!")) { - continue; - } - const match = /^motd\s*[=:]\s*(.*)$/.exec(trimmed); - if (match === null) { - continue; - } - const motd = stripFormatting(match[1] ?? ""); - return motd.length > 0 ? motd : null; + const raw = parsePropertiesText(content).get("motd"); + if (raw === undefined) { + return null; } - return null; + const motd = stripFormatting(raw); + return motd.length > 0 ? motd : null; } export interface ServerManagerOptions { @@ -570,9 +564,11 @@ export function createServerManager(options: ServerManagerOptions = {}): ServerM permissions: permissionContext, }); + // online-mode is the owner's choice once the server exists: a new server starts + // with it on, and saving other settings keeps whatever the owner set. writeServerProperties(serverDir, { port: nextPort, - forceOnlineMode: true, + forceOnlineMode: false, permissions: permissionContext, }); diff --git a/src/sleep/server-files.test.ts b/src/sleep/server-files.test.ts index d9dd717..8264d0e 100644 --- a/src/sleep/server-files.test.ts +++ b/src/sleep/server-files.test.ts @@ -107,6 +107,27 @@ describe("server.properties", () => { expect(readSleepProperties(dir).max_players).toBe(0); }); + test("escapes are undone and a repeated key keeps the last value, like the game", () => { + const dir = makeServerDir(); + writeFileSync( + join(dir, "server.properties"), + [ + "motd=first", + "max-players=5", + "motd=Servidor do Jo\\u00e3o \\", + " na casa", + "max-players=8", + "", + ].join("\n"), + ); + + expect(readSleepProperties(dir)).toEqual({ + server_ip: "", + max_players: 8, + motd: "Servidor do João na casa", + }); + }); + test("a missing file reads as the defaults", () => { expect(readSleepProperties(makeServerDir())).toEqual({ server_ip: "", diff --git a/src/sleep/server-files.ts b/src/sleep/server-files.ts index e9f42bf..426f869 100644 --- a/src/sleep/server-files.ts +++ b/src/sleep/server-files.ts @@ -5,6 +5,7 @@ import { closeSync, constants as fsConstants, fstatSync, readSync } from "node:f import { resolve } from "node:path"; import { z } from "zod"; import { openBeneath } from "../server/open-beneath"; +import { parsePropertiesText } from "../server/properties-file"; export const WHITELIST_FILE = "whitelist.json"; export const SERVER_PROPERTIES_FILE = "server.properties"; @@ -17,8 +18,6 @@ const MAX_MAX_PLAYERS = 100_000; const whitelistEntrySchema = z.object({ name: z.string() }); const whitelistFileSchema = z.array(z.unknown()); -const propertiesLineRegex = /^([a-zA-Z0-9_.-]+)\s*(?:[=:]|\s)\s*(.*)$/; - /** * Reads a file the Minecraft process owns without following a symbolic link and * without reading more than `maxBytes`. Any failure reads as null. @@ -116,29 +115,13 @@ export function readSleepProperties(serverDir: string): SleepProperties { return defaults; } - let serverIp: string | null = null; - let maxPlayers: number | null = null; - let motd: string | null = null; - - for (const rawLine of content.split(/\r?\n/)) { - const trimmed = rawLine.trim(); - if (trimmed.length === 0 || trimmed.startsWith("#") || trimmed.startsWith("!")) { - continue; - } - const match = propertiesLineRegex.exec(trimmed); - if (match === null) { - continue; - } - const key = (match[1] ?? "").toLowerCase(); - const value = (match[2] ?? "").trim(); - if (key === "server-ip" && serverIp === null) { - serverIp = value; - } else if (key === "max-players" && maxPlayers === null) { - maxPlayers = parseMaxPlayers(value); - } else if (key === "motd" && motd === null) { - motd = value; - } - } + // Same reading as the game: escapes undone and, for a repeated key, the last one. + const values = parsePropertiesText(content); + const serverIp = values.get("server-ip")?.trim() ?? null; + const rawMaxPlayers = values.get("max-players"); + const maxPlayers = rawMaxPlayers === undefined ? null : parseMaxPlayers(rawMaxPlayers.trim()); + const rawMotd = values.get("motd"); + const motd = rawMotd === undefined ? null : rawMotd.trim(); return { server_ip: serverIp ?? "",