From 015e9bb2c86c0e449c3bdf57dace626652e9e6c3 Mon Sep 17 00:00:00 2001 From: Overlord Date: Tue, 29 Sep 2026 16:51:13 +0200 Subject: [PATCH] Improve/add initial project structure for ZomboidForge with build system, runtime, and patching logic. Added version support for building images. --- .dockerignore | 2 + .gitignore | 1 + Dockerfile | 52 +++- README.md | 48 +++- agent/build.gradle.kts | 20 ++ .../zomboidforge/agent/ForgeAgent.java | 24 ++ api/build.gradle.kts | 5 + .../zomboidforge/api/ZomboidForge.java | 13 + .../main/kotlin/ProjectZomboidExtension.kt | 7 + .../zomboidforge.java-conventions.gradle.kts | 7 + ci/release.sh | 139 ++++++++++ ci/steam-buildid.sh | 71 ++++++ compat/b42/patches/build.gradle.kts | 10 + .../compat/b42/patches/B42PatchSet.java | 21 ++ ...dev.overlord.zomboidforge.patcher.PatchSet | 1 + compat/b42/runtime/build.gradle.kts | 12 + .../zomboidforge/compat/b42/package-info.java | 5 + compose.yaml | 30 ++- core/build.gradle.kts | 9 + .../zomboidforge/core/package-info.java | 5 + docker/entrypoint.sh | 237 ++++++++++++++++-- docker/install-server.sh | 51 +++- gradle.properties | 5 + gradle/libs.versions.toml | 17 +- patcher/build.gradle.kts | 55 ++++ .../zomboidforge/patcher/ClassPatch.java | 22 ++ .../zomboidforge/patcher/GameVersion.java | 72 ++++++ .../patcher/GameVersionReader.java | 94 +++++++ .../patcher/HierarchyClassWriter.java | 75 ++++++ .../zomboidforge/patcher/JarPatcher.java | 194 ++++++++++++++ .../zomboidforge/patcher/PatchSet.java | 15 ++ settings.gradle.kts | 7 +- 32 files changed, 1268 insertions(+), 58 deletions(-) create mode 100644 agent/build.gradle.kts create mode 100644 agent/src/main/java/dev/overlord/zomboidforge/agent/ForgeAgent.java create mode 100644 api/build.gradle.kts create mode 100644 api/src/main/java/dev/overlord/zomboidforge/api/ZomboidForge.java create mode 100755 ci/release.sh create mode 100755 ci/steam-buildid.sh create mode 100644 compat/b42/patches/build.gradle.kts create mode 100644 compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/patches/B42PatchSet.java create mode 100644 compat/b42/patches/src/main/resources/META-INF/services/dev.overlord.zomboidforge.patcher.PatchSet create mode 100644 compat/b42/runtime/build.gradle.kts create mode 100644 compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/package-info.java create mode 100644 core/build.gradle.kts create mode 100644 core/src/main/java/dev/overlord/zomboidforge/core/package-info.java create mode 100644 patcher/build.gradle.kts create mode 100644 patcher/src/main/java/dev/overlord/zomboidforge/patcher/ClassPatch.java create mode 100644 patcher/src/main/java/dev/overlord/zomboidforge/patcher/GameVersion.java create mode 100644 patcher/src/main/java/dev/overlord/zomboidforge/patcher/GameVersionReader.java create mode 100644 patcher/src/main/java/dev/overlord/zomboidforge/patcher/HierarchyClassWriter.java create mode 100644 patcher/src/main/java/dev/overlord/zomboidforge/patcher/JarPatcher.java create mode 100644 patcher/src/main/java/dev/overlord/zomboidforge/patcher/PatchSet.java diff --git a/.dockerignore b/.dockerignore index 584b141..f2f986b 100644 --- a/.dockerignore +++ b/.dockerignore @@ -5,6 +5,8 @@ !settings.gradle.kts !build-logic/ !api/ +!core/ +!compat/ !agent/ !patcher/ !docker/ diff --git a/.gitignore b/.gitignore index 15fc579..4a58c5c 100644 --- a/.gitignore +++ b/.gitignore @@ -2,6 +2,7 @@ !README.md lib .*/ +!.gitea/ build/ out/ diff --git a/Dockerfile b/Dockerfile index 35a8352..0c3467e 100644 --- a/Dockerfile +++ b/Dockerfile @@ -4,9 +4,22 @@ # contains no game files. # # podman build --platform linux/amd64 -t zomboidforge . -# podman build --build-arg PZ_BRANCH=unstable ... # non-public Steam branch +# podman build --build-arg PZ_BRANCH=42.19 --build-arg PZ_VERSION=42.19 ... +# +# Build arguments: +# PZ_BRANCH Steam branch of app 380870: public, unstable, or a version branch (42.19, ...) +# PZ_VERSION Expected Project Zomboid version; the build fails when the downloaded +# server reports another one. Default: pz.version in gradle.properties +# STEAMCLIENT bundled (default) or steamcmd: replace the server's steamclient.so +# files with steamcmd's newer copies +# FORGE_VERSION Image label only; set by ci/release.sh +# STEAM_BUILDID Image label only; set by ci/release.sh ARG PZ_BRANCH=public +ARG PZ_VERSION="" +ARG STEAMCLIENT=bundled +ARG FORGE_VERSION="" +ARG STEAM_BUILDID="" # --- Stage 1: vanilla dedicated server ----------------------------------------- FROM docker.io/steamcmd/steamcmd:debian-13 AS server @@ -16,8 +29,9 @@ FROM docker.io/steamcmd/steamcmd:debian-13 AS server RUN steamcmd +quit ARG PZ_BRANCH +ARG STEAMCLIENT COPY docker/install-server.sh /usr/local/bin/install-server -RUN install-server /server "${PZ_BRANCH}" +RUN install-server /server "${PZ_BRANCH}" "${STEAMCLIENT}" # --- Stage 2: ZomboidForge build and server jar patching ----------------------- FROM docker.io/library/eclipse-temurin:25-jdk AS build @@ -30,19 +44,28 @@ RUN ./gradlew --no-daemon --version COPY build-logic build-logic COPY api api +COPY core core +COPY compat compat COPY agent agent COPY patcher patcher COPY --from=server /server/java/projectzomboid.jar /pz/projectzomboid.jar -RUN ./gradlew --no-daemon -Ppz.jar=/pz/projectzomboid.jar build :patcher:patchServerJar + +# An empty PZ_VERSION keeps pz.version from gradle.properties. +ARG PZ_VERSION +RUN ./gradlew --no-daemon \ + -Ppz.jar=/pz/projectzomboid.jar \ + ${PZ_VERSION:+-Ppz.version=${PZ_VERSION}} \ + build :patcher:patchServerJar # --- Stage 3: runtime ------------------------------------------------------------ FROM docker.io/library/debian:trixie-slim -# ca-certificates: required by steamclient.so to connect to Steam. Unpinned so -# the image picks up the current Debian CA bundle. +# ca-certificates: required by steamclient.so to connect to Steam. +# sqlite3: the entrypoint checks the admin account in the server database. +# Unpinned so the image picks up current Debian security updates. # hadolint ignore=DL3008 RUN apt-get update \ - && apt-get install --yes --no-install-recommends ca-certificates \ + && apt-get install --yes --no-install-recommends ca-certificates sqlite3 \ && rm --recursive --force /var/lib/apt/lists/* RUN useradd --create-home --uid 1000 pz \ @@ -54,6 +77,23 @@ COPY --from=build /src/patcher/build/server/projectzomboid.jar /opt/pz/java/proj COPY --from=build /src/agent/build/libs/zomboidforge-agent-*.jar /opt/pz/zomboidforge-agent.jar COPY docker/entrypoint.sh /usr/local/bin/entrypoint +# Steam downloads Workshop items into /steamapps/workshop. /opt/pz is +# owned by root, so steamapps points into the data volume, which also keeps the +# downloads across container recreation. +RUN ln --symbolic /data/steamapps /opt/pz/steamapps + +ARG PZ_BRANCH +ARG PZ_VERSION +ARG FORGE_VERSION +ARG STEAM_BUILDID + +LABEL org.opencontainers.image.title="ZomboidForge" \ + org.opencontainers.image.description="Project Zomboid dedicated server with Java mod support." \ + org.opencontainers.image.version="${FORGE_VERSION}" \ + dev.overlord.zomboidforge.pz-version="${PZ_VERSION}" \ + dev.overlord.zomboidforge.steam-branch="${PZ_BRANCH}" \ + dev.overlord.zomboidforge.steam-buildid="${STEAM_BUILDID}" + USER 1000:1000 VOLUME /data # 16261/udp game, 16262/udp direct connect, 27015/tcp RCON diff --git a/README.md b/README.md index 36ddf5b..4312723 100644 --- a/README.md +++ b/README.md @@ -7,30 +7,65 @@ first‑class support for custom Java mods and drop‑in server builds. The container image downloads the vanilla dedicated server (Steam app 380870) with an anonymous steamcmd login while it builds, and patches it. No game files are part of this -repository. +repository. The build fails when the downloaded server is not the Project Zomboid +version in `gradle.properties` (`pz.version`). ```sh podman build --platform linux/amd64 -t zomboidforge . # or: docker build ... ``` +| Build argument | Default | | +|---|---|---| +| `PZ_BRANCH` | `public` | Steam branch: `public`, `unstable`, or a version branch such as `42.19` | +| `PZ_VERSION` | `pz.version` | Expected Project Zomboid version | +| `STEAMCLIENT` | `bundled` | `steamcmd` replaces the server's `steamclient.so` files with steamcmd's newer copies (workaround for failing Workshop downloads) | + +Published images are tagged `-pz-build` (immutable), +`-pz`, and `latest`. + ## Running ```sh podman run -d --name zomboidforge \ -e ADMIN_PASSWORD=... -e RCON_PASSWORD=... \ - -p 16261:16261/udp -p 16262:16262/udp -p 27015:27015/tcp \ + -p 16261:16261/udp -p 16262:16262/udp -p 127.0.0.1:27015:27015/tcp \ -v zomboid-data:/data zomboidforge ``` +Unset variables keep the value in the server `.ini` (or the game default). + | Variable | Default | | |---|---|---| | `SERVER_NAME` | `zomboidforge` | Server config name (`/data/Server/.ini`) | -| `ADMIN_PASSWORD` | | Required on the first start, when the admin account is created | -| `RCON_PASSWORD` | | Written into the server ini on every start; RCON is disabled without it | +| `SERVER_PASSWORD` | | Password clients need to join (`.ini` `Password`) | +| `PUBLIC` | | `true`/`false`: listed in the in-game server browser | +| `PUBLIC_NAME` | | Name in the server browser | +| `PORT` | `16261` | Game port (`-port`) | +| `UDP_PORT` | `16262` | Direct connection port (`-udpport`) | +| `ADMIN_USERNAME` | `admin` | First start only | +| `ADMIN_PASSWORD` | | Required on the first start, ignored afterwards | +| `SERVER_PRESET` | | Sandbox preset for a new server: `Apocalypse`, `Extinction`, `Outbreak`, `Rising`, `SixMonthsLater` | +| `MODS` | | Mod IDs, Build 42 format: `\ModA;\ModB` | +| `WORKSHOP_ITEMS` | | Workshop item IDs: `123;456` | +| `RCON_PASSWORD` | | Written into the `.ini` on every start; RCON is disabled without it | +| `JVM_MIN_HEAP` | | `-Xms` | | `JVM_MAX_HEAP` | `8g` | `-Xmx` | | `STEAM` | `1` | `0` runs the server without Steam | +| `SOFT_RESET` | | `true` starts once in soft reset mode (`-Dsoftreset`); unset it afterwards | -For local testing there is `compose.yaml` (`podman compose up --build`, passwords from `.env`). +Notes: + +- **Ports:** host and container ports must be the same. The server announces its own + port, so `-p 17000:16261/udp` is unreachable; set `PORT=17000` and publish + `17000:17000/udp` instead. +- **Data:** `/data` holds the server config, saves, database, logs, and downloaded Workshop + items (`/data/steamapps`). The server runs as UID 1000. A bind-mounted host directory + must be writable by UID 1000 (`chown 1000:1000 `); with rootless Podman, use + `--userns=keep-id:uid=1000,gid=1000` to map it to your own user. +- **Stopping:** `SIGTERM` triggers the game's own save-and-quit. Allow enough time for large + worlds (`podman stop -t 120`, `stop_grace_period` in compose). + +For local testing there is `compose.yaml` (`podman compose up --build`, settings from `.env`). ## Development @@ -41,3 +76,6 @@ server jar, `lib/server/java/projectzomboid.jar` by default (override with `-Ppz ./gradlew build # compile + tests ./gradlew :patcher:patchServerJar # -> patcher/build/server/projectzomboid.jar ``` + +Game-specific code lives in `compat/b/`; `api` and `core` are version-independent. +`pz.version` in `gradle.properties` selects the targeted version. diff --git a/agent/build.gradle.kts b/agent/build.gradle.kts new file mode 100644 index 0000000..4965e66 --- /dev/null +++ b/agent/build.gradle.kts @@ -0,0 +1,20 @@ +// Java agent for runtime work (mod loading, live patches). Build-time patches are in :patcher. + +plugins { + id("zomboidforge.java-conventions") +} + +dependencies { + implementation(project(":api")) + implementation(project(":core")) + implementation(project(projectZomboid.compatProject("runtime"))) + compileOnly(files(projectZomboid.serverJar)) +} + +tasks.jar { + archiveBaseName = "zomboidforge-agent" + manifest.attributes("Premain-Class" to "dev.overlord.zomboidforge.agent.ForgeAgent") + // The agent jar is appended to the system class path and includes api, core and compat runtime. + from(configurations.runtimeClasspath.map { classpath -> classpath.map { zipTree(it) } }) + duplicatesStrategy = DuplicatesStrategy.EXCLUDE +} diff --git a/agent/src/main/java/dev/overlord/zomboidforge/agent/ForgeAgent.java b/agent/src/main/java/dev/overlord/zomboidforge/agent/ForgeAgent.java new file mode 100644 index 0000000..e986e00 --- /dev/null +++ b/agent/src/main/java/dev/overlord/zomboidforge/agent/ForgeAgent.java @@ -0,0 +1,24 @@ +package dev.overlord.zomboidforge.agent; + +import dev.overlord.zomboidforge.api.ZomboidForge; + +import java.lang.instrument.Instrumentation; + +public final class ForgeAgent +{ + private static Instrumentation instrumentation; + + private ForgeAgent() {} + + /** Runs before {@code zombie.network.GameServer.main}; Project Zomboid's logging is not initialized yet. */ + public static void premain(String args, Instrumentation inst) { + instrumentation = inst; + System.out.println("[ZomboidForge] Agent " + ZomboidForge.VERSION + " loaded."); + } + + public static Instrumentation instrumentation() { + if (instrumentation == null) throw new IllegalStateException("ZomboidForge agent was not loaded via -javaagent"); + + return instrumentation; + } +} diff --git a/api/build.gradle.kts b/api/build.gradle.kts new file mode 100644 index 0000000..220d193 --- /dev/null +++ b/api/build.gradle.kts @@ -0,0 +1,5 @@ +// API for custom Java mods. Version-independent: no references to game classes. + +plugins { + id("zomboidforge.java-conventions") +} diff --git a/api/src/main/java/dev/overlord/zomboidforge/api/ZomboidForge.java b/api/src/main/java/dev/overlord/zomboidforge/api/ZomboidForge.java new file mode 100644 index 0000000..d94a50f --- /dev/null +++ b/api/src/main/java/dev/overlord/zomboidforge/api/ZomboidForge.java @@ -0,0 +1,13 @@ +package dev.overlord.zomboidforge.api; + +import java.util.Objects; + +public final class ZomboidForge +{ + /** Build version, from the manifest of the jar these classes were loaded from. */ + public static final String VERSION = Objects.requireNonNullElse( + ZomboidForge.class.getPackage().getImplementationVersion(), "dev" + ); + + private ZomboidForge() {} +} diff --git a/build-logic/src/main/kotlin/ProjectZomboidExtension.kt b/build-logic/src/main/kotlin/ProjectZomboidExtension.kt index 9151ee8..7287e0f 100644 --- a/build-logic/src/main/kotlin/ProjectZomboidExtension.kt +++ b/build-logic/src/main/kotlin/ProjectZomboidExtension.kt @@ -1,6 +1,13 @@ import org.gradle.api.file.RegularFileProperty +import org.gradle.api.provider.Property abstract class ProjectZomboidExtension { /** Vanilla dedicated server projectzomboid.jar. Not bundled or published. */ abstract val serverJar: RegularFileProperty + + /** Targeted Project Zomboid version, e.g. "42.21" (gradle property pz.version). */ + abstract val version: Property + + /** Path of a compat module of the targeted Build, e.g. ":compat:b42:runtime". */ + fun compatProject(module: String): String = ":compat:b${version.get().substringBefore('.')}:$module" } diff --git a/build-logic/src/main/kotlin/zomboidforge.java-conventions.gradle.kts b/build-logic/src/main/kotlin/zomboidforge.java-conventions.gradle.kts index 5368393..0eca814 100644 --- a/build-logic/src/main/kotlin/zomboidforge.java-conventions.gradle.kts +++ b/build-logic/src/main/kotlin/zomboidforge.java-conventions.gradle.kts @@ -8,6 +8,13 @@ projectZomboid.serverJar.convention( providers.gradleProperty("pz.jar").orElse("lib/server/java/projectzomboid.jar") ) ) +projectZomboid.version.convention(providers.gradleProperty("pz.version")) + +val libs = extensions.getByType().named("libs") +dependencies { + "compileOnly"(libs.findLibrary("jetbrains-annotations").get()) + "testCompileOnly"(libs.findLibrary("jetbrains-annotations").get()) +} java { // Project Zomboid ships and runs on Java 25 (bundled Zulu jre64; class version 69). diff --git a/ci/release.sh b/ci/release.sh new file mode 100755 index 0000000..10e63d4 --- /dev/null +++ b/ci/release.sh @@ -0,0 +1,139 @@ +#!/usr/bin/env bash +# +# Builds the ZomboidForge image for one Project Zomboid version and optionally +# publishes it. Published tags: +# +# -pz-build immutable; never overwritten +# -pz moves to the newest Steam build of that version +# latest only with LATEST=true +# +# Nothing is built when the immutable tag already exists in the registry. +# +# Environment: +# IMAGE Image name without tag, e.g. git.security-command.org/overlord/zomboidforge +# PZ_BRANCH Steam branch. Default: public +# PZ_VERSION Expected Project Zomboid version. Default: pz.version in gradle.properties +# PUBLISH true: push the tags. Default: false (build and verify only) +# LATEST true: also push "latest". Default: false +# CONTAINER_ENGINE docker or podman. Default: docker if installed, else podman + +set -o errexit +set -o nounset +set -o pipefail + +REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +readonly REPO_ROOT + +readonly IMAGE="${IMAGE:?IMAGE is required}" +readonly PZ_BRANCH="${PZ_BRANCH:-public}" +readonly PUBLISH="${PUBLISH:-false}" +readonly LATEST="${LATEST:-false}" + +log() { + echo "[release] $*" >&2 +} + +container_engine() { + if [[ -n "${CONTAINER_ENGINE:-}" ]]; then + echo "${CONTAINER_ENGINE}" + elif command -v docker > /dev/null; then + echo "docker" + else + echo "podman" + fi +} + +# Prints the value of = in gradle.properties. +gradle_property() { + local key="$1" + local line + + while IFS= read -r line; do + if [[ "${line}" == "${key}="* ]]; then + echo "${line#*=}" + return + fi + done < "${REPO_ROOT}/gradle.properties" + + log "${key} not found in gradle.properties" + exit 1 +} + +image_exists() { + local reference="$1" + "$(container_engine)" manifest inspect "${reference}" > /dev/null 2>&1 +} + +build_image() { + local reference="$1" + local forge_version="$2" + local pz_version="$3" + local build_id="$4" + + "$(container_engine)" build \ + --platform linux/amd64 \ + --build-arg "PZ_BRANCH=${PZ_BRANCH}" \ + --build-arg "PZ_VERSION=${pz_version}" \ + --build-arg "FORGE_VERSION=${forge_version}" \ + --build-arg "STEAM_BUILDID=${build_id}" \ + --tag "${reference}" \ + "${REPO_ROOT}" +} + +# Steam can publish a new build between the build ID lookup and the download. +verify_build_id() { + local reference="$1" + local expected="$2" + local actual + + actual="$("$(container_engine)" run --rm --entrypoint cat "${reference}" /opt/pz/steam-buildid)" + if [[ "${actual}" != "${expected}" ]]; then + log "Image contains Steam build ${actual}, expected ${expected}; Steam updated during the build." + exit 1 + fi +} + +push_as() { + local source="$1" + local target="$2" + + "$(container_engine)" tag "${source}" "${target}" + "$(container_engine)" push "${target}" + log "Pushed ${target}" +} + +main() { + local forge_version + local pz_version + local build_id + + forge_version="$(gradle_property version)" + pz_version="${PZ_VERSION:-$(gradle_property pz.version)}" + build_id="$("${REPO_ROOT}/ci/steam-buildid.sh" "${PZ_BRANCH}")" + + local immutable_tag="${IMAGE}:${forge_version}-pz${pz_version}-build${build_id}" + local version_tag="${IMAGE}:${forge_version}-pz${pz_version}" + log "ZomboidForge ${forge_version}, Project Zomboid ${pz_version}, Steam branch ${PZ_BRANCH} build ${build_id}" + + if [[ "${PUBLISH}" == true ]] && image_exists "${immutable_tag}"; then + log "${immutable_tag} is already published; nothing to do." + return + fi + + build_image "${immutable_tag}" "${forge_version}" "${pz_version}" "${build_id}" + verify_build_id "${immutable_tag}" "${build_id}" + + if [[ "${PUBLISH}" != true ]]; then + log "Built ${immutable_tag} (PUBLISH is not true; nothing pushed)" + return + fi + + "$(container_engine)" push "${immutable_tag}" + log "Pushed ${immutable_tag}" + push_as "${immutable_tag}" "${version_tag}" + if [[ "${LATEST}" == true ]]; then + push_as "${immutable_tag}" "${IMAGE}:latest" + fi +} + +main diff --git a/ci/steam-buildid.sh b/ci/steam-buildid.sh new file mode 100755 index 0000000..35b7656 --- /dev/null +++ b/ci/steam-buildid.sh @@ -0,0 +1,71 @@ +#!/usr/bin/env bash +# +# Prints the current Steam build ID of a branch of the Project Zomboid +# dedicated server (app 380870), using steamcmd in a container. +# +# Usage: steam-buildid.sh +# Steam branch: public, unstable, or a version branch such as 42.19 +# +# Environment: +# CONTAINER_ENGINE docker or podman. Default: docker if installed, else podman + +set -o errexit +set -o nounset +set -o pipefail + +readonly APP_ID="380870" +readonly STEAMCMD_IMAGE="docker.io/steamcmd/steamcmd:debian-13" + +readonly BRANCH="$1" + +log() { + echo "[steam-buildid] $*" >&2 +} + +container_engine() { + if [[ -n "${CONTAINER_ENGINE:-}" ]]; then + echo "${CONTAINER_ENGINE}" + elif command -v docker > /dev/null; then + echo "docker" + else + echo "podman" + fi +} + +# Prints app_info for the app. The output is Valve KeyValues text; the +# "branches" section contains one block per branch with its "buildid". +print_app_info() { + "$(container_engine)" run --rm "${STEAMCMD_IMAGE}" \ + +login anonymous \ + +app_info_update 1 \ + +app_info_print "${APP_ID}" \ + +quit +} + +# Reads the buildid of the branch block inside the "branches" section. +extract_build_id() { + awk -v branch="\"${BRANCH}\"" ' + $1 == "\"branches\"" { in_branches = 1; next } + in_branches && $1 == branch { in_branch = 1; next } + in_branch && $1 == "\"buildid\"" { gsub(/"/, "", $2); print $2; exit } + in_branch && $1 == "}" { exit } + ' +} + +main() { + local app_info + local build_id + + # Captured first: extract_build_id stops reading early, which would end + # print_app_info with SIGPIPE inside a pipeline. + app_info="$(print_app_info)" + build_id="$(extract_build_id <<< "${app_info}")" + + if [[ -z "${build_id}" ]]; then + log "No build ID found for branch '${BRANCH}' of app ${APP_ID}" + exit 1 + fi + echo "${build_id}" +} + +main diff --git a/compat/b42/patches/build.gradle.kts b/compat/b42/patches/build.gradle.kts new file mode 100644 index 0000000..0a309a5 --- /dev/null +++ b/compat/b42/patches/build.gradle.kts @@ -0,0 +1,10 @@ +// Build-time patches for Project Zomboid Build 42. + +plugins { + id("zomboidforge.java-conventions") +} + +dependencies { + implementation(project(":patcher")) + implementation(libs.bundles.asm) +} diff --git a/compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/patches/B42PatchSet.java b/compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/patches/B42PatchSet.java new file mode 100644 index 0000000..fa85aac --- /dev/null +++ b/compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/patches/B42PatchSet.java @@ -0,0 +1,21 @@ +package dev.overlord.zomboidforge.compat.b42.patches; + +import dev.overlord.zomboidforge.patcher.ClassPatch; +import dev.overlord.zomboidforge.patcher.PatchSet; + +import java.util.List; + +/** Every build-time patch for Build 42, in application order. */ +public final class B42PatchSet implements PatchSet { + private static final List PATCHES = List.of(); + + @Override + public int build() { + return 42; + } + + @Override + public List patches() { + return PATCHES; + } +} diff --git a/compat/b42/patches/src/main/resources/META-INF/services/dev.overlord.zomboidforge.patcher.PatchSet b/compat/b42/patches/src/main/resources/META-INF/services/dev.overlord.zomboidforge.patcher.PatchSet new file mode 100644 index 0000000..2f47db8 --- /dev/null +++ b/compat/b42/patches/src/main/resources/META-INF/services/dev.overlord.zomboidforge.patcher.PatchSet @@ -0,0 +1 @@ +dev.overlord.zomboidforge.compat.b42.patches.B42PatchSet diff --git a/compat/b42/runtime/build.gradle.kts b/compat/b42/runtime/build.gradle.kts new file mode 100644 index 0000000..18de99a --- /dev/null +++ b/compat/b42/runtime/build.gradle.kts @@ -0,0 +1,12 @@ +// Runtime code for Project Zomboid Build 42: hooks called by patched game code, and +// adapters between game classes and the version-independent core and api. + +plugins { + id("zomboidforge.java-conventions") +} + +dependencies { + implementation(project(":core")) + implementation(project(":api")) + compileOnly(files(projectZomboid.serverJar)) +} diff --git a/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/package-info.java b/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/package-info.java new file mode 100644 index 0000000..a694060 --- /dev/null +++ b/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/package-info.java @@ -0,0 +1,5 @@ +/** + * Build 42 runtime code: hooks that patched game classes call, and adapters between + * game classes and the version-independent {@code core} and {@code api}. + */ +package dev.overlord.zomboidforge.compat.b42; diff --git a/compose.yaml b/compose.yaml index 62b69e0..79ac385 100644 --- a/compose.yaml +++ b/compose.yaml @@ -1,19 +1,31 @@ -# Local test setup: `podman compose up --build`. Passwords are read from the -# environment or from .env (gitignored). +# Local test setup: `podman compose up --build`. Settings are read from the +# environment or from .env (gitignored); docker/entrypoint.sh lists all variables. services: zomboidforge: build: . image: localhost/zomboidforge:dev platform: linux/amd64 environment: - SERVER_NAME: ${SERVER_NAME:-zomboidforgetest} - ADMIN_PASSWORD: ${ADMIN_PASSWORD:-} - RCON_PASSWORD: ${RCON_PASSWORD:-} - JVM_MAX_HEAP: ${JVM_MAX_HEAP:-8g} + SERVER_NAME: ${SERVER_NAME:-zomboidforgetest} + SERVER_PASSWORD: ${SERVER_PASSWORD:-} + PUBLIC: ${PUBLIC:-} + PUBLIC_NAME: ${PUBLIC_NAME:-} + PORT: ${PORT:-16261} + UDP_PORT: ${UDP_PORT:-16262} + ADMIN_USERNAME: ${ADMIN_USERNAME:-} + ADMIN_PASSWORD: ${ADMIN_PASSWORD:-} + SERVER_PRESET: ${SERVER_PRESET:-} + MODS: ${MODS:-} + WORKSHOP_ITEMS: ${WORKSHOP_ITEMS:-} + RCON_PASSWORD: ${RCON_PASSWORD:-} + JVM_MIN_HEAP: ${JVM_MIN_HEAP:-} + JVM_MAX_HEAP: ${JVM_MAX_HEAP:-8g} ports: - - "16261:16261/udp" - - "16262:16262/udp" - - "27015:27015/tcp" + # Host and container ports must be equal: the server reports its own port + # to Steam and to clients, so a remapped port is unreachable. + - "${PORT:-16261}:${PORT:-16261}/udp" + - "${UDP_PORT:-16262}:${UDP_PORT:-16262}/udp" + - "127.0.0.1:27015:27015/tcp" volumes: - zomboid-data:/data # SIGTERM runs GameServer's shutdown hook, which queues a save-and-quit. diff --git a/core/build.gradle.kts b/core/build.gradle.kts new file mode 100644 index 0000000..611e340 --- /dev/null +++ b/core/build.gradle.kts @@ -0,0 +1,9 @@ +// Version-independent runtime: mod loading, events, configuration. No game references. + +plugins { + id("zomboidforge.java-conventions") +} + +dependencies { + implementation(project(":api")) +} diff --git a/core/src/main/java/dev/overlord/zomboidforge/core/package-info.java b/core/src/main/java/dev/overlord/zomboidforge/core/package-info.java new file mode 100644 index 0000000..b001fcc --- /dev/null +++ b/core/src/main/java/dev/overlord/zomboidforge/core/package-info.java @@ -0,0 +1,5 @@ +/** + * Version-independent runtime: mod loading, events, configuration. Contains no + * references to game classes; game-specific code is in the compat modules. + */ +package dev.overlord.zomboidforge.core; diff --git a/docker/entrypoint.sh b/docker/entrypoint.sh index f1ec3e0..1e1de86 100755 --- a/docker/entrypoint.sh +++ b/docker/entrypoint.sh @@ -4,12 +4,41 @@ # with the ZomboidForge agent. Arguments are passed through to # zombie.network.GameServer. # -# Environment variables: -# SERVER_NAME Server config name (/data/Server/.ini). Default: zomboidforge -# ADMIN_PASSWORD Admin account password. Required on the first start only. -# RCON_PASSWORD Written into the server .ini before every start. RCON is disabled when empty. -# JVM_MAX_HEAP Value for -Xmx. Default: 8g (the vanilla ProjectZomboid64.json value) -# STEAM 1 = Steam mode (required for official Steam clients), 0 = no Steam. Default: 1 +# Environment variables (unset or empty keep the value in the server .ini, or the game default): +# +# Server +# SERVER_NAME Server config name (/data/Server/.ini). Default: zomboidforge +# SERVER_PASSWORD Password clients need to join (.ini Password) +# PUBLIC true/false: listed in the in-game server browser (.ini Public) +# PUBLIC_NAME Name in the server browser (.ini PublicName) +# PORT Game port (-port). Default: 16261 +# UDP_PORT Direct connection port (-udpport). Default: 16262 +# STEAM 1 = Steam mode (required for official Steam clients), 0 = no Steam. Default: 1 +# +# Admin account +# ADMIN_USERNAME Admin account name (-adminusername), passed on every start. +# Project Zomboid creates the account when it does not exist. Default: admin +# ADMIN_PASSWORD Password for creating that account (-adminpassword). Required while +# the account does not exist; not passed once it does. +# +# New server +# SERVER_PRESET Sandbox preset from media/lua/shared/Sandbox (e.g. Apocalypse), +# copied to _SandboxVars.lua when that file does not exist +# +# Mods +# MODS Semicolon-separated mod IDs (.ini Mods). Build 42 format: \ModA;\ModB +# WORKSHOP_ITEMS Semicolon-separated Workshop item IDs (.ini WorkshopItems) +# +# RCON +# RCON_PASSWORD Written into the .ini before every start. RCON is disabled when empty. +# +# JVM +# JVM_MIN_HEAP Value for -Xms. Default: JVM default +# JVM_MAX_HEAP Value for -Xmx. Default: 8g (the vanilla ProjectZomboid64.json value) +# +# Maintenance +# SOFT_RESET true: start in Project Zomboid's soft reset mode (-Dsoftreset). +# Intended for a single start; unset it afterwards. set -o errexit set -o nounset @@ -19,20 +48,67 @@ readonly INSTALL_DIR="/opt/pz" readonly DATA_DIR="/data" readonly AGENT_JAR="${INSTALL_DIR}/zomboidforge-agent.jar" readonly JAVA="${INSTALL_DIR}/jre64/bin/java" +readonly SANDBOX_PRESET_DIR="${INSTALL_DIR}/media/lua/shared/Sandbox" readonly SERVER_NAME="${SERVER_NAME:-zomboidforge}" -readonly ADMIN_PASSWORD="${ADMIN_PASSWORD:-}" -readonly RCON_PASSWORD="${RCON_PASSWORD:-}" -readonly JVM_MAX_HEAP="${JVM_MAX_HEAP:-8g}" +readonly SERVER_PASSWORD="${SERVER_PASSWORD:-}" +readonly PUBLIC="${PUBLIC:-}" +readonly PUBLIC_NAME="${PUBLIC_NAME:-}" +readonly PORT="${PORT:-}" +readonly UDP_PORT="${UDP_PORT:-}" readonly STEAM="${STEAM:-1}" +readonly ADMIN_USERNAME="${ADMIN_USERNAME:-}" +readonly ADMIN_PASSWORD="${ADMIN_PASSWORD:-}" +readonly SERVER_PRESET="${SERVER_PRESET:-}" +readonly MODS="${MODS:-}" +readonly WORKSHOP_ITEMS="${WORKSHOP_ITEMS:-}" +readonly RCON_PASSWORD="${RCON_PASSWORD:-}" +readonly JVM_MIN_HEAP="${JVM_MIN_HEAP:-}" +readonly JVM_MAX_HEAP="${JVM_MAX_HEAP:-8g}" +readonly SOFT_RESET="${SOFT_RESET:-}" readonly SERVER_INI="${DATA_DIR}/Server/${SERVER_NAME}.ini" +readonly SERVER_SANDBOX_VARS="${DATA_DIR}/Server/${SERVER_NAME}_SandboxVars.lua" readonly SERVER_DB="${DATA_DIR}/db/${SERVER_NAME}.db" +# Target of the /opt/pz/steamapps symlink; Steam stores Workshop downloads there. +readonly STEAMAPPS_DIR="${DATA_DIR}/steamapps" log() { echo "[entrypoint] $*" >&2 } +fail() { + log "$*" + exit 1 +} + +# True for 1/true/yes, case-insensitive. +is_true() { + local value="${1,,}" + [[ "${value}" == "1" || "${value}" == "true" || "${value}" == "yes" ]] +} + +# True for 0/false/no, case-insensitive. +is_false() { + local value="${1,,}" + [[ "${value}" == "0" || "${value}" == "false" || "${value}" == "no" ]] +} + +# Same lookup as ServerWorldDatabase.create(), which prompts on stdin for a +# password when the admin account does not exist and no -adminpassword is given. +admin_account_exists() { + local username="${ADMIN_USERNAME:-admin}" + local escaped_username="${username//\'/\'\'}" + local account_id + + if [[ ! -f "${SERVER_DB}" ]]; then + return 1 + fi + account_id="$(sqlite3 -readonly "${SERVER_DB}" \ + "SELECT id FROM whitelist WHERE username = '${escaped_username}';")" + [[ -n "${account_id}" ]] +} + # Sets = in the server .ini. Creates the file or the key if missing. # Project Zomboid reads a partial .ini and writes the missing defaults on start. set_ini_value() { @@ -63,30 +139,101 @@ set_ini_value() { mv "${temp_file}" "${SERVER_INI}" } -apply_rcon_password() { - if [[ -z "${RCON_PASSWORD}" ]]; then +# Sets = only when is not empty. +set_ini_value_if_given() { + local key="$1" + local value="$2" + + if [[ -n "${value}" ]]; then + set_ini_value "${key}" "${value}" + fi +} + +apply_ini_settings() { + set_ini_value_if_given "Password" "${SERVER_PASSWORD}" + set_ini_value_if_given "PublicName" "${PUBLIC_NAME}" + set_ini_value_if_given "Mods" "${MODS}" + set_ini_value_if_given "WorkshopItems" "${WORKSHOP_ITEMS}" + + if [[ -n "${PUBLIC}" ]]; then + if is_true "${PUBLIC}"; then + set_ini_value "Public" "true" + elif is_false "${PUBLIC}"; then + set_ini_value "Public" "false" + else + fail "PUBLIC must be true or false, got '${PUBLIC}'." + fi + fi + + if [[ -n "${RCON_PASSWORD}" ]]; then + set_ini_value "RCONPassword" "${RCON_PASSWORD}" + else log "RCON_PASSWORD is not set; RCON stays disabled unless the .ini sets RCONPassword." + fi +} + +# Preset names, without SandboxVars.lua (which only references a preset). +list_sandbox_presets() { + local file + local names=() + + for file in "${SANDBOX_PRESET_DIR}"/*.lua; do + file="$(basename "${file}" .lua)" + if [[ "${file}" != "SandboxVars" ]]; then + names+=("${file}") + fi + done + echo "${names[*]}" +} + +# Presets start with "return {" and use CRLF line endings; the server's +# _SandboxVars.lua starts with "SandboxVars = {". +install_sandbox_preset() { + local preset_file="${SANDBOX_PRESET_DIR}/${SERVER_PRESET}.lua" + local first_line=true + local line + + if [[ -z "${SERVER_PRESET}" || -f "${SERVER_SANDBOX_VARS}" ]]; then return fi - set_ini_value "RCONPassword" "${RCON_PASSWORD}" + if [[ "${SERVER_PRESET}" == "SandboxVars" || ! -f "${preset_file}" ]]; then + fail "Unknown SERVER_PRESET '${SERVER_PRESET}'. Available: $(list_sandbox_presets)" + fi + + log "Creating ${SERVER_SANDBOX_VARS} from preset ${SERVER_PRESET}" + mkdir --parents "$(dirname "${SERVER_SANDBOX_VARS}")" + while IFS= read -r line || [[ -n "${line}" ]]; do + line="${line%$'\r'}" + if [[ "${first_line}" == true ]]; then + if [[ "${line}" != "return {" ]]; then + fail "Unexpected first line in ${preset_file}: '${line}'" + fi + line="SandboxVars = {" + first_line=false + fi + printf '%s\n' "${line}" + done < "${preset_file}" > "${SERVER_SANDBOX_VARS}" } -# Without -adminpassword, Project Zomboid blocks on an interactive prompt to -# create the admin account on the first start. -check_admin_password() { - if [[ -z "${ADMIN_PASSWORD}" && ! -f "${SERVER_DB}" ]]; then - log "First start of '${SERVER_NAME}': ADMIN_PASSWORD is required to create the admin account." - exit 1 +# Sets needs_admin_password, used by build_server_args. +check_admin_account() { + if admin_account_exists; then + needs_admin_password=false + if [[ -n "${ADMIN_PASSWORD}" ]]; then + log "ADMIN_PASSWORD is ignored: the admin account '${ADMIN_USERNAME:-admin}' already exists." + fi + else + needs_admin_password=true + if [[ -z "${ADMIN_PASSWORD}" ]]; then + fail "The admin account '${ADMIN_USERNAME:-admin}' of '${SERVER_NAME}' does not exist yet: ADMIN_PASSWORD is required to create it." + fi fi } -main() { - apply_rcon_password - check_admin_password - - # Same JVM setup as the vanilla ProjectZomboid64.json and start-server.sh. - # Java runs directly instead of through the native ProjectZomboid64 launcher. - local jvm_args=( +# Same JVM setup as the vanilla ProjectZomboid64.json and start-server.sh. +# Java runs directly instead of through the native ProjectZomboid64 launcher. +build_jvm_args() { + jvm_args=( "-javaagent:${AGENT_JAR}" "-Djava.awt.headless=true" "--enable-native-access=ALL-UNNAMED" @@ -100,13 +247,49 @@ main() { "-cp" "java/:java/projectzomboid.jar" ) - local server_args=( + if [[ -n "${JVM_MIN_HEAP}" ]]; then + jvm_args+=("-Xms${JVM_MIN_HEAP}") + fi + if [[ -n "${SOFT_RESET}" ]] && is_true "${SOFT_RESET}"; then + log "SOFT_RESET is set: starting in soft reset mode. Unset it for the next start." + jvm_args+=("-Dsoftreset") + fi +} + +build_server_args() { + server_args=( "-cachedir=${DATA_DIR}" "-servername" "${SERVER_NAME}" ) - if [[ -n "${ADMIN_PASSWORD}" ]]; then + + if [[ -n "${PORT}" ]]; then + server_args+=("-port" "${PORT}") + fi + if [[ -n "${UDP_PORT}" ]]; then + server_args+=("-udpport" "${UDP_PORT}") + fi + + if [[ -n "${ADMIN_USERNAME}" ]]; then + server_args+=("-adminusername" "${ADMIN_USERNAME}") + fi + # Only while the account does not exist: the value is visible in the process arguments. + if [[ "${needs_admin_password}" == true ]]; then server_args+=("-adminpassword" "${ADMIN_PASSWORD}") fi +} + +main() { + mkdir --parents "${STEAMAPPS_DIR}" + + local needs_admin_password + check_admin_account + apply_ini_settings + install_sandbox_preset + + local jvm_args + local server_args + build_jvm_args + build_server_args # Native libraries: game (linux64/), Steam (install root), JVM (jre64/lib). # libjsig.so chains signal handlers between the JVM and native libraries. diff --git a/docker/install-server.sh b/docker/install-server.sh index 6c35950..59aae47 100755 --- a/docker/install-server.sh +++ b/docker/install-server.sh @@ -4,8 +4,14 @@ # with steamcmd, using an anonymous login. Runs in the steamcmd image during # the Docker build. # -# Usage: install-server.sh -# Steam branch; "public" is the default branch. +# Usage: install-server.sh +# Steam branch: "public" (default branch), "unstable", or a +# version branch such as "42.19". +# "bundled" keeps the steamclient.so files shipped with the +# server; "steamcmd" replaces them with steamcmd's own, newer +# copies (a known workaround for failing Workshop downloads). +# +# Writes the installed Steam build ID to /steam-buildid. set -o errexit set -o nounset @@ -13,15 +19,17 @@ set -o pipefail readonly APP_ID="380870" readonly MAX_ATTEMPTS=3 +readonly STEAMCMD_DIR="${HOME}/.local/share/Steam/steamcmd" readonly INSTALL_DIR="$1" readonly BRANCH="$2" +readonly STEAMCLIENT="$3" log() { echo "[install-server] $*" >&2 } -main() { +install_app() { local branch_args=() if [[ "${BRANCH}" != "public" ]]; then branch_args=("-beta" "${BRANCH}") @@ -47,6 +55,43 @@ main() { log "Installation failed: ${INSTALL_DIR}/java/projectzomboid.jar not found" exit 1 fi +} + +# Copies the build ID from Steam's app manifest, which is removed afterwards. +record_build_id() { + local manifest="${INSTALL_DIR}/steamapps/appmanifest_${APP_ID}.acf" + local build_id + + build_id="$(grep --max-count=1 '"buildid"' "${manifest}" | tr --delete --complement '0-9')" + if [[ -z "${build_id}" ]]; then + log "No buildid found in ${manifest}" + exit 1 + fi + echo "${build_id}" > "${INSTALL_DIR}/steam-buildid" + log "Installed Steam build ${build_id}" +} + +# The install root holds the 32-bit steamclient.so, linux64/ the 64-bit one. +replace_steamclient() { + case "${STEAMCLIENT}" in + bundled) + ;; + steamcmd) + log "Replacing the bundled steamclient.so files with steamcmd's" + cp "${STEAMCMD_DIR}/linux32/steamclient.so" "${INSTALL_DIR}/steamclient.so" + cp "${STEAMCMD_DIR}/linux64/steamclient.so" "${INSTALL_DIR}/linux64/steamclient.so" + ;; + *) + log "Unknown steamclient option '${STEAMCLIENT}' (expected: bundled, steamcmd)" + exit 1 + ;; + esac +} + +main() { + install_app + record_build_id + replace_steamclient # Steam's install metadata; not needed at runtime. rm --recursive --force "${INSTALL_DIR}/steamapps" diff --git a/gradle.properties b/gradle.properties index 9542bf3..17da66e 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,6 +1,11 @@ group=dev.overlord.zomboidforge version=0.1.0-SNAPSHOT +# Project Zomboid version the build targets. Selects compat/b/, and +# :patcher:patchServerJar fails when the server jar reports another version. +# "42.21" matches every 42.21.x build; "42.21.0" matches exactly. +pz.version=42.21 + # Vanilla dedicated server jar used for compilation and patching. # Default: lib/server/java/projectzomboid.jar (relative to the root project). # The Docker build sets -Ppz.jar. diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 134b439..84aa56c 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -1,13 +1,16 @@ [versions] -asm = "9.10.1" -junit = "6.1.3" +asm = "9.10.1" +junit = "6.1.3" +jetbrains-annotations = "26.0.2" [libraries] -asm = { module = "org.ow2.asm:asm", version.ref = "asm" } -asm-tree = { module = "org.ow2.asm:asm-tree", version.ref = "asm" } -asm-commons = { module = "org.ow2.asm:asm-commons", version.ref = "asm" } -asm-util = { module = "org.ow2.asm:asm-util", version.ref = "asm" } -junit-bom = { module = "org.junit:junit-bom", version.ref = "junit" } +#noinspection UnusedVersionCatalogEntry +jetbrains-annotations = { module = "org.jetbrains:annotations", version.ref = "jetbrains-annotations" } +asm = { module = "org.ow2.asm:asm", version.ref = "asm" } +asm-tree = { module = "org.ow2.asm:asm-tree", version.ref = "asm" } +asm-commons = { module = "org.ow2.asm:asm-commons", version.ref = "asm" } +asm-util = { module = "org.ow2.asm:asm-util", version.ref = "asm" } +junit-bom = { module = "org.junit:junit-bom", version.ref = "junit" } junit-jupiter = { module = "org.junit.jupiter:junit-jupiter" } junit-platform-launcher = { module = "org.junit.platform:junit-platform-launcher" } diff --git a/patcher/build.gradle.kts b/patcher/build.gradle.kts new file mode 100644 index 0000000..c07396b --- /dev/null +++ b/patcher/build.gradle.kts @@ -0,0 +1,55 @@ +// Build-time patching engine. The patches themselves are in compat/b/patches. + +plugins { + id("zomboidforge.java-conventions") +} + +// Patch set of the targeted Build; only on the class path of patchServerJar. +val serverPatches = configurations.create("serverPatches") { + isCanBeConsumed = false + isCanBeResolved = true +} + +dependencies { + implementation(libs.bundles.asm) + serverPatches(project(projectZomboid.compatProject("patches"))) + + testImplementation(platform(libs.junit.bom)) + testImplementation(libs.junit.jupiter) + testRuntimeOnly(libs.junit.platform.launcher) +} + +tasks.test { + // Enables GameVersionReaderTest.readsTargetedVersionFromServerJar when the jar exists. + val serverJar = projectZomboid.serverJar + val targetedVersion = projectZomboid.version + inputs.property("pzVersion", targetedVersion) + jvmArgumentProviders.add(CommandLineArgumentProvider { + listOf( + "-Dpz.jar=${serverJar.get().asFile.absolutePath}", + "-Dpz.version=${targetedVersion.get()}", + ) + }) +} + +tasks.register("patchServerJar") { + description = "Applies the targeted Build's patches to the vanilla server jar." + group = "build" + + val vanillaJar = projectZomboid.serverJar + val patchedJar = layout.buildDirectory.file("server/projectzomboid.jar") + val expectedVersion = projectZomboid.version + inputs.file(vanillaJar).withPropertyName("vanillaJar") + inputs.property("expectedVersion", expectedVersion) + outputs.file(patchedJar).withPropertyName("patchedJar") + + classpath = sourceSets.main.get().runtimeClasspath + serverPatches + mainClass = "dev.overlord.zomboidforge.patcher.JarPatcher" + argumentProviders.add(CommandLineArgumentProvider { + listOf( + vanillaJar.get().asFile.absolutePath, + patchedJar.get().asFile.absolutePath, + expectedVersion.get(), + ) + }) +} diff --git a/patcher/src/main/java/dev/overlord/zomboidforge/patcher/ClassPatch.java b/patcher/src/main/java/dev/overlord/zomboidforge/patcher/ClassPatch.java new file mode 100644 index 0000000..2092099 --- /dev/null +++ b/patcher/src/main/java/dev/overlord/zomboidforge/patcher/ClassPatch.java @@ -0,0 +1,22 @@ +package dev.overlord.zomboidforge.patcher; + +import org.objectweb.asm.tree.ClassNode; + +/** A build-time change to one class of the vanilla server jar. */ +public interface ClassPatch { + /** Internal name of the class to patch, e.g. {@code zombie/network/GameServer}. */ + String target(); + + /** + * Whether the patch applies to the given game version. Patches that differ + * between minor versions of the same Build provide one implementation per + * version range. Default: every version. + */ + default boolean appliesTo(GameVersion version) { return true; } + + /** + * Modifies {@code node} in place. Throws if the class does not match what the + * patch expects (e.g. after a Project Zomboid update). + */ + void apply(ClassNode node); +} diff --git a/patcher/src/main/java/dev/overlord/zomboidforge/patcher/GameVersion.java b/patcher/src/main/java/dev/overlord/zomboidforge/patcher/GameVersion.java new file mode 100644 index 0000000..8b889aa --- /dev/null +++ b/patcher/src/main/java/dev/overlord/zomboidforge/patcher/GameVersion.java @@ -0,0 +1,72 @@ +package dev.overlord.zomboidforge.patcher; + +import org.jetbrains.annotations.NotNull; + +import java.util.Comparator; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** Project Zomboid version, e.g. 42.21.0 (Core.getGameAndBuildVersion()). */ +public record GameVersion(int major, int minor, int build) implements Comparable +{ + private static final Pattern FORMAT = Pattern.compile("(\\d+)\\.(\\d+)(?:\\.(\\d+))?"); + + private static final Comparator ORDER = Comparator + .comparingInt(GameVersion::major) + .thenComparingInt(GameVersion::minor) + .thenComparingInt(GameVersion::build); + + // + + /** Parses "42.21.0", or "42.21" as 42.21.0. */ + public static GameVersion parse(String text) + { + Matcher matcher = FORMAT.matcher(text.trim()); + if (!matcher.matches()) throw new IllegalArgumentException("Not a Project Zomboid version: " + text); + + int build = matcher.group(3) == null + ? 0 + : Integer.parseInt(matcher.group(3)); + + return new GameVersion( + Integer.parseInt(matcher.group(1)), + Integer.parseInt(matcher.group(2)), + build + ); + } + + /** + * Whether this version satisfies an expected version: "42.21" matches every + * 42.21.x build, "42.21.0" matches only 42.21.0. + */ + public boolean matches(String expected) + { + GameVersion other = parse(expected); + boolean buildGiven = expected.trim().chars().filter(c -> c == '.').count() == 2; + + return + major == other.major && + minor == other.minor && + (!buildGiven || build == other.build); + } + + // + + public boolean isAtLeast(int major, int minor) { + return compareTo(new GameVersion(major, minor, 0)) >= 0; + } + + public boolean isBefore(int major, int minor) { + return compareTo(new GameVersion(major, minor, 0)) < 0; + } + + @Override + public int compareTo(@NotNull GameVersion other) { + return ORDER.compare(this, other); + } + + @Override + public @NotNull String toString() { + return major + "." + minor + "." + build; + } +} diff --git a/patcher/src/main/java/dev/overlord/zomboidforge/patcher/GameVersionReader.java b/patcher/src/main/java/dev/overlord/zomboidforge/patcher/GameVersionReader.java new file mode 100644 index 0000000..8151b8f --- /dev/null +++ b/patcher/src/main/java/dev/overlord/zomboidforge/patcher/GameVersionReader.java @@ -0,0 +1,94 @@ +package dev.overlord.zomboidforge.patcher; + +import org.jetbrains.annotations.Contract; +import org.objectweb.asm.ClassReader; +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.tree.AbstractInsnNode; +import org.objectweb.asm.tree.ClassNode; +import org.objectweb.asm.tree.FieldInsnNode; +import org.objectweb.asm.tree.IntInsnNode; +import org.objectweb.asm.tree.MethodInsnNode; +import org.objectweb.asm.tree.MethodNode; + +import java.util.ArrayList; +import java.util.List; + +/** + * Reads the game version from the bytes of zombie/core/Core.class. + * + *

Core's static initializer contains {@code gameVersion = new GameVersion(major, minor, "")}, + * and {@code buildVersion} is a compile-time constant; together they form + * Core.getGameAndBuildVersion(). + */ +public final class GameVersionReader +{ + public static final String CORE_CLASS = "zombie/core/Core"; + private static final String GAME_VERSION_CLASS = "zombie/core/GameVersion"; + private static final String GAME_VERSION_FIELD = "gameVersion"; + private static final String BUILD_VERSION_FIELD = "buildVersion"; + + private GameVersionReader() {} + + public static GameVersion read(byte[] coreClass) + { + ClassNode core = new ClassNode(); + new ClassReader(coreClass).accept(core, 0); + + MethodNode staticInitializer = core.methods.stream() + .filter(m -> m.name.equals("")) + .findFirst() + .orElseThrow(() -> new IllegalStateException("Core has no static initializer.")); + + int[] majorMinor = readGameVersionConstructorArguments(staticInitializer); + return new GameVersion(majorMinor[0], majorMinor[1], readBuildVersion(core)); + } + + /** Finds the two int constants passed to the GameVersion constructor stored in Core.gameVersion. */ + private static int[] readGameVersionConstructorArguments(MethodNode staticInitializer) + { + List intConstants = new ArrayList<>(); + + for (AbstractInsnNode insn : staticInitializer.instructions) + { + if (insn.getOpcode() == Opcodes.NEW) intConstants.clear(); + + Integer constant = intConstant(insn); + if (constant != null) intConstants.add(constant); + + if + ( + insn instanceof MethodInsnNode call + && call.owner.equals(GAME_VERSION_CLASS) + && call.name.equals("") + && isGameVersionStore(call.getNext()) + && intConstants.size() == 2 + ) + { return new int[]{intConstants.get(0), intConstants.get(1)}; } + } + + throw new IllegalStateException("Core.gameVersion initialization not found."); + } + + private static boolean isGameVersionStore(AbstractInsnNode insn) { + return insn instanceof FieldInsnNode field + && field.getOpcode() == Opcodes.PUTSTATIC + && field.name.equals(GAME_VERSION_FIELD); + } + + private static int readBuildVersion(ClassNode core) { + return core.fields.stream() + .filter(f -> f.name.equals(BUILD_VERSION_FIELD) && f.value instanceof Integer) + .map(f -> (Integer) f.value) + .findFirst() + .orElseThrow(() -> new IllegalStateException("Core.buildVersion constant not found.")); + } + + private static Integer intConstant(AbstractInsnNode insn) + { + int opcode = insn.getOpcode(); + if (opcode >= Opcodes.ICONST_M1 && opcode <= Opcodes.ICONST_5) return opcode - Opcodes.ICONST_0; + if ((opcode == Opcodes.BIPUSH || opcode == Opcodes.SIPUSH) && insn instanceof IntInsnNode push) return push.operand; + + return null; + } +} diff --git a/patcher/src/main/java/dev/overlord/zomboidforge/patcher/HierarchyClassWriter.java b/patcher/src/main/java/dev/overlord/zomboidforge/patcher/HierarchyClassWriter.java new file mode 100644 index 0000000..8070840 --- /dev/null +++ b/patcher/src/main/java/dev/overlord/zomboidforge/patcher/HierarchyClassWriter.java @@ -0,0 +1,75 @@ +package dev.overlord.zomboidforge.patcher; + +import org.objectweb.asm.ClassReader; +import org.objectweb.asm.ClassWriter; +import org.objectweb.asm.Opcodes; + +import java.io.IOException; +import java.io.InputStream; +import java.io.UncheckedIOException; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.function.Function; + +/** + * {@link ClassWriter} that computes frames from class bytes instead of loading + * classes. The game classes are not on the patcher's class path, and loading + * them would run their static initializers. + */ +final class HierarchyClassWriter extends ClassWriter { + private static final String OBJECT = "java/lang/Object"; + + private record Header(String superName, boolean isInterface) {} + + private final Function jarClasses; + private final Map headers = new HashMap<>(); + + /** @param jarClasses bytes of a class in the jar being patched, or {@code null} */ + HierarchyClassWriter(Function jarClasses) { + super(COMPUTE_FRAMES); + this.jarClasses = jarClasses; + } + + @Override + protected String getCommonSuperClass(String type1, String type2) + { + if (header(type1).isInterface() || header(type2).isInterface()) return OBJECT; + + Set supers1 = new HashSet<>(); + for (String c = type1; c != null; c = header(c).superName()) { + supers1.add(c); + } + + for (String c = type2; c != null; c = header(c).superName()) { + if (supers1.contains(c)) { + return c; + } + } + + return OBJECT; + } + + private Header header(String internalName) { + return headers.computeIfAbsent(internalName, name -> { + ClassReader reader = new ClassReader(bytes(name)); + return new Header(reader.getSuperName(), (reader.getAccess() & Opcodes.ACC_INTERFACE) != 0); + }); + } + + private byte[] bytes(String internalName) + { + byte[] bytes = jarClasses.apply(internalName); + if (bytes != null) return bytes; + + // JDK (or other non-jar) class. + try (InputStream in = ClassLoader.getSystemResourceAsStream(internalName + ".class")) + { + if (in == null) throw new IllegalStateException("Class not found while computing frames: '" + internalName + "'."); + + return in.readAllBytes(); + } + catch (IOException e) { throw new UncheckedIOException(e); } + } +} diff --git a/patcher/src/main/java/dev/overlord/zomboidforge/patcher/JarPatcher.java b/patcher/src/main/java/dev/overlord/zomboidforge/patcher/JarPatcher.java new file mode 100644 index 0000000..09ed8a7 --- /dev/null +++ b/patcher/src/main/java/dev/overlord/zomboidforge/patcher/JarPatcher.java @@ -0,0 +1,194 @@ +package dev.overlord.zomboidforge.patcher; + +import org.objectweb.asm.ClassReader; +import org.objectweb.asm.tree.ClassNode; + +import java.io.IOException; +import java.io.UncheckedIOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Enumeration; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.ServiceLoader; +import java.util.zip.ZipEntry; +import java.util.zip.ZipFile; +import java.util.zip.ZipOutputStream; + +/** + * Copies a jar, applying {@link ClassPatch}es to their target classes. Every + * other entry is copied through unchanged. + */ +public final class JarPatcher +{ + private static final String VERSIONED_PREFIX = "META-INF/versions/"; + + private final Map> patchesByEntry = new LinkedHashMap<>(); + + public JarPatcher(Collection patches) { + for (ClassPatch patch : patches) { + patchesByEntry.computeIfAbsent(patch.target() + ".class", k -> new ArrayList<>()).add(patch); + } + } + + // + + /** + * Usage: {@code JarPatcher }. Loads the + * single {@link PatchSet} on the class path and applies every patch that applies to + * the jar's game version. + */ + static void main(String[] args) throws IOException + { + if (args.length != 3) { + System.err.println("Usage: JarPatcher "); + System.exit(2); + } + + Path vanillaJar = Path.of(args[0]); + Path patchedJar = Path.of(args[1]); + String expectedVersion = args[2]; + + GameVersion version = readGameVersion(vanillaJar); + if (!version.matches(expectedVersion)) { + throw new IllegalStateException( + "Server jar is Project Zomboid " + version + + ", but the build targets " + expectedVersion + + " (gradle property pz.version)" + ); + } + + PatchSet patchSet = loadPatchSet(); + List applicable = applicablePatches(patchSet, version); + + int patchedClasses = new JarPatcher(applicable).patch(vanillaJar, patchedJar); + System.out.println( + "Project Zomboid " + version + ": patched " + patchedClasses + " class(es) with " + + applicable.size() + " of " + patchSet.patches().size() + " patch(es) -> " + patchedJar + ); + } + + /** Reads the game version from zombie/core/Core.class in the jar. */ + public static GameVersion readGameVersion(Path jar) throws IOException + { + try (ZipFile zip = new ZipFile(jar.toFile())) + { + byte[] core = read(zip, GameVersionReader.CORE_CLASS + ".class"); + if (core == null) throw new IllegalStateException("'" + jar + "' contains no " + GameVersionReader.CORE_CLASS + ".class"); + + return GameVersionReader.read(core); + } + } + + /** Patches of {@code patchSet} that apply to {@code version}, in application order. */ + public static List applicablePatches(PatchSet patchSet, GameVersion version) + { + if (patchSet.build() != version.major()) { + throw new IllegalStateException( + "Patch set is for Build " + patchSet.build() + + ", but the server jar is Project Zomboid " + version + ); + } + + return patchSet.patches().stream() + .filter(patch -> patch.appliesTo(version)) + .toList(); + } + + private static PatchSet loadPatchSet() + { + List patchSets = ServiceLoader.load(PatchSet.class) + .stream() + .map(ServiceLoader.Provider::get) + .toList(); + + if (patchSets.size() != 1) throw new IllegalStateException("Expected exactly one PatchSet on the class path, found: " + patchSets.size()); + + return patchSets.getFirst(); + } + + /** @return the number of classes that were patched */ + public int patch(Path in, Path out) throws IOException + { + Path parent = out.toAbsolutePath().getParent(); + if (parent != null) Files.createDirectories(parent); + + try ( + ZipFile jar = new ZipFile(in.toFile()); + ZipOutputStream zip = new ZipOutputStream(Files.newOutputStream(out)) + ) { + checkTargets(jar); + int patched = 0; + + for (Enumeration entries = jar.entries(); entries.hasMoreElements();) + { + ZipEntry entry = entries.nextElement(); + List patches = patchesByEntry.get(entry.getName()); + byte[] bytes = jar.getInputStream(entry).readAllBytes(); + + if (patches != null) { + bytes = transform(jar, bytes, patches); + patched++; + } + + ZipEntry copy = new ZipEntry(entry.getName()); + copy.setTime(entry.getTime()); + + zip.putNextEntry(copy); + zip.write(bytes); + zip.closeEntry(); + } + + return patched; + } + } + + /** Fails if a target is missing or shadowed by an unpatched multi-release override. */ + private void checkTargets(ZipFile jar) + { + List problems = new ArrayList<>(); + + for (String name : patchesByEntry.keySet()) { + if (jar.getEntry(name) == null) { + problems.add("'" + name + "' not found in jar."); + } + } + + jar.stream() + .map(ZipEntry::getName) + .filter(n -> n.startsWith(VERSIONED_PREFIX)) + .filter(n -> patchesByEntry.containsKey(n.substring(n.indexOf('/', VERSIONED_PREFIX.length()) + 1))) + .forEach(n -> problems.add("'" + n + "' overrides a patched class.")); + + if (!problems.isEmpty()) { + throw new IllegalStateException("Cannot patch '" + jar.getName() + "':\n " + String.join("\n ", problems)); + } + } + + private static byte[] transform(ZipFile jar, byte[] bytes, List patches) + { + ClassNode node = new ClassNode(); + new ClassReader(bytes).accept(node, 0); + + for (ClassPatch patch : patches) { + patch.apply(node); + } + + HierarchyClassWriter writer = new HierarchyClassWriter(name -> read(jar, name + ".class")); + node.accept(writer); + + return writer.toByteArray(); + } + + private static byte[] read(ZipFile jar, String entryName) + { + ZipEntry entry = jar.getEntry(entryName); + if (entry == null) return null; + + try { return jar.getInputStream(entry).readAllBytes(); } + catch (IOException e) { throw new UncheckedIOException(e); } + } +} diff --git a/patcher/src/main/java/dev/overlord/zomboidforge/patcher/PatchSet.java b/patcher/src/main/java/dev/overlord/zomboidforge/patcher/PatchSet.java new file mode 100644 index 0000000..cd07020 --- /dev/null +++ b/patcher/src/main/java/dev/overlord/zomboidforge/patcher/PatchSet.java @@ -0,0 +1,15 @@ +package dev.overlord.zomboidforge.patcher; + +import java.util.List; + +/** + * All build-time patches of one Project Zomboid Build, provided by a compat module + * (compat/b<major>/patches) through {@link java.util.ServiceLoader}. + */ +public interface PatchSet { + /** Project Zomboid major version (Build) the patches are written for, e.g. 42. */ + int build(); + + /** Patches in application order. */ + List patches(); +} diff --git a/settings.gradle.kts b/settings.gradle.kts index b9c08c5..a3163c2 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -10,4 +10,9 @@ dependencyResolutionManagement { rootProject.name = "ZomboidForge" -include("api", "agent", "patcher") +include("api", "core", "agent", "patcher") + +// Only the compat modules of the selected Project Zomboid Build are part of the build. +// Each of them compiles against that Build's server jar. +val pzBuild = providers.gradleProperty("pz.version").get().substringBefore('.') +include(":compat:b$pzBuild:patches", ":compat:b$pzBuild:runtime")