diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml index 88bd92d..ae25a5e 100644 --- a/.gitea/workflows/ci.yml +++ b/.gitea/workflows/ci.yml @@ -15,12 +15,12 @@ jobs: include: # One entry per supported version; add older Steam version branches # (e.g. pz_version 42.19, steam_branch 42.19) to keep them building. - - pz_version: "42.21" + - pz_version: "42" steam_branch: public steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 with: - # release.sh derives the version from the newest v* tag + # release.sh derives the version from the v* tags fetch-depth: 0 - name: Build and verify diff --git a/.gitea/workflows/publish.yml b/.gitea/workflows/publish.yml index 0b964ba..efe9f25 100644 --- a/.gitea/workflows/publish.yml +++ b/.gitea/workflows/publish.yml @@ -9,25 +9,27 @@ on: push: tags: - "v*" - workflow_dispatch: jobs: maven: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 with: - # publish.sh derives the version from the newest v* tag + # publish.sh derives the version from the v* tag on HEAD fetch-depth: 0 - - uses: actions/setup-java@v4 + - uses: actions/setup-java@cf277c60eb25467037889841efdb72551f06f6c3 # v4.9.1 with: distribution: temurin java-version: "25" - - name: Test and publish + # The tests run without the registry credentials; only the publish step gets them. + - name: Test + run: ci/publish.sh test + + - name: Publish env: ORG_GRADLE_PROJECT_giteaUsername: ${{ secrets.REGISTRY_USER }} ORG_GRADLE_PROJECT_giteaPassword: ${{ secrets.REGISTRY_TOKEN }} - PUBLISH: "true" - run: ci/publish.sh + run: ci/publish.sh publish diff --git a/.gitea/workflows/release.yml b/.gitea/workflows/release.yml index 8b8558a..0c0c4f2 100644 --- a/.gitea/workflows/release.yml +++ b/.gitea/workflows/release.yml @@ -1,12 +1,16 @@ -# Publishes an image for every new Steam build of each supported Project Zomboid -# version. Immutable tags are never overwritten (see ci/release.sh). +# Publishes an image for every new Project Zomboid version (hotfixes included) of each +# matrix entry and every new ZomboidForge release; full version tags are never overwritten +# (see ci/release.sh). # Requires the repository secrets REGISTRY_USER and REGISTRY_TOKEN (a token with # package write access) and a runner with a Docker (or Podman) CLI. name: release on: + # Every 2.5 hours; cron cannot divide a day into 2.5-hour steps, so the gap + # from 22:30 to 00:00 is 1.5 hours. schedule: - - cron: "0 */6 * * *" + - cron: "0 0,5,10,15,20 * * *" + - cron: "30 2,7,12,17,22 * * *" workflow_dispatch: jobs: @@ -16,13 +20,13 @@ jobs: fail-fast: false matrix: include: - - pz_version: "42.21" + - pz_version: "42" steam_branch: public latest: "true" steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 with: - # release.sh derives the version from the newest v* tag + # release.sh derives the version from the v* tags fetch-depth: 0 - name: Log in to the registry @@ -39,3 +43,8 @@ jobs: PUBLISH: "true" LATEST: ${{ matrix.latest }} run: ci/release.sh + + # Removes the stored registry token, also when a step failed, in case the runner is reused. + - name: Log out of the registry + if: always() + run: docker logout git.security-command.org diff --git a/Dockerfile b/Dockerfile index 92db997..0d14573 100644 --- a/Dockerfile +++ b/Dockerfile @@ -6,6 +6,10 @@ # podman build --platform linux/amd64 -t zomboidforge . # podman build --build-arg PZ_BRANCH=42.19 --build-arg PZ_VERSION=42.19 ... # +# The stage game-version (--target game-version) downloads only the server jar of +# PZ_BRANCH and writes its game version to /game-version; ci/release.sh uses it to +# name the image before the full build. +# # 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 @@ -14,7 +18,8 @@ # files with steamcmd's newer copies # FORGE_VERSION ZomboidForge version (jar manifest, image label); set by ci/release.sh. # Default: 0.0.0-prerelease -# STEAM_BUILDID Image label only; set by ci/release.sh +# STEAM_BUILDID Image label; in the stage game-version it keeps the cached result until +# Steam publishes a new build. Set by ci/release.sh # DISABLED_PATCHES Comma-separated simple class names of build-time patches to skip # (debug builds only; ci/release.sh never sets it) @@ -24,8 +29,11 @@ ARG STEAMCLIENT=bundled ARG FORGE_VERSION="0.0.0-prerelease" ARG STEAM_BUILDID="" +# Base images are pinned by digest; the tag in front of the digest is for readers only. +# The same steamcmd image is in ci/steam-buildid.sh and the Gradle plugin's DownloadGame. + # --- Stage 1: vanilla dedicated server ----------------------------------------- -FROM docker.io/steamcmd/steamcmd:debian-13 AS server +FROM docker.io/steamcmd/steamcmd:debian-13@sha256:b0b49ef3101c304ed6e3fbc3ea930b2940d7c489563a1ebac524ad5bb46d336d AS server # steamcmd updates itself on its first run. This runs in its own layer so the # update is cached and separate from the app installation. @@ -36,8 +44,8 @@ ARG STEAMCLIENT COPY docker/install-server.sh /usr/local/bin/install-server 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 +# --- Stage 2: ZomboidForge sources and Gradle ----------------------------------- +FROM docker.io/library/eclipse-temurin:25-jdk@sha256:8c0a84ea11c8f6ed52600fc19f1040121f2a162998e9f50a5faebbbad9172dcc AS sources WORKDIR /src # Gradle distribution download, cached independently of the sources. @@ -53,6 +61,35 @@ COPY agent agent COPY patcher patcher COPY mod-tools mod-tools COPY gradle-plugin gradle-plugin + +# --- Game version of a Steam branch, from its server jar alone ------------------ +# Not part of the image; built on its own by ci/release.sh. +FROM sources AS game-version + +# DepotDownloader downloads single files of a depot; steamcmd only whole apps. +ADD --checksum=sha256:a999dec66b4850fc961bd50366696d23c2d0fad7b18790e6a5647b2f19097a53 \ + https://github.com/SteamRE/DepotDownloader/releases/download/DepotDownloader_3.4.0/DepotDownloader-linux-x64.zip \ + /opt/depotdownloader/depotdownloader.zip +RUN cd /opt/depotdownloader \ + && jar xf depotdownloader.zip \ + && chmod +x DepotDownloader \ + && rm depotdownloader.zip + +# FORGE_VERSION only keeps Gradle from asking git (not in this stage) for the version. +ARG PZ_BRANCH +ARG STEAM_BUILDID +ARG FORGE_VERSION +RUN echo java/projectzomboid.jar > /tmp/files \ + && /opt/depotdownloader/DepotDownloader \ + -app 380870 -depot 380871 -branch "${PZ_BRANCH}" -filelist /tmp/files -dir /pz \ + && ./gradlew --no-daemon --quiet \ + -Ppz.jar=/pz/java/projectzomboid.jar \ + -Pversion=${FORGE_VERSION} \ + :patcher:printGameVersion > /game-version + +# --- Stage 3: ZomboidForge build and server jar patching ----------------------- +FROM sources AS build + COPY --from=server /server/java/projectzomboid.jar /pz/projectzomboid.jar # An empty PZ_VERSION keeps pz.version from gradle.properties. FORGE_VERSION always has a @@ -67,8 +104,8 @@ RUN ./gradlew --no-daemon \ ${DISABLED_PATCHES:+-Pzf.disabledPatches=${DISABLED_PATCHES}} \ build -x :gradle-plugin:test :patcher:patchServerJar -# --- Stage 3: runtime ------------------------------------------------------------ -FROM docker.io/library/debian:trixie-slim +# --- Stage 4: runtime ------------------------------------------------------------ +FROM docker.io/library/debian:trixie-slim@sha256:a99cfc517144bc59b1978475ec53b46ecabec7e43635402ee5b77cc54cd1b20a # ca-certificates: required by steamclient.so to connect to Steam. # sqlite3: the entrypoint checks the admin account in the server database. diff --git a/MOD_DEVELOPMENT.md b/MOD_DEVELOPMENT.md index 4286127..4e45b50 100644 --- a/MOD_DEVELOPMENT.md +++ b/MOD_DEVELOPMENT.md @@ -40,7 +40,7 @@ version = "1.2.0" zomboidForge { id = "shop" entrypoint = "com.example.shop.ShopMod" - game("42.21") // only when the mod uses game classes + game("42") // only when the mod uses game classes dependsOn("economy", "2.1") // other mods: id and minimum version } @@ -69,7 +69,8 @@ game jar for mods that declare `game` versions. Default settings go into | `gameJar` | see below | the `projectzomboid.jar` to compile and check against | | `steamBranch` | `public` | Steam branch for the download: `public`, `unstable`, or a version such as `42.19` | | `serverImage` | the ZomboidForge image, `latest` | image for `runServer` | -| `adminPassword` | `admin` | admin password of the `runServer` server | +| `adminPassword` | random, generated once per volume | admin password of the `runServer` server (see below) | +| `serverAddress` | `127.0.0.1` | host address `runServer` publishes the game ports on; `0.0.0.0` for the network | | `dataVolume` | `zomboidforge-` | volume for the `runServer` world and server config | | `containerEngine` | podman or docker, whichever is installed | for `runServer` and the download | | `deployDirectory` | none | a server's mods directory for `deployMod` | @@ -77,6 +78,10 @@ game jar for mods that declare `game` versions. Default settings go into The plugin generates `META-INF/zomboidforge/mod.toml` from these settings; a hand-written one fails the build. +Declare a minor version in `game(...)` only when the mod needs it. A mod declaring `"42.21"` +stops the server after an update to 42.22, while the server checks every game member a mod uses +against the running jar anyway. + ### The game jar Mods that declare `game` versions compile against `projectzomboid.jar`, which cannot be @@ -100,9 +105,15 @@ The game jar has to be one of the declared `game` versions; the check below fail | `modFolder` | `build/mod//` with `.jar` and `lib/`, as a server expects it in `/mods` | | `modZip` | the same as `build/distributions/-.zip` | | `runServer` | a ZomboidForge server in a container with the mod; Ctrl+C stops it after it saved the world | -| `deployMod` | copies the mod folder into `deployDirectory` | +| `deployMod` | copies the mod folder into `deployDirectory`; keeps the server's `config.toml` of the mod | | `downloadGame` | installs the dedicated server for its game jar; runs only when needed | +`runServer` is reachable from this machine only, unless `serverAddress` says otherwise. Without +`adminPassword`, the first run generates a random admin password for the volume, prints it, and +keeps it in `/zomboidforge/admin-passwords/`. The server uses the +password only when it creates the admin account, on the volume's first start; a later change +needs a new volume (`dataVolume`, or remove the old one). + ### Working on ZomboidForge itself To build a mod against a local ZomboidForge checkout instead of a published version, include it @@ -153,19 +164,21 @@ public final class ShopMod extends Mod Methods of `Mod`, usable from the constructor on (also in field initializers): -| Method | Returns | Use | -|-----------------|-----------------|---------------------------------------------------------------| -| `id()` | `String` | the mod's id from `mod.toml` | -| `version()` | `String` | the mod's version from `mod.toml` | -| `gameVersion()` | `GameVersion` | the running Project Zomboid version | -| `config()` | `ModConfig` | settings from `config.toml`, bound to records or read by path | -| `logger()` | `System.Logger` | messages in the Project Zomboid log, marked with the mod's id | -| `directory()` | `Path` | the mod's folder, `/mods/` | -| `events()` | `Events` | event listeners | -| `main()` | `MainThread` | code that touches game objects | -| `modThread()` | `ModThread` | the mod's own work, one task at a time | -| `async()` | `AsyncExecutor` | blocking work such as HTTP calls or file I/O | -| `storage()` | `ModStorage` | the mod's tables in the world's `zomboidforge.db` | +| Method | Returns | Use | +|--------------------|------------------|---------------------------------------------------------------| +| `id()` | `String` | the mod's id from `mod.toml` | +| `version()` | `String` | the mod's version from `mod.toml` | +| `gameVersion()` | `GameVersion` | the running Project Zomboid version | +| `config()` | `ModConfig` | settings from `config.toml`, bound to records or read by path | +| `logger()` | `System.Logger` | messages in the Project Zomboid log, marked with the mod's id | +| `directory()` | `Path` | the mod's folder, `/mods/` | +| `events()` | `Events` | event listeners | +| `main()` | `MainThread` | code that touches game objects | +| `modThread()` | `ModThread` | the mod's own work, one task at a time | +| `async()` | `AsyncExecutor` | blocking work such as HTTP calls or file I/O | +| `storage()` | `ModStorage` | the mod's tables in the world's `zomboidforge.db` | +| `commands()` | `Commands` | admin commands for chat, the server console, and RCON | +| `clientCommands()` | `ClientCommands` | server commands to clients, received by their Lua mods | ## Threads @@ -199,11 +212,110 @@ Listeners are matched by the event's exact class. Events that carry live game ob removed after ten failures; both `onMain` and `onModThread` return a `Subscription` to remove it earlier. +## Commands + +Admin commands work wherever Project Zomboid's own commands work: in the in-game chat +(`/zfhello`), the server console, and RCON. They use Project Zomboid's command framework, so the +mod declares `game` versions. In Build 42 a command is a subclass of +`zombie.commands.CommandBase`: + +```java +@CommandName(name = "zfhello") +@CommandArgs(optional = "(.+)") +@CommandHelp(helpText = "zfhello [name]: greets", shouldTranslated = false) +@RequiredCapability(requiredCapability = Capability.LoginOnServer) +public class HelloCommand extends CommandBase +{ + public HelloCommand(String username, Role role, String command, UdpConnection connection) { super(username, role, command, connection); } + + @Override + protected String Command() + { + String name = this.getCommandArg(0); + return "Hello " + (name == null ? this.getExecutorUsername() : name); + } +} +``` + +```java +@Override +public void onLoad() { this.commands().register(HelloCommand.class); } +``` + +- **Registration** happens in the entry point's constructor or `onLoad()`; later calls throw. + `register` checks the class and throws `IllegalArgumentException` listing every problem, + which stops the server like any other exception in `onLoad()`. +- **The class** is public and not abstract, with one public constructor + `(String, Role, String, UdpConnection)`. +- **Names** (`@CommandName`, repeatable for aliases) consist of letters, digits, and `_` and + differ, ignoring case, from the names of Project Zomboid's commands and other mods' commands. + A name matches when it is the first word of the input, ignoring case. +- **`@RequiredCapability`** is required: Project Zomboid refuses to run a command without one. + RCON and the server console run commands with the default admin role. +- **`@CommandArgs`** (regular expressions for the arguments; the capture groups become + `getCommandArg(n)`) and **`@CommandHelp`** (`help zfhello` and the `help` list; with + `shouldTranslated = false` the text is used as written) are optional. +- **`Command()`** runs on the main thread, for every use on a new instance; its return value + is the reply. Long work belongs on `modThread()` or `async()`; the reply then only confirms + that the work started. +- Project Zomboid's commands are looked up first; mods' commands follow in load order. + +## Client commands + +A Java mod on the server and a Lua mod on the client (for example from the Workshop) talk +through Project Zomboid's command channel, so players keep the official client. + +Client to server: the Lua mod calls `sendClientCommand`, and the server posts +`ClientCommandEvent` on the main thread. + +```lua +sendClientCommand(getPlayer(), "Shop", "buy", { item = "Base.Axe", count = 2 }) +``` + +```java +this.events().onMain(ClientCommandEvent.class, event -> +{ + if (!event.module().equals("Shop")) return; + event.cancel(); // Lua's OnClientCommand does not see it + + String item = (String) event.args().get("item"); + int count = ((Double) event.args().get("count")).intValue(); + // ... + this.clientCommands().send(event.player(), "Shop", "bought", Map.of("item", item, "count", count)); +}); +``` + +Server to client: `clientCommands().send(player, ...)` and `sendToAll(...)`; the Lua mod +receives them in `Events.OnServerCommand`. + +```lua +Events.OnServerCommand.Add(function(module, command, args) + if module == "Shop" and command == "bought" then print(args.item, args.count) end +end) +``` + +- **Every** client command is posted, including those of Project Zomboid (`vehicle`, + `player`, ...) and of other mods; filter by `module()`. The event is a `MainThreadEvent`. +- **`cancel()`** stops Project Zomboid from passing the command to Lua's `OnClientCommand`. + Every listener still runs; `isCancelled()` tells whether another one cancelled. +- **`args()`** is the Lua table as an unmodifiable map: keys are `String` or `Double` (Lua + arrays have the keys `1.0`, `2.0`, ...); values are `String`, `Double` (every Lua number), + `Boolean`, nested maps, or game objects (inventory items, directions, dead bodies). It is + empty when the client sent no table. +- **`player()`** is a `PlayerRef` (online id and username), a value that stays valid on other + threads and after the player left. Sending to a player who left sends nothing. +- **Sending** works from any thread. The arguments are copied and checked at once + (`IllegalArgumentException` for unsupported types, `null`, or cycles); numbers become Lua + numbers, lists become Lua arrays. The command is sent on the main thread: at once when + called there, otherwise as one of the mod's queued main-thread tasks. +- Client commands come from players and can be forged by a modified client. Check every + argument and the player's rights before acting on it. + ## Storage Mod data belongs in `storage()`: tables in `zomboidforge.db`, a SQLite database in the world's -save folder. Vanilla backups include it, and deleting the world deletes it. Each mod only -reaches its own tables. +save folder. Vanilla backups include it, and deleting the world deletes it. Through the API, +each mod only reaches its own tables. A record declares a table's columns; each row has a `String` key: @@ -216,7 +328,7 @@ balances.set("player1", new Balance(250, Instant.now())); Optional balance = balances.get("player1"); balances.update("player1", old -> new Balance(old.coins() + 10, Instant.now()), () -> new Balance(0, null)); -this.storage().transaction(() -> { // all or nothing +this.storage().transaction(() -> { // all or nothing, also when nested balances.update("player1", old -> new Balance(old.coins() - 5, old.lastPaid()), () -> new Balance(0, null)); balances.update("player2", old -> new Balance(old.coins() + 5, old.lastPaid()), () -> new Balance(0, null)); }); @@ -257,6 +369,10 @@ Things to know: world goes back to its last save, but the mod data keeps later writes. 3. When a mod's id changes, list the old ids in `mod.toml` as `previous_ids`; their tables move to the new id once. +4. While a `transaction`, `update`, or `forEach` callback runs, the storage of every mod waits. + These callbacks must not wait for other threads, for example with + `main().submit(...).join()`. A backup waits at most 10 seconds for them and then runs + without pausing storage, so its copy of `zomboidforge.db` may be incomplete. ## Checks at startup @@ -282,6 +398,11 @@ Every problem of every mod is listed in the log. | game jar (game code and its bundled libraries) | only with `game` declared | | ZomboidForge internals | no | +These rules keep mods from linking against the wrong classes by accident. They are not a +sandbox: a mod runs with the full privileges of the server process. Through reflection or the +file system it can reach anything the server can, including other mods' data in +`zomboidforge.db`. + ## Profiling Main-thread tasks and event listener calls appear in JFR recordings as the event diff --git a/README.md b/README.md index 6aea91c..c6e0de2 100644 --- a/README.md +++ b/README.md @@ -22,8 +22,10 @@ podman build --platform linux/amd64 -t zomboidforge . # or: docker build ... | `FORGE_VERSION` | `0.0.0-prerelease` | ZomboidForge version (jar manifest, image label). The build stage has no `git`, so the version is never read from a tag there; `ci/release.sh` passes it | | `DISABLED_PATCHES` | | Comma-separated simple class names of build-time patches to skip (debug builds only), e.g. `IsoZombieVehiclePerformancePatch` | -Published images are tagged `-pz-build` (immutable), -`-pz`, and `latest`. +Published images are tagged `-pz` (never overwritten), +`-pz` (the newest hotfix of that minor version), and `latest`. A new image +is built for every ZomboidForge release and every Project Zomboid version, hotfixes included: +the server only admits clients with the same version. ## Running @@ -93,6 +95,11 @@ forge/ podman run ... -v ./forge:/forge zomboidforge ``` +Mods are trusted code. They run inside the server process with its full privileges: they can +read and write any file the server can, open network connections, and stop the server. The +class loader isolation and the startup checks catch mistakes; they do not contain a malicious +mod. Install only mods whose authors you trust. + A mod's settings live in its `config.toml`. When the file is missing, it is created from the mod's defaults if the folder is writable by UID 1000; otherwise the defaults are used without a file. Keys missing from `config.toml` take the default. `enabled = false` in its `[forge]` diff --git a/agent/build.gradle.kts b/agent/build.gradle.kts index a22c8b3..41e58d9 100644 --- a/agent/build.gradle.kts +++ b/agent/build.gradle.kts @@ -2,6 +2,7 @@ plugins { id("zomboidforge.java-conventions") + alias(libs.plugins.shadow) } dependencies { @@ -11,12 +12,19 @@ dependencies { compileOnly(files(projectZomboid.serverJar)) } -tasks.jar { - archiveBaseName = "zomboidforge-agent" +// The agent jar is appended to the system class path behind the game jar and includes api, +// core, compat runtime, and their libraries. The libraries are relocated, so a copy of the same +// library in the game jar cannot replace them. +tasks.shadowJar { + archiveBaseName = "zomboidforge-agent" + archiveClassifier = "" 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. - // Mapping the classpath to zip trees loses its task dependencies; the input restores them. - inputs.files(configurations.runtimeClasspath) - from(configurations.runtimeClasspath.map { classpath -> classpath.map { zipTree(it) } }) - duplicatesStrategy = DuplicatesStrategy.EXCLUDE + + relocate("org.objectweb.asm", "dev.overlord.zomboidforge.shaded.asm") + relocate("com.electronwill.nightconfig", "dev.overlord.zomboidforge.shaded.nightconfig") +} + +// Only the shadow jar is used; the plain jar would match the same file name pattern. +tasks.jar { + enabled = false } diff --git a/api/src/main/java/dev/overlord/zomboidforge/api/Cancellable.java b/api/src/main/java/dev/overlord/zomboidforge/api/Cancellable.java new file mode 100644 index 0000000..cd2edcd --- /dev/null +++ b/api/src/main/java/dev/overlord/zomboidforge/api/Cancellable.java @@ -0,0 +1,14 @@ +package dev.overlord.zomboidforge.api; + +/** + * An event whose default action, what Project Zomboid does after the event, can be prevented. + * Only listeners on the main thread can cancel: the default action runs once every main-thread + * listener returned. Every listener is called, also after one cancelled. + */ +public interface Cancellable +{ + /** Prevents the default action. */ + void cancel(); + + boolean isCancelled(); +} diff --git a/api/src/main/java/dev/overlord/zomboidforge/api/ClientCommandEvent.java b/api/src/main/java/dev/overlord/zomboidforge/api/ClientCommandEvent.java new file mode 100644 index 0000000..78f40d3 --- /dev/null +++ b/api/src/main/java/dev/overlord/zomboidforge/api/ClientCommandEvent.java @@ -0,0 +1,55 @@ +package dev.overlord.zomboidforge.api; + +import java.util.Map; +import java.util.Objects; + +/** + * A client command arrived: a client called Lua's {@code sendClientCommand(module, command, args)}. + * Posted on the main thread for every client command, including those of Project Zomboid and of + * Lua mods, so listeners filter by {@link #module()}. + * + *

Default action: Project Zomboid passes the command to Lua's {@code Events.OnClientCommand}. + * {@link #cancel()} prevents that, for example when a Java mod handles the module itself. + * + *

{@link #args()} is the Lua table converted to Java: keys are {@code String} or + * {@code Double} (Lua arrays have the keys {@code 1.0}, {@code 2.0}, ...), values are + * {@code String}, {@code Double}, {@code Boolean}, a nested {@code Map} of the same kind, or a + * game object that Project Zomboid sends with commands (in Build 42 an inventory item, an + * {@code IsoDirections}, or a dead body). The maps cannot be modified. + */ +public final class ClientCommandEvent implements MainThreadEvent, Cancellable +{ + private final PlayerRef player; + private final String module; + private final String command; + private final Map args; + + private boolean cancelled; + + /** @param args the converted arguments; empty when the client sent none */ + public ClientCommandEvent(PlayerRef player, String module, String command, Map args) + { + this.player = Objects.requireNonNull(player, "player"); + this.module = Objects.requireNonNull(module, "module"); + this.command = Objects.requireNonNull(command, "command"); + this.args = Objects.requireNonNull(args, "args"); + } + + /** The player who sent the command. */ + public PlayerRef player() { return this.player; } + + public String module() { return this.module; } + + public String command() { return this.command; } + + public Map args() { return this.args; } + + @Override + public void cancel() { this.cancelled = true; } + + @Override + public boolean isCancelled() { return this.cancelled; } + + @Override + public String toString() { return "ClientCommandEvent[" + this.player + ", " + this.module + "." + this.command + ", " + this.args + (this.cancelled ? ", cancelled" : "") + "]"; } +} diff --git a/api/src/main/java/dev/overlord/zomboidforge/api/ClientCommands.java b/api/src/main/java/dev/overlord/zomboidforge/api/ClientCommands.java new file mode 100644 index 0000000..4264e62 --- /dev/null +++ b/api/src/main/java/dev/overlord/zomboidforge/api/ClientCommands.java @@ -0,0 +1,35 @@ +package dev.overlord.zomboidforge.api; + +import java.util.Map; + +/** + * Server commands to clients, the reply channel to {@link ClientCommandEvent}: a client receives + * them in Lua's {@code Events.OnServerCommand(module, command, args)}. Together, a Java mod on the + * server and a Lua mod on the client exchange commands while players keep the official client. + * + *

{@code args} becomes a Lua table: keys are {@code String} or a {@code Number} (sent as a + * Lua number), values are {@code String}, {@code Number}, {@code Boolean}, a nested {@code Map}, a + * {@code List} (a Lua array, indexed from 1), or a game object that Project Zomboid sends with + * commands (see {@link ClientCommandEvent}). {@code null} keys or values, and cycles, are not + * allowed. An empty map sends no arguments; the client then receives {@code nil}. + * + *

The methods can be called on any thread. The arguments are checked at once; the command is + * sent on the main thread, at once when called there, otherwise with the mod's queued + * main-thread tasks. + */ +public interface ClientCommands +{ + /** + * Sends a command to {@code player}. Nothing is sent when the player is no longer connected. + * + * @throws IllegalArgumentException when {@code args} contains a key or value that cannot be sent + */ + void send(PlayerRef player, String module, String command, Map args); + + /** + * Sends a command to every connected client. + * + * @throws IllegalArgumentException when {@code args} contains a key or value that cannot be sent + */ + void sendToAll(String module, String command, Map args); +} diff --git a/api/src/main/java/dev/overlord/zomboidforge/api/Commands.java b/api/src/main/java/dev/overlord/zomboidforge/api/Commands.java new file mode 100644 index 0000000..e402c87 --- /dev/null +++ b/api/src/main/java/dev/overlord/zomboidforge/api/Commands.java @@ -0,0 +1,35 @@ +package dev.overlord.zomboidforge.api; + +/** + * Registration of admin commands. A registered command works wherever Project Zomboid's own + * admin commands work: in the in-game chat ({@code /name}), the server console, and RCON. It + * is looked up after the commands of Project Zomboid and runs on the main thread. + * + *

A command is a class of the running Project Zomboid version's command framework, so a mod + * that registers commands declares {@code game} versions in {@code mod.toml}. In Build 42 it is + * a public, non-abstract subclass of {@code zombie.commands.CommandBase} with: + *

    + *
  • one public constructor {@code (String username, Role role, String command, UdpConnection connection)}, + * which passes its arguments to {@code super};
  • + *
  • at least one {@code @CommandName}; names consist of letters, digits, and {@code _}, and + * differ (ignoring case) from every name of Project Zomboid and of other mods;
  • + *
  • at least one {@code @RequiredCapability}; Project Zomboid refuses to run a command + * without one;
  • + *
  • optionally {@code @CommandArgs} (argument patterns) and {@code @CommandHelp} + * ({@code help } and the {@code help} list).
  • + *
+ * Project Zomboid creates a new instance for every use and calls its {@code Command()}, whose + * result is the reply. + */ +public interface Commands +{ + /** + * Registers {@code command}. Only on the main thread while the mod loads: in the entry point's + * constructor or {@link Mod#onLoad()}. + * + * @throws IllegalArgumentException when {@code command} does not meet the rules above, or is + * registered already + * @throws IllegalStateException when called later or on another thread + */ + void register(Class command); +} diff --git a/api/src/main/java/dev/overlord/zomboidforge/api/GameVersion.java b/api/src/main/java/dev/overlord/zomboidforge/api/GameVersion.java index d279290..b826159 100644 --- a/api/src/main/java/dev/overlord/zomboidforge/api/GameVersion.java +++ b/api/src/main/java/dev/overlord/zomboidforge/api/GameVersion.java @@ -9,8 +9,9 @@ import java.util.regex.Pattern; /** Project Zomboid version, e.g. 42.21.0 ({@code Core.getGameAndBuildVersion()}). */ public record GameVersion(int major, int minor, int build) implements Comparable { - private static final Pattern VERSION = Pattern.compile("(\\d+)\\.(\\d+)(?:\\.(\\d+))?"); - private static final Pattern PREFIX = Pattern.compile("(\\d+)(?:\\.(\\d+)(?:\\.(\\d+))?)?"); + // At most 9 digits per number, so every number fits an int. + private static final Pattern VERSION = Pattern.compile("(\\d{1,9})\\.(\\d{1,9})(?:\\.(\\d{1,9}))?"); + private static final Pattern PREFIX = Pattern.compile("(\\d{1,9})(?:\\.(\\d{1,9})(?:\\.(\\d{1,9}))?)?"); private static final Comparator ORDER = Comparator .comparingInt(GameVersion::major) diff --git a/api/src/main/java/dev/overlord/zomboidforge/api/Mod.java b/api/src/main/java/dev/overlord/zomboidforge/api/Mod.java index 1190d9d..d5666f5 100644 --- a/api/src/main/java/dev/overlord/zomboidforge/api/Mod.java +++ b/api/src/main/java/dev/overlord/zomboidforge/api/Mod.java @@ -84,4 +84,10 @@ public abstract class Mod /** The mod's tables in the world's {@code zomboidforge.db}; not on the main thread once the server runs. */ protected final ModStorage storage() { return this.context.storage(); } + + /** Admin command registration. */ + protected final Commands commands() { return this.context.commands(); } + + /** Server commands to clients, received by their Lua mods. */ + protected final ClientCommands clientCommands() { return this.context.clientCommands(); } } diff --git a/api/src/main/java/dev/overlord/zomboidforge/api/ModContext.java b/api/src/main/java/dev/overlord/zomboidforge/api/ModContext.java index 5efd9ca..5f03a8c 100644 --- a/api/src/main/java/dev/overlord/zomboidforge/api/ModContext.java +++ b/api/src/main/java/dev/overlord/zomboidforge/api/ModContext.java @@ -42,4 +42,10 @@ public interface ModContext /** The mod's tables in the world's {@code zomboidforge.db}. */ ModStorage storage(); + + /** Admin command registration. */ + Commands commands(); + + /** Server commands to clients, received by their Lua mods. */ + ClientCommands clientCommands(); } diff --git a/api/src/main/java/dev/overlord/zomboidforge/api/PlayerRef.java b/api/src/main/java/dev/overlord/zomboidforge/api/PlayerRef.java new file mode 100644 index 0000000..e17cac5 --- /dev/null +++ b/api/src/main/java/dev/overlord/zomboidforge/api/PlayerRef.java @@ -0,0 +1,19 @@ +package dev.overlord.zomboidforge.api; + +import java.util.Objects; + +/** + * A connected player, by value: usable on any thread and after the player left. Project + * Zomboid reuses online ids of players who left, so ZomboidForge matches both the id and the + * username before it acts on a player. + * + * @param onlineId the player's online id while connected + * @param username the player's account name + */ +public record PlayerRef(int onlineId, String username) +{ + public PlayerRef + { + Objects.requireNonNull(username, "username"); + } +} diff --git a/api/src/main/java/dev/overlord/zomboidforge/api/storage/ModStorage.java b/api/src/main/java/dev/overlord/zomboidforge/api/storage/ModStorage.java index e077816..41bb28f 100644 --- a/api/src/main/java/dev/overlord/zomboidforge/api/storage/ModStorage.java +++ b/api/src/main/java/dev/overlord/zomboidforge/api/storage/ModStorage.java @@ -4,7 +4,8 @@ import java.util.function.Supplier; /** * The mod's tables in {@code zomboidforge.db}, next to the world's save. Every table belongs to - * the mod; other mods cannot reach it. + * the mod; this interface gives no access to the tables of other mods. It is not a security + * boundary: mod code runs with the server's privileges and can open the file directly. * *

A record declares a table's columns: {@code String}, {@code long}/{@code int}, * {@code double}/{@code float}, {@code boolean}, {@code byte[]}, {@code UUID}, {@code Instant}, @@ -26,6 +27,10 @@ public interface ModStorage /** * Runs {@code work} in one transaction: writes of this thread inside it are committed * together, or not at all when {@code work} throws. + * + *

Storage of every mod waits while {@code work} runs, so {@code work} must not wait for + * other threads, for example with {@code main().submit(...).join()}. A backup waits at most + * 10 seconds for it and then runs without pausing storage. */ void transaction(Runnable work); diff --git a/api/src/main/java/dev/overlord/zomboidforge/api/storage/Table.java b/api/src/main/java/dev/overlord/zomboidforge/api/storage/Table.java index 7064082..077afcc 100644 --- a/api/src/main/java/dev/overlord/zomboidforge/api/storage/Table.java +++ b/api/src/main/java/dev/overlord/zomboidforge/api/storage/Table.java @@ -37,7 +37,11 @@ public interface Table /** Every key, sorted. */ List keys(); - /** Calls {@code action} for every row, sorted by key, without loading all rows at once. */ + /** + * Calls {@code action} for every row, sorted by key, without loading all rows at once. + * Storage of every mod waits until it returns, so {@code action} must not wait for other + * threads. + */ void forEach(BiConsumer action); long count(); @@ -45,6 +49,8 @@ public interface Table /** * Replaces the row under {@code key} with {@code change} applied to it, or to * {@code initial} when there is none, in one transaction: no other write comes in between. + * As in {@link ModStorage#transaction}, {@code change} and {@code initial} must not wait for + * other threads. * * @return the stored value */ diff --git a/api/src/test/java/dev/overlord/zomboidforge/api/GameVersionTest.java b/api/src/test/java/dev/overlord/zomboidforge/api/GameVersionTest.java index 5a383d4..50c3c4d 100644 --- a/api/src/test/java/dev/overlord/zomboidforge/api/GameVersionTest.java +++ b/api/src/test/java/dev/overlord/zomboidforge/api/GameVersionTest.java @@ -42,6 +42,16 @@ class GameVersionTest assertThrows(IllegalArgumentException.class, () -> version.matches("42.21.3.1")); } + @Test + void rejectsNumbersOutsideTheIntRange() + { + GameVersion version = new GameVersion(42, 21, 3); + + assertThrows(IllegalArgumentException.class, () -> GameVersion.parse("42.99999999999")); + assertThrows(IllegalArgumentException.class, () -> version.matches("99999999999")); + assertFalse(GameVersion.isPrefix("42.99999999999")); + } + @Test void comparesNumerically() { diff --git a/ci/publish.sh b/ci/publish.sh index ea9bc6d..dd76600 100755 --- a/ci/publish.sh +++ b/ci/publish.sh @@ -2,15 +2,18 @@ # # Publishes the mod API (dev.overlord.zomboidforge:api), the mod tools (mod-tools), and the # Gradle plugin (dev.overlord.zomboidforge.mod) to the Maven registry of the ZomboidForge Gitea, -# in the version of the newest v* git tag reachable from HEAD, without the "v". +# in the version of the v* git tag on HEAD, without the "v". # # A pre-release version (containing "-", e.g. 0.3.0-rc.1) is built and tested but never -# published. Without any v* tag nothing is published. +# published. Without a v* tag on HEAD nothing is published. # -# Environment: +# Usage: +# ci/publish.sh test runs the checks of the published modules; needs no credentials +# ci/publish.sh publish publishes them without running the checks again +# +# Environment (publish only): # ORG_GRADLE_PROJECT_giteaUsername Gitea user with package write access # ORG_GRADLE_PROJECT_giteaPassword Token of that user -# PUBLISH true: publish after the tests. Default: false (test only) set -o errexit set -o nounset @@ -19,8 +22,6 @@ set -o pipefail REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" readonly REPO_ROOT -readonly REQUESTED_PUBLISH="${PUBLISH:-false}" - readonly MODULES=( api mod-tools @@ -31,11 +32,11 @@ log() { echo "[publish] $*" >&2 } -# Prints the newest v* tag reachable from HEAD without its "v", or nothing. +# Prints the v* tag on HEAD without its "v", or nothing. release_tag_version() { local tag - if tag="$(git -C "${REPO_ROOT}" describe --tags --abbrev=0 --match 'v*' 2> /dev/null)"; then + if tag="$(git -C "${REPO_ROOT}" describe --tags --exact-match --match 'v*' 2> /dev/null)"; then echo "${tag#v}" fi } @@ -61,36 +62,54 @@ run_gradle() { "$@" } -main() { - local version - local publish="${REQUESTED_PUBLISH}" +run_tests() { + local version="$1" local check_tasks - local publish_tasks - - version="$(release_tag_version)" - if [[ -z "${version}" ]]; then - log "No v* git tag found (shallow clone without tags?); nothing to publish." - exit 1 - fi - if [[ "${version}" == *-* ]]; then - publish=false - log "${version} is a pre-release version; nothing will be published." - fi mapfile -t check_tasks < <(module_tasks check) - mapfile -t publish_tasks < <(module_tasks publishAllPublicationsToGiteaRepository) log "Testing ZomboidForge ${version}: ${MODULES[*]}" run_gradle "${version}" :core:check "${check_tasks[@]}" +} - if [[ "${publish}" != "true" ]]; then - log "Not publishing (PUBLISH=${REQUESTED_PUBLISH})." +publish() { + local version="$1" + local publish_tasks + + if [[ "${version}" == *-* ]]; then + log "${version} is a pre-release version; nothing is published." return fi + mapfile -t publish_tasks < <(module_tasks publishAllPublicationsToGiteaRepository) + log "Publishing ZomboidForge ${version}" run_gradle "${version}" "${publish_tasks[@]}" log "Published ${MODULES[*]} ${version}" } +main() { + local step="${1:-}" + local version + + version="$(release_tag_version)" + if [[ -z "${version}" ]]; then + log "HEAD has no v* git tag (not a release commit, or a shallow clone without tags?); nothing to publish." + exit 1 + fi + + case "${step}" in + test) + run_tests "${version}" + ;; + publish) + publish "${version}" + ;; + *) + log "Usage: ci/publish.sh test|publish" + exit 2 + ;; + esac +} + main "$@" diff --git a/ci/release.sh b/ci/release.sh index bed1f85..59b926c 100755 --- a/ci/release.sh +++ b/ci/release.sh @@ -1,22 +1,29 @@ #!/usr/bin/env bash # -# Builds the ZomboidForge image for one Project Zomboid version and optionally +# Builds the ZomboidForge image for the current build of a Steam branch 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 +# -pz written once per ZomboidForge and Project Zomboid version +# -pz moves to the newest hotfix of that minor version +# latest only with LATEST=true # -# is the newest v* git tag reachable from HEAD, without the "v" (v0.2.0 -> 0.2.0). -# A pre-release version (containing "-", e.g. 0.2.0-rc.1) is built and verified but never -# published. Without any v* tag the version is "0.0.0-prerelease". +# is the version the branch's server jar reports, read before the full +# build (Dockerfile stage game-version, which downloads only the jar). # -# Nothing is built when the immutable tag already exists in the registry. +# is the v* git tag on HEAD, without the "v" (v0.2.0 -> 0.2.0). When HEAD has no such +# tag, it is the git describe version of HEAD (0.2.0-3-g1a2b3c4: 3 commits after v0.2.0). +# A pre-release version (containing "-", e.g. 0.2.0-rc.1 or 0.2.0-3-g1a2b3c4) is built and +# verified but never published. Without any v* tag the version is "0.0.0-prerelease". +# +# Nothing is built when -pz already exists in the registry. The +# server only admits clients with the same major.minor.build, so every hotfix (42.21.1 -> +# 42.21.2) gets an image; a new Steam build with an unchanged version does not. # # 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 +# PZ_VERSION Accepted Project Zomboid versions ("42": every Build 42 version). +# Default: pz.version in gradle.properties # PUBLISH true: push the tags (not for pre-release versions). Default: false (build and verify only) # LATEST true: also push "latest". Default: false # CONTAINER_ENGINE docker or podman. Default: docker if installed, else podman @@ -63,12 +70,15 @@ gradle_property() { exit 1 } -# Prints the forge version: the newest v* tag reachable from HEAD without its "v", -# or nothing when the repository has no such tag. +# Prints the forge version without the "v": the v* tag on HEAD, else the git describe version +# of HEAD relative to the newest reachable v* tag (v0.2.0-3-g1a2b3c4), or nothing when the +# repository has no such tag. release_tag_version() { local tag - if tag="$(git -C "${REPO_ROOT}" describe --tags --abbrev=0 --match 'v*' 2> /dev/null)"; then + if tag="$(git -C "${REPO_ROOT}" describe --tags --exact-match --match 'v*' 2> /dev/null)"; then + echo "${tag#v}" + elif tag="$(git -C "${REPO_ROOT}" describe --tags --match 'v*' 2> /dev/null)"; then echo "${tag#v}" fi } @@ -78,6 +88,22 @@ image_exists() { "$(container_engine)" manifest inspect "${reference}" > /dev/null 2>&1 } +# Prints the game version of the branch's current server jar, e.g. 42.21.0. Downloads only +# the jar; the result stays cached until the build ID changes. +read_game_version() { + local build_id="$1" + local image + + image="$("$(container_engine)" build --quiet \ + --platform linux/amd64 \ + --target game-version \ + --build-arg "PZ_BRANCH=${PZ_BRANCH}" \ + --build-arg "STEAM_BUILDID=${build_id}" \ + "${REPO_ROOT}")" + + "$(container_engine)" run --rm --entrypoint cat "${image}" /game-version +} + build_image() { local reference="$1" local forge_version="$2" @@ -119,8 +145,9 @@ push_as() { main() { local forge_version local publish="${REQUESTED_PUBLISH}" - local pz_version + local pz_prefix local build_id + local game_version forge_version="$(release_tag_version)" if [[ -z "${forge_version}" ]]; then @@ -132,31 +159,39 @@ main() { log "${forge_version} is a pre-release version; nothing will be published." fi - pz_version="${PZ_VERSION:-$(gradle_property pz.version)}" + pz_prefix="${PZ_VERSION:-$(gradle_property pz.version)}" build_id="$("${REPO_ROOT}/ci/steam-buildid.sh" "${PZ_BRANCH}")" + game_version="$(read_game_version "${build_id}")" + log "ZomboidForge ${forge_version}, Project Zomboid ${game_version}, Steam branch ${PZ_BRANCH} build ${build_id}" - 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}" + # Checked here as well as by the patcher, to fail before the full download. + if [[ "${game_version}" != "${pz_prefix}" && "${game_version}" != "${pz_prefix}."* ]]; then + log "Steam branch ${PZ_BRANCH} has Project Zomboid ${game_version}; the build accepts ${pz_prefix}." + exit 1 + fi - if [[ "${publish}" == true ]] && image_exists "${immutable_tag}"; then - log "${immutable_tag} is already published; nothing to do." + local version_tag="${IMAGE}:${forge_version}-pz${game_version}" + # 42.21.2 -> 42.21 + local minor_tag="${IMAGE}:${forge_version}-pz${game_version%.*}" + + if [[ "${publish}" == true ]] && image_exists "${version_tag}"; then + log "${version_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}" + build_image "${version_tag}" "${forge_version}" "${game_version}" "${build_id}" + verify_build_id "${version_tag}" "${build_id}" if [[ "${publish}" != true ]]; then - log "Built ${immutable_tag} (not published)" + log "Built ${version_tag} (not published)" return fi - "$(container_engine)" push "${immutable_tag}" - log "Pushed ${immutable_tag}" - push_as "${immutable_tag}" "${version_tag}" + "$(container_engine)" push "${version_tag}" + log "Pushed ${version_tag}" + push_as "${version_tag}" "${minor_tag}" if [[ "${LATEST}" == true ]]; then - push_as "${immutable_tag}" "${IMAGE}:latest" + push_as "${version_tag}" "${IMAGE}:latest" fi } diff --git a/ci/steam-buildid.sh b/ci/steam-buildid.sh index 35b7656..5efa38c 100755 --- a/ci/steam-buildid.sh +++ b/ci/steam-buildid.sh @@ -14,7 +14,7 @@ set -o nounset set -o pipefail readonly APP_ID="380870" -readonly STEAMCMD_IMAGE="docker.io/steamcmd/steamcmd:debian-13" +readonly STEAMCMD_IMAGE="docker.io/steamcmd/steamcmd:debian-13@sha256:b0b49ef3101c304ed6e3fbc3ea930b2940d7c489563a1ebac524ad5bb46d336d" readonly BRANCH="$1" diff --git a/compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/B42PatchSet.java b/compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/B42PatchSet.java index 2ee7f65..c28494a 100644 --- a/compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/B42PatchSet.java +++ b/compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/B42PatchSet.java @@ -18,6 +18,9 @@ public final class B42PatchSet implements PatchSet new ServerTickPatch(), new ServerStoppingPatch(), new BackupStoragePatch(), + new CommandLookupPatch(), + new CommandListPatch(), + new ClientCommandPatch(), new IsoZombieVehiclePerformancePatch(), new IsoZombieNetworkComponentPerformancePatch(), new IsoZombieSpotChancePerformancePatch(), diff --git a/compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/patches/ClientCommandPatch.java b/compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/patches/ClientCommandPatch.java new file mode 100644 index 0000000..efa039d --- /dev/null +++ b/compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/patches/ClientCommandPatch.java @@ -0,0 +1,43 @@ +package dev.overlord.zomboidforge.compat.b42.patches; + +import dev.overlord.zomboidforge.patcher.Anchor; +import dev.overlord.zomboidforge.patcher.Hook; +import dev.overlord.zomboidforge.patcher.HookArgument; +import dev.overlord.zomboidforge.patcher.Patches.CancellableHookPatch; + +import java.util.List; + +/** + * Makes the Lua event {@code OnClientCommand} in {@code GameServer.receiveClientCommand} depend on + * {@code ClientCommandHooks.onClientCommand(module, command, player, tbl)}: + * + *

{@code
+ * if (!ClientCommandHooks.onClientCommand(module, command, player, tbl))
+ *     LuaEventManager.triggerEvent("OnClientCommand", module, command, player, tbl);
+ * }
+ * + * The arguments are the method's local variables of these names. + */ +public final class ClientCommandPatch extends CancellableHookPatch +{ + private static final Anchor.Call ANCHOR = new Anchor.Call( + new Anchor.Method("receiveClientCommand", "(Lzombie/core/network/ByteBufferReader;Lzombie/core/raknet/UdpConnection;S)V"), + "zombie/Lua/LuaEventManager", "triggerEvent", "(Ljava/lang/String;Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;)V" + ); + + private static final Hook HOOK = new Hook( + "dev/overlord/zomboidforge/compat/b42/hooks/ClientCommandHooks", "onClientCommand", + "(Ljava/lang/String;Ljava/lang/String;Lzombie/characters/IsoPlayer;Lse/krka/kahlua/vm/KahluaTable;)Z" + ); + + private static final List ARGUMENTS = List.of( + new HookArgument.Local("module"), + new HookArgument.Local("command"), + new HookArgument.Local("player"), + new HookArgument.Local("tbl") + ); + + public ClientCommandPatch() { + super("zombie/network/GameServer", ClientCommandPatch.ANCHOR, ClientCommandPatch.HOOK, ClientCommandPatch.ARGUMENTS); + } +} diff --git a/compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/patches/CommandListPatch.java b/compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/patches/CommandListPatch.java new file mode 100644 index 0000000..d4f750a --- /dev/null +++ b/compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/patches/CommandListPatch.java @@ -0,0 +1,32 @@ +package dev.overlord.zomboidforge.compat.b42.patches; + +import dev.overlord.zomboidforge.patcher.Anchor; +import dev.overlord.zomboidforge.patcher.Hook; +import dev.overlord.zomboidforge.patcher.Patches.ReturnHookPatch; + +import org.objectweb.asm.Opcodes; + +import java.util.List; + +/** + * Makes {@code CommandBase.getSubClasses()} return + * {@code CommandHooks.listCommands(childrenClasses)}: Project Zomboid's command classes followed + * by the mods'. The {@code help} command lists commands through this method. + */ +public final class CommandListPatch extends ReturnHookPatch +{ + /** The whole method: {@code getstatic childrenClasses}, {@code areturn}. */ + private static final Anchor.Sequence ANCHOR = new Anchor.Sequence( + new Anchor.Method("getSubClasses", "()[Ljava/lang/Class;"), + new Anchor.Instruction.Opcode(Opcodes.GETSTATIC), + new Anchor.Instruction.Opcode(Opcodes.ARETURN) + ); + + private static final Hook HOOK = new Hook( + "dev/overlord/zomboidforge/compat/b42/hooks/CommandHooks", "listCommands", "([Ljava/lang/Class;)[Ljava/lang/Class;" + ); + + public CommandListPatch() { + super("zombie/commands/CommandBase", CommandListPatch.ANCHOR, CommandListPatch.HOOK, List.of()); + } +} diff --git a/compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/patches/CommandLookupPatch.java b/compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/patches/CommandLookupPatch.java new file mode 100644 index 0000000..be4d659 --- /dev/null +++ b/compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/patches/CommandLookupPatch.java @@ -0,0 +1,33 @@ +package dev.overlord.zomboidforge.compat.b42.patches; + +import dev.overlord.zomboidforge.patcher.Anchor; +import dev.overlord.zomboidforge.patcher.Hook; +import dev.overlord.zomboidforge.patcher.HookArgument; +import dev.overlord.zomboidforge.patcher.Patches.ReturnHookPatch; + +import org.objectweb.asm.Opcodes; + +import java.util.List; + +/** + * Makes {@code CommandBase.findCommandCls(command)} return + * {@code CommandHooks.findCommand(null, command)} where it returns {@code null}: when no command + * of Project Zomboid matches, the mods' commands are searched. The server console, RCON, chat + * commands, and {@code help } look commands up through this method. + */ +public final class CommandLookupPatch extends ReturnHookPatch +{ + private static final Anchor.Sequence ANCHOR = new Anchor.Sequence( + new Anchor.Method("findCommandCls", "(Ljava/lang/String;)Ljava/lang/Class;"), + new Anchor.Instruction.Opcode(Opcodes.ACONST_NULL), + new Anchor.Instruction.Opcode(Opcodes.ARETURN) + ); + + private static final Hook HOOK = new Hook( + "dev/overlord/zomboidforge/compat/b42/hooks/CommandHooks", "findCommand", "(Ljava/lang/Class;Ljava/lang/String;)Ljava/lang/Class;" + ); + + public CommandLookupPatch() { + super("zombie/commands/CommandBase", CommandLookupPatch.ANCHOR, CommandLookupPatch.HOOK, List.of(new HookArgument.Parameter(0))); + } +} diff --git a/compat/b42/runtime/build.gradle.kts b/compat/b42/runtime/build.gradle.kts index 42937d1..10dcb47 100644 --- a/compat/b42/runtime/build.gradle.kts +++ b/compat/b42/runtime/build.gradle.kts @@ -10,6 +10,8 @@ dependencies { implementation(project(":api")) compileOnly(files(projectZomboid.serverJar)) + // ModCommandsTest checks command classes against the game's command framework. + testImplementation(files(projectZomboid.serverJar)) testImplementation(platform(libs.junit.bom)) testImplementation(libs.junit.jupiter) testRuntimeOnly(libs.junit.platform.launcher) diff --git a/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/ForgeInstance.java b/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/ForgeInstance.java index fd6ee55..f9b5960 100644 --- a/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/ForgeInstance.java +++ b/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/ForgeInstance.java @@ -1,11 +1,15 @@ package dev.overlord.zomboidforge.compat.b42; +import dev.overlord.zomboidforge.compat.b42.commands.ClientCommandChannel; +import dev.overlord.zomboidforge.compat.b42.commands.ModCommands; import dev.overlord.zomboidforge.core.Forge; /** The one {@link Forge} of the server, shared by the hook classes. */ public final class ForgeInstance { - public static final Forge FORGE = Forge.fromSystemProperties(); + public static final Forge FORGE = Forge.fromSystemProperties( + ModCommands::check, ClientCommandChannel::prepare + ); private ForgeInstance() {} } diff --git a/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/commands/ClientCommandChannel.java b/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/commands/ClientCommandChannel.java new file mode 100644 index 0000000..2d71720 --- /dev/null +++ b/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/commands/ClientCommandChannel.java @@ -0,0 +1,55 @@ +package dev.overlord.zomboidforge.compat.b42.commands; + +import dev.overlord.zomboidforge.api.PlayerRef; + +import org.jetbrains.annotations.Nullable; + +import se.krka.kahlua.vm.KahluaTable; + +import zombie.Lua.LuaManager; +import zombie.characters.IsoPlayer; +import zombie.network.GameServer; + +import java.util.Map; + +/** Client commands in Build 42: players as {@link PlayerRef}s, and server commands to clients. */ +public final class ClientCommandChannel +{ + private ClientCommandChannel() {} + + public static PlayerRef ref(IsoPlayer player) { return new PlayerRef(player.getOnlineID(), player.getUsername()); } + + /** + * Copies {@code args} at once and returns the action that sends the command with + * {@code GameServer.sendServerCommand}, to every connection when {@code player} is + * {@code null}. The action runs on the main thread and sends nothing when the player is no + * longer connected. + * + * @throws IllegalArgumentException naming a key or value that cannot be sent + */ + public static Runnable prepare(@Nullable PlayerRef player, String module, String command, Map args) + { + Map copy = LuaTables.copy(args); + + return () -> + { + KahluaTable table = copy.isEmpty() ? null : LuaTables.toLua(copy, LuaManager.platform::newTable); + + if (player == null) { + GameServer.sendServerCommand(module, command, table); + return; + } + + IsoPlayer target = ClientCommandChannel.find(player); + if (target != null) GameServer.sendServerCommand(target, module, command, table); + }; + } + + /** The connected player with the online id and the username of {@code player}, or {@code null}. Main thread. */ + private static @Nullable IsoPlayer find(PlayerRef player) + { + Object connected = GameServer.IDToPlayerMap.get((short) player.onlineId()); + + return connected instanceof IsoPlayer target && player.username().equals(target.getUsername()) ? target : null; + } +} diff --git a/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/commands/LuaTables.java b/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/commands/LuaTables.java new file mode 100644 index 0000000..1aed19c --- /dev/null +++ b/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/commands/LuaTables.java @@ -0,0 +1,134 @@ +package dev.overlord.zomboidforge.compat.b42.commands; + +import org.jetbrains.annotations.Nullable; + +import se.krka.kahlua.vm.KahluaTable; +import se.krka.kahlua.vm.KahluaTableIterator; + +import zombie.inventory.InventoryItem; +import zombie.iso.IsoDirections; +import zombie.iso.objects.IsoDeadBody; + +import java.util.Collections; +import java.util.IdentityHashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.function.Supplier; + +/** + * Conversion between the Kahlua tables of command arguments and the Java maps of the API. The + * types are those {@code TableNetworkUtils} sends: {@code String} and {@code Double} keys; + * {@code String}, {@code Double}, {@code Boolean}, table, {@code InventoryItem}, + * {@code IsoDirections}, and {@code IsoDeadBody} values. + */ +public final class LuaTables +{ + private LuaTables() {} + + /** {@code table} as an unmodifiable map, nested tables as nested maps; empty for {@code null}. */ + public static Map toJava(@Nullable KahluaTable table) + { + if (table == null) return Map.of(); + + Map map = new LinkedHashMap<>(); + KahluaTableIterator iterator = table.iterator(); + + while (iterator.advance()) + { + Object value = iterator.getValue(); + map.put(iterator.getKey(), value instanceof KahluaTable nested ? LuaTables.toJava(nested) : value); + } + + return Collections.unmodifiableMap(map); + } + + /** + * A deep, unmodifiable copy of {@code args} in Lua's types: number keys and values become + * {@code Double}, lists become maps with the keys {@code 1.0}, {@code 2.0}, .... + * + * @throws IllegalArgumentException naming the first key or value that cannot be sent, or a + * map or list that contains itself + */ + public static Map copy(Map args) { return LuaTables.copy(args, "args", Collections.newSetFromMap(new IdentityHashMap<>())); } + + /** A new table with the entries of {@code args}, a result of {@link #copy}; nested maps become nested tables. */ + public static KahluaTable toLua(Map args, Supplier newTable) + { + KahluaTable table = newTable.get(); + + for (Map.Entry entry : args.entrySet()) + { + Object value = entry.getValue(); + + @SuppressWarnings("unchecked") + Object luaValue = value instanceof Map nested ? LuaTables.toLua((Map) nested, newTable) : value; + + table.rawset(entry.getKey(), luaValue); + } + + return table; + } + + private static Map copy(Map map, String path, Set open) + { + if (!open.add(map)) throw new IllegalArgumentException("'" + path + "' contains itself."); + + Map copy = new LinkedHashMap<>(); + + for (Map.Entry entry : map.entrySet()) + { + Object key = LuaTables.key(entry.getKey(), path); + String here = path + "[" + key + "]"; + + copy.put(key, LuaTables.value(entry.getValue(), here, open)); + } + + open.remove(map); + + return Collections.unmodifiableMap(copy); + } + + private static Map copy(List list, String path, Set open) + { + if (!open.add(list)) throw new IllegalArgumentException("'" + path + "' contains itself."); + + Map copy = new LinkedHashMap<>(); + + for (int i = 0; i < list.size(); i++) copy.put((double) (i + 1), LuaTables.value(list.get(i), path + "[" + (i + 1) + "]", open)); + + open.remove(list); + + return Collections.unmodifiableMap(copy); + } + + private static Object key(@Nullable Object key, String path) + { + if (key instanceof String) return key; + if (key instanceof Number number) return number.doubleValue(); + + throw new IllegalArgumentException("'" + path + "' has the key '" + key + "'" + LuaTables.typeOf(key) + "; keys are strings or numbers."); + } + + private static Object value(@Nullable Object value, String path, Set open) + { + return switch (value) + { + case String string -> string; + case Boolean bool -> bool; + case Number number -> number.doubleValue(); + case Map map -> LuaTables.copy(map, path, open); + case List list -> LuaTables.copy(list, path, open); + case InventoryItem item -> item; + case IsoDirections direction -> direction; + case IsoDeadBody body -> body; + case null -> throw new IllegalArgumentException("'" + path + "' is null."); + default -> throw new IllegalArgumentException( + "'" + path + "' is a '" + value.getClass().getName() + "'; values are strings, numbers, booleans, maps, lists, inventory items, directions, or dead bodies." + ); + }; + } + + private static String typeOf(@Nullable Object value) { return value == null ? "" : " ('" + value.getClass().getName() + "')"; } +} diff --git a/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/commands/ModCommands.java b/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/commands/ModCommands.java new file mode 100644 index 0000000..2e2b452 --- /dev/null +++ b/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/commands/ModCommands.java @@ -0,0 +1,111 @@ +package dev.overlord.zomboidforge.compat.b42.commands; + +import org.jetbrains.annotations.Nullable; + +import zombie.characters.Role; +import zombie.commands.CommandBase; +import zombie.commands.CommandName; +import zombie.commands.RequiredCapability; +import zombie.core.raknet.UdpConnection; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; +import java.util.regex.Pattern; + +/** + * Command classes of mods in Build 42: subclasses of {@code CommandBase}, which + * {@code GameServer.handleServerCommand} creates through {@code getConstructors()[0]} with + * {@code (username, role, command, connection)}. + */ +public final class ModCommands +{ + private static final Class[] CONSTRUCTOR = {String.class, Role.class, String.class, UdpConnection.class}; + + /** + * Names are inserted into a regular expression by {@code findCommandCls}, so they are limited + * to word characters. With such names, {@code ^name\b} matches the input exactly when its first + * word equals the name, ignoring case. + */ + private static final Pattern NAME = Pattern.compile("\\w+"); + + private ModCommands() {} + + /** + * Fails unless {@code command} is a usable Build 42 command whose names are not taken by + * Project Zomboid's commands or by {@code registered}. + * + * @throws IllegalArgumentException listing every problem + */ + public static void check(Class command, List> registered) + { + List problems = new ArrayList<>(); + int modifiers = command.getModifiers(); + + if (!CommandBase.class.isAssignableFrom(command)) problems.add("it does not extend '" + CommandBase.class.getName() + "'"); + if (!Modifier.isPublic(modifiers)) problems.add("it is not public"); + if (Modifier.isAbstract(modifiers)) problems.add("it is abstract"); + + Constructor[] constructors = command.getConstructors(); + if (constructors.length != 1 || !Arrays.equals(constructors[0].getParameterTypes(), ModCommands.CONSTRUCTOR)) + problems.add("it needs exactly one public constructor '(String, Role, String, UdpConnection)'"); + + if (command.getAnnotationsByType(RequiredCapability.class).length == 0) + problems.add("it has no @RequiredCapability, and Project Zomboid runs no command without one"); + + CommandName[] names = command.getAnnotationsByType(CommandName.class); + if (names.length == 0) problems.add("it has no @CommandName"); + + for (CommandName name : names) + { + if (!ModCommands.NAME.matcher(name.name()).matches()) { + problems.add("the name '" + name.name() + "' contains characters other than letters, digits, and '_'"); + continue; + } + + Class owner = ModCommands.owner(name.name(), registered); + if (owner != null) problems.add("the name '" + name.name() + "' is taken by '" + owner.getName() + "'"); + } + + if (!problems.isEmpty()) throw new IllegalArgumentException("'" + command.getName() + "' cannot be a command: " + String.join("; ", problems) + "."); + } + + /** + * The first class of {@code commands} that is not disabled and has a name that {@code input} + * starts with, matched like {@code CommandBase.findCommandCls} matches Project Zomboid's + * commands; {@code null} when there is none. + */ + public static @Nullable Class find(List> commands, String input) + { + for (Class command : commands) + { + if (CommandBase.isDisabled(command)) continue; + + for (CommandName name : command.getAnnotationsByType(CommandName.class)) { + if (Pattern.compile("^" + name.name() + "\\b", Pattern.CASE_INSENSITIVE).matcher(input).find()) return command; + } + } + + return null; + } + + /** The class among Project Zomboid's commands and {@code registered} that has {@code name}, ignoring case. */ + private static @Nullable Class owner(String name, List> registered) + { + Set> taken = new LinkedHashSet<>(Arrays.>asList(CommandBase.getSubClasses())); + taken.addAll(registered); + + for (Class command : taken) + { + for (CommandName existing : command.getAnnotationsByType(CommandName.class)) { + if (existing.name().equalsIgnoreCase(name)) return command; + } + } + + return null; + } +} diff --git a/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/commands/package-info.java b/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/commands/package-info.java new file mode 100644 index 0000000..79fc54e --- /dev/null +++ b/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/commands/package-info.java @@ -0,0 +1,11 @@ +/** + * Commands of mods in Build 42: checks for registered admin command classes and the lookup that + * mirrors {@code zombie.commands.CommandBase.findCommandCls}; client commands and the conversion + * of their Lua tables. + * + * @noinspection UnstableApiUsage, RedundantSuppression + */ +@NotNullByDefault +package dev.overlord.zomboidforge.compat.b42.commands; + +import org.jetbrains.annotations.NotNullByDefault; diff --git a/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/hooks/ClientCommandHooks.java b/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/hooks/ClientCommandHooks.java new file mode 100644 index 0000000..c0d37bb --- /dev/null +++ b/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/hooks/ClientCommandHooks.java @@ -0,0 +1,54 @@ +package dev.overlord.zomboidforge.compat.b42.hooks; + +import dev.overlord.zomboidforge.api.ClientCommandEvent; +import dev.overlord.zomboidforge.compat.b42.ForgeInstance; +import dev.overlord.zomboidforge.compat.b42.commands.ClientCommandChannel; +import dev.overlord.zomboidforge.compat.b42.commands.LuaTables; + +import org.jetbrains.annotations.Nullable; + +import se.krka.kahlua.vm.KahluaTable; + +import zombie.characters.IsoPlayer; + +/** + * Hooks called by patched {@code zombie.network.GameServer.receiveClientCommand} code, on the main + * thread (client commands are queued for the main loop). Exceptions are caught here; the command + * then reaches Lua as in vanilla. + */ +@SuppressWarnings("CallToPrintStackTrace") +public final class ClientCommandHooks +{ + private ClientCommandHooks() {} + + /** + * Called directly before {@code LuaEventManager.triggerEvent("OnClientCommand", module, command, player, args)}, + * after the vanilla checks (the player exists; {@code vehicle.remove} only with permission). + * Posts {@link ClientCommandEvent} when a mod listens for it. + * + * @param args {@code null} when the client sent no arguments + * @return {@code true} when a listener cancelled the event, which skips the Lua event + */ + public static boolean onClientCommand(String module, String command, IsoPlayer player, @Nullable KahluaTable args) + { + try + { + if (!ForgeInstance.FORGE.hasListeners(ClientCommandEvent.class)) return false; + + ClientCommandEvent event = new ClientCommandEvent( + ClientCommandChannel.ref(player), + module, command, + LuaTables.toJava(args) + ); + + ForgeInstance.FORGE.post(event); + + return event.isCancelled(); + } + catch (Throwable t) + { + t.printStackTrace(); + return false; + } + } +} diff --git a/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/hooks/CommandHooks.java b/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/hooks/CommandHooks.java new file mode 100644 index 0000000..4f73479 --- /dev/null +++ b/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/hooks/CommandHooks.java @@ -0,0 +1,61 @@ +package dev.overlord.zomboidforge.compat.b42.hooks; + +import dev.overlord.zomboidforge.compat.b42.ForgeInstance; +import dev.overlord.zomboidforge.compat.b42.commands.ModCommands; + +import org.jetbrains.annotations.Nullable; + +import java.util.Arrays; +import java.util.List; + +/** + * Hooks called by patched {@code zombie.commands.CommandBase} code, on the main thread: the + * server console, RCON, and chat commands all run there. Exceptions are caught here, and the + * vanilla value is returned. + */ +@SuppressWarnings("CallToPrintStackTrace") +public final class CommandHooks +{ + private CommandHooks() {} + + /** + * Replaces the {@code null} that {@code CommandBase.findCommandCls} returns when no command of + * Project Zomboid matches {@code command}: the mods' command class for it, or {@code null}. + */ + public static @Nullable Class findCommand(@Nullable Class vanilla, String command) + { + try + { + return ModCommands.find(ForgeInstance.FORGE.commands(), command); + } + catch (Throwable t) + { + t.printStackTrace(); + return vanilla; + } + } + + /** + * Replaces the array that {@code CommandBase.getSubClasses} returns: Project Zomboid's + * command classes followed by the mods', in registration order. Without mod commands, the + * vanilla array itself. + */ + public static Class[] listCommands(Class[] vanilla) + { + try + { + List> mods = ForgeInstance.FORGE.commands(); + if (mods.isEmpty()) return vanilla; + + Class[] all = Arrays.copyOf(vanilla, vanilla.length + mods.size()); + for (int i = 0; i < mods.size(); i++) all[vanilla.length + i] = mods.get(i); + + return all; + } + catch (Throwable t) + { + t.printStackTrace(); + return vanilla; + } + } +} diff --git a/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/hooks/ServerHooks.java b/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/hooks/ServerHooks.java index f6d1e66..44e0384 100644 --- a/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/hooks/ServerHooks.java +++ b/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/hooks/ServerHooks.java @@ -75,7 +75,7 @@ public final class ServerHooks ForgeInstance.FORGE.started(); System.out.println("[ZomboidForge] Server started (ZomboidForge " + ZomboidForge.VERSION + ")."); } - catch (RuntimeException e) { e.printStackTrace(); } + catch (Throwable t) { t.printStackTrace(); } } /** @@ -86,8 +86,8 @@ public final class ServerHooks */ public static void onTick() { - try { ForgeInstance.FORGE.tick(); } - catch (RuntimeException e) { e.printStackTrace(); } + try { ForgeInstance.FORGE.tick(); } + catch (Throwable t) { t.printStackTrace(); } } /** @@ -105,6 +105,6 @@ public final class ServerHooks System.out.println("[ZomboidForge] Server stopping."); ForgeInstance.FORGE.stopping(); } - catch (RuntimeException e) { e.printStackTrace(); } + catch (Throwable t) { t.printStackTrace(); } } } diff --git a/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/hooks/StorageHooks.java b/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/hooks/StorageHooks.java index b6e943b..5244379 100644 --- a/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/hooks/StorageHooks.java +++ b/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/hooks/StorageHooks.java @@ -20,6 +20,6 @@ public final class StorageHooks if (running) ForgeInstance.FORGE.backupStarted(); else ForgeInstance.FORGE.backupFinished(); } - catch (RuntimeException e) { e.printStackTrace(); } + catch (Throwable t) { t.printStackTrace(); } } } diff --git a/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/hooks/ZombieVehicleHooks.java b/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/hooks/ZombieVehicleHooks.java index e374764..e9ed449 100644 --- a/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/hooks/ZombieVehicleHooks.java +++ b/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/hooks/ZombieVehicleHooks.java @@ -33,10 +33,8 @@ public final class ZombieVehicleHooks * and is skipped here. */ public static @Nullable Vector3f getIntersectPoint( - @NotNull BaseVehicle vehicle, - @NotNull Vector3f start, - @NotNull Vector3f end, - @Nullable Vector3f result + BaseVehicle vehicle, Vector3f start, + Vector3f end, @Nullable Vector3f result ) { VehicleScript script = vehicle.getScript(); Vector3f extents = script.getExtents(); diff --git a/compat/b42/runtime/src/test/java/dev/overlord/zomboidforge/compat/b42/commands/LuaTablesTest.java b/compat/b42/runtime/src/test/java/dev/overlord/zomboidforge/compat/b42/commands/LuaTablesTest.java new file mode 100644 index 0000000..1654add --- /dev/null +++ b/compat/b42/runtime/src/test/java/dev/overlord/zomboidforge/compat/b42/commands/LuaTablesTest.java @@ -0,0 +1,127 @@ +package dev.overlord.zomboidforge.compat.b42.commands; + +import org.junit.jupiter.api.Test; + +import se.krka.kahlua.j2se.KahluaTableImpl; +import se.krka.kahlua.vm.KahluaTable; + +import zombie.iso.IsoDirections; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.function.Supplier; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** Runs against the Kahlua classes of the server jar; {@code LuaManager.platform} is not used. */ +class LuaTablesTest +{ + private static final Supplier NEW_TABLE = () -> new KahluaTableImpl(new HashMap<>()); + + @Test + void convertsTablesToUnmodifiableMaps() + { + KahluaTable items = LuaTablesTest.NEW_TABLE.get(); + items.rawset(1.0, "Base.Axe"); + items.rawset(2.0, "Base.Saw"); + + KahluaTable table = LuaTablesTest.NEW_TABLE.get(); + table.rawset("count", 3.0); + table.rawset("gift", true); + table.rawset("facing", IsoDirections.N); + table.rawset("items", items); + + Map args = LuaTables.toJava(table); + + assertEquals(Map.of("count", 3.0, "gift", true, "facing", IsoDirections.N, "items", Map.of(1.0, "Base.Axe", 2.0, "Base.Saw")), args); + assertThrows(UnsupportedOperationException.class, () -> args.put("x", "y")); + assertThrows(UnsupportedOperationException.class, () -> ((Map) args.get("items")).clear()); + } + + @Test + void convertsMissingArgumentsToAnEmptyMap() + { + assertEquals(Map.of(), LuaTables.toJava(null)); + } + + @Test + void copiesJavaValuesInLuaTypes() + { + Map args = new LinkedHashMap<>(); + args.put("count", 3); + args.put("price", 2.5F); + args.put("items", List.of("Base.Axe", "Base.Saw")); + args.put("seller", Map.of("name", "alice", 7, false)); + + assertEquals( + Map.of( + "count", 3.0, + "price", 2.5, + "items", Map.of(1.0, "Base.Axe", 2.0, "Base.Saw"), + "seller", Map.of("name", "alice", 7.0, false) + ), + LuaTables.copy(args) + ); + } + + @Test + void copiesAtOnceSoLaterChangesAreNotSent() + { + Map args = new HashMap<>(Map.of("count", 1)); + Map copy = LuaTables.copy(args); + + args.put("count", 2); + + assertEquals(Map.of("count", 1.0), copy); + } + + @Test + void buildsNestedTablesFromACopy() + { + KahluaTable table = LuaTables.toLua(LuaTables.copy(Map.of("count", 3, "items", List.of("Base.Axe"))), LuaTablesTest.NEW_TABLE); + + assertEquals(3.0, table.rawget("count")); + + KahluaTable items = (KahluaTable) table.rawget("items"); + assertEquals("Base.Axe", items.rawget(1.0)); + assertNull(items.rawget(2.0)); + assertEquals(1, items.len()); + } + + @Test + void namesTheFirstValueThatCannotBeSent() + { + IllegalArgumentException e = assertThrows( + IllegalArgumentException.class, + () -> LuaTables.copy(Map.of("seller", Map.of("since", new Object()))) + ); + + assertTrue(e.getMessage().startsWith("'args[seller][since]' is a 'java.lang.Object'; values are strings, numbers, booleans,"), e.getMessage()); + } + + @Test + void rejectsNullValuesOtherKeysAndCycles() + { + Map withNull = new HashMap<>(); + withNull.put("name", null); + + Map withObjectKey = new HashMap<>(); + withObjectKey.put(true, "yes"); + + List cycle = new ArrayList<>(); + cycle.add(cycle); + + assertEquals("'args[name]' is null.", assertThrows(IllegalArgumentException.class, () -> LuaTables.copy(withNull)).getMessage()); + assertEquals( + "'args' has the key 'true' ('java.lang.Boolean'); keys are strings or numbers.", + assertThrows(IllegalArgumentException.class, () -> LuaTables.copy(withObjectKey)).getMessage() + ); + assertEquals("'args[list][1]' contains itself.", assertThrows(IllegalArgumentException.class, () -> LuaTables.copy(Map.of("list", cycle))).getMessage()); + } +} diff --git a/compat/b42/runtime/src/test/java/dev/overlord/zomboidforge/compat/b42/commands/ModCommandsTest.java b/compat/b42/runtime/src/test/java/dev/overlord/zomboidforge/compat/b42/commands/ModCommandsTest.java new file mode 100644 index 0000000..c331228 --- /dev/null +++ b/compat/b42/runtime/src/test/java/dev/overlord/zomboidforge/compat/b42/commands/ModCommandsTest.java @@ -0,0 +1,125 @@ +package dev.overlord.zomboidforge.compat.b42.commands; + +import org.junit.jupiter.api.Test; + +import zombie.characters.Capability; +import zombie.characters.Role; +import zombie.commands.CommandBase; +import zombie.commands.CommandName; +import zombie.commands.DisabledCommand; +import zombie.commands.RequiredCapability; +import zombie.core.raknet.UdpConnection; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; + +/** Runs against the classes of the server jar that the module compiles against. */ +class ModCommandsTest +{ + @CommandName(name = "zfshop") + @CommandName(name = "zfbuy") + @RequiredCapability(requiredCapability = Capability.LoginOnServer) + public static final class ShopCommand extends CommandBase + { + public ShopCommand(String username, Role role, String command, UdpConnection connection) { super(username, role, command, connection); } + + @Override + protected String Command() { return "shop"; } + } + + @CommandName(name = "ZFSHOP") + @RequiredCapability(requiredCapability = Capability.LoginOnServer) + public static final class OtherShopCommand extends CommandBase + { + public OtherShopCommand(String username, Role role, String command, UdpConnection connection) { super(username, role, command, connection); } + + @Override + protected String Command() { return "other shop"; } + } + + @CommandName(name = "Save") + @CommandName(name = "zf-save") + @RequiredCapability(requiredCapability = Capability.SaveWorld) + public static final class SaveCommand extends CommandBase + { + public SaveCommand(String username, Role role, String command, UdpConnection connection) { super(username, role, command, connection); } + + @Override + protected String Command() { return "save"; } + } + + @DisabledCommand + @CommandName(name = "zfoff") + @RequiredCapability(requiredCapability = Capability.LoginOnServer) + public static final class DisabledShopCommand extends CommandBase + { + public DisabledShopCommand(String username, Role role, String command, UdpConnection connection) { super(username, role, command, connection); } + + @Override + protected String Command() { return "off"; } + } + + /** Neither a command nor annotated; its constructor has no parameters. */ + public static final class NotACommand {} + + @Test + void acceptsAUsableCommand() + { + assertDoesNotThrow(() -> ModCommands.check(ModCommandsTest.ShopCommand.class, List.of())); + } + + @Test + void listsEveryProblemOfAClassThatIsNoCommand() + { + IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> ModCommands.check(ModCommandsTest.NotACommand.class, List.of())); + + assertEquals( + "'" + ModCommandsTest.NotACommand.class.getName() + "' cannot be a command: it does not extend 'zombie.commands.CommandBase';" + + " it needs exactly one public constructor '(String, Role, String, UdpConnection)';" + + " it has no @RequiredCapability, and Project Zomboid runs no command without one; it has no @CommandName.", + e.getMessage() + ); + } + + @Test + void rejectsNamesOfProjectZomboidIgnoringCaseAndNamesWithOtherCharacters() + { + IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> ModCommands.check(ModCommandsTest.SaveCommand.class, List.of())); + + assertEquals( + "'" + ModCommandsTest.SaveCommand.class.getName() + "' cannot be a command:" + + " the name 'Save' is taken by 'zombie.commands.serverCommands.SaveCommand';" + + " the name 'zf-save' contains characters other than letters, digits, and '_'.", + e.getMessage() + ); + } + + @Test + void rejectsNamesOfRegisteredCommands() + { + IllegalArgumentException e = assertThrows( + IllegalArgumentException.class, + () -> ModCommands.check(ModCommandsTest.OtherShopCommand.class, List.of(ModCommandsTest.ShopCommand.class)) + ); + + assertEquals( + "'" + ModCommandsTest.OtherShopCommand.class.getName() + "' cannot be a command: the name 'ZFSHOP' is taken by '" + ModCommandsTest.ShopCommand.class.getName() + "'.", + e.getMessage() + ); + } + + @Test + void findsCommandsByTheirFirstWordIgnoringCase() + { + List> commands = List.of(ModCommandsTest.DisabledShopCommand.class, ModCommandsTest.ShopCommand.class); + + assertEquals(ModCommandsTest.ShopCommand.class, ModCommands.find(commands, "zfshop")); + assertEquals(ModCommandsTest.ShopCommand.class, ModCommands.find(commands, "ZFBuy apple 3")); + assertNull(ModCommands.find(commands, "zfshopping")); + assertNull(ModCommands.find(commands, "zfoff"), "disabled commands are skipped, like Project Zomboid's"); + } +} diff --git a/core/src/main/java/dev/overlord/zomboidforge/core/Forge.java b/core/src/main/java/dev/overlord/zomboidforge/core/Forge.java index b9d0ac2..839065d 100644 --- a/core/src/main/java/dev/overlord/zomboidforge/core/Forge.java +++ b/core/src/main/java/dev/overlord/zomboidforge/core/Forge.java @@ -2,10 +2,14 @@ package dev.overlord.zomboidforge.core; import dev.overlord.zomboidforge.api.Event; import dev.overlord.zomboidforge.api.GameVersion; +import dev.overlord.zomboidforge.api.MainThread; import dev.overlord.zomboidforge.api.Mod; import dev.overlord.zomboidforge.api.TickEvent; import dev.overlord.zomboidforge.api.ZomboidForge; import dev.overlord.zomboidforge.api.storage.StorageException; +import dev.overlord.zomboidforge.core.commands.ClientCommandSender; +import dev.overlord.zomboidforge.core.commands.CommandRegistry; +import dev.overlord.zomboidforge.core.commands.ModClientCommands; import dev.overlord.zomboidforge.core.config.ForgeSettings; import dev.overlord.zomboidforge.core.mods.GameClasses; import dev.overlord.zomboidforge.core.mods.ModDiscovery; @@ -52,6 +56,8 @@ public final class Forge private final Path directory; private final @Nullable ModVersion api; + private final CommandRegistry commands; + private final ClientCommandSender clientCommands; private volatile List mods = List.of(); private volatile ForgeSettings settings = ForgeSettings.DEFAULTS; @@ -61,32 +67,44 @@ public final class Forge * @param directory the ZomboidForge directory * @param api the API version mods are checked against, or {@code null} to skip the * check + * @param commands checks the command classes that mods register against the running + * game version + * @param clientCommands sends the mods' server commands to clients in the running game version */ - public Forge(Path directory, @Nullable ModVersion api) + public Forge(Path directory, @Nullable ModVersion api, CommandRegistry.Validator commands, ClientCommandSender clientCommands) { - this.directory = directory; - this.api = api; + this.directory = directory; + this.api = api; + this.commands = new CommandRegistry(commands, this::commandsOpen); + this.clientCommands = clientCommands; } /** * Directory from {@value #DIRECTORY_PROPERTY} (default {@value #DEFAULT_DIRECTORY}); API * version from {@link ZomboidForge#VERSION}. Builds without a release version ({@code dev}, * {@code 0.0.0-...}) skip the API check. + * + * @param commands checks the command classes that mods register against the running + * game version + * @param clientCommands sends the mods' server commands to clients in the running game version */ - public static Forge fromSystemProperties() + public static Forge fromSystemProperties(CommandRegistry.Validator commands, ClientCommandSender clientCommands) { Path directory = Path.of(System.getProperty(Forge.DIRECTORY_PROPERTY, Forge.DEFAULT_DIRECTORY)); ModVersion api = ModVersion.tryParse(ZomboidForge.VERSION) .filter(version -> version.major() != 0 || version.minor() != 0 || version.patch() != 0) .orElse(null); - return new Forge(directory, api); + return new Forge(directory, api, commands, clientCommands); } public Lifecycle.Phase phase() { return this.lifecycle.phase(); } public List mods() { return this.mods; } + /** The admin command classes that mods registered, in registration order. */ + public List> commands() { return this.commands.classes(); } + /** * Reads {@code forge.toml}, then discovers, checks, and loads every mod in * {@code /mods}. Called once on the main thread, which becomes the thread of @@ -154,14 +172,17 @@ public final class Forge ); } - /** Calls {@link Mod#onServerStarted()} of every mod in load order. Main thread. */ + /** + * Calls {@link Mod#onServerStarted()} of every mod in load order. Main thread. Anything a + * mod throws is logged, and the next mod is called. + */ public void started() { this.lifecycle.started(); for (ModLoader.LoadedMod mod : this.mods) { - try { mod.mod().onServerStarted(); } - catch (RuntimeException e) { this.logger.log(System.Logger.Level.ERROR, "'" + mod.descriptor().id() + "': onServerStarted() threw.", e); } + try { mod.mod().onServerStarted(); } + catch (Throwable t) { this.logger.log(System.Logger.Level.ERROR, "'" + mod.descriptor().id() + "': onServerStarted() threw.", t); } } } @@ -183,6 +204,9 @@ public final class Forge */ public void post(Event event) { this.events.post(event); } + /** Whether any mod listens for {@code type}, so a hook can skip creating the event. */ + public boolean hasListeners(Class type) { return this.events.hasListeners(type); } + /** * Pauses storage for a backup of the save folder (see {@link StorageDatabase#backupStarted()}). * Called by the patched {@code ZipBackup.makeBackupFile}, on the thread that makes the backup. @@ -205,18 +229,24 @@ public final class Forge /** * Once: calls {@link Mod#onStopping()} of every mod in reverse load order, then stops the - * mods' threads, events, and storage (see {@link #stopMods}). Called on the shutdown thread. + * mods' threads, events, and storage (see {@link #stopMods}). Called on the shutdown thread, + * before the world is saved, so nothing a mod throws leaves this method. */ public void stopping() { if (!this.lifecycle.stopping()) return; - for (ModLoader.LoadedMod mod : this.mods.reversed()) { - try { mod.mod().onStopping(); } - catch (RuntimeException e) { this.logger.log(System.Logger.Level.ERROR, "'" + mod.descriptor().id() + "': onStopping() threw.", e); } + try + { + for (ModLoader.LoadedMod mod : this.mods.reversed()) { + try { mod.mod().onStopping(); } + catch (Throwable t) { this.logger.log(System.Logger.Level.ERROR, "'" + mod.descriptor().id() + "': onStopping() threw.", t); } + } + } + finally + { + this.stopMods(this.settings.shutdownTimeout()); } - - this.stopMods(this.settings.shutdownTimeout()); } /** @@ -237,6 +267,9 @@ public final class Forge catch (StorageException e) { this.logger.log(System.Logger.Level.ERROR, "Closing the storage failed.", e); } } + /** Mods register commands on the main thread while they load. */ + private boolean commandsOpen() { return this.queue.isMainThread() && this.lifecycle.phase() == Lifecycle.Phase.BOOTING; } + /** The main thread may use storage only before the main loop runs. */ private boolean storageForbidden() { return this.queue.isMainThread() && this.lifecycle.phase() == Lifecycle.Phase.RUNNING; } @@ -245,13 +278,16 @@ public final class Forge ModThreads.ModExecutors executors = this.threads.create(id, logger); StorageDatabase storage = Objects.requireNonNull(this.storage, "storage"); + MainThread main = this.queue.forMod(id, logger); return new ModServices( this.events.forMod(id, executors.modThread(), logger), - this.queue.forMod(id, logger), + main, executors.modThread(), executors.async(), - new ModTables(id, storage, logger) + new ModTables(id, storage, logger), + this.commands.forMod(logger), + new ModClientCommands(this.clientCommands, main) ); } } diff --git a/core/src/main/java/dev/overlord/zomboidforge/core/commands/ClientCommandSender.java b/core/src/main/java/dev/overlord/zomboidforge/core/commands/ClientCommandSender.java new file mode 100644 index 0000000..287ca6d --- /dev/null +++ b/core/src/main/java/dev/overlord/zomboidforge/core/commands/ClientCommandSender.java @@ -0,0 +1,21 @@ +package dev.overlord.zomboidforge.core.commands; + +import dev.overlord.zomboidforge.api.PlayerRef; + +import org.jetbrains.annotations.Nullable; + +import java.util.Map; + +/** Sends server commands to clients; implemented by the compat module of the running game version. */ +@FunctionalInterface +public interface ClientCommandSender +{ + /** + * Checks {@code args} on the calling thread and returns the action that converts and sends + * the command, which runs on the main thread. + * + * @param player the receiving player, or {@code null} for every connected client + * @throws IllegalArgumentException naming a key or value that cannot be sent + */ + Runnable prepare(@Nullable PlayerRef player, String module, String command, Map args); +} diff --git a/core/src/main/java/dev/overlord/zomboidforge/core/commands/CommandRegistry.java b/core/src/main/java/dev/overlord/zomboidforge/core/commands/CommandRegistry.java new file mode 100644 index 0000000..b4335c9 --- /dev/null +++ b/core/src/main/java/dev/overlord/zomboidforge/core/commands/CommandRegistry.java @@ -0,0 +1,74 @@ +package dev.overlord.zomboidforge.core.commands; + +import dev.overlord.zomboidforge.api.Commands; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.function.BooleanSupplier; + +/** + * The admin command classes that mods registered, in registration order. What a command class + * has to look like depends on the Project Zomboid version, so a {@link Validator} from the compat + * module checks every class. Registration happens only while the mods load, on the main thread; + * the compat hooks read {@link #classes()} on the main thread afterwards. + */ +public final class CommandRegistry +{ + /** Checks a command class against the command framework of the running game version. */ + @FunctionalInterface + public interface Validator + { + /** + * @param registered the classes registered before, by any mod + * @throws IllegalArgumentException naming what is wrong with {@code command} + */ + void check(Class command, List> registered); + } + + private final Validator validator; + private final BooleanSupplier open; + + private volatile List> classes = List.of(); + + /** @param open whether registration is allowed now, on the calling thread */ + public CommandRegistry(Validator validator, BooleanSupplier open) + { + this.validator = Objects.requireNonNull(validator); + this.open = Objects.requireNonNull(open); + } + + /** Every registered class, in registration order. */ + public List> classes() { return this.classes; } + + /** + * Registration for one mod; registered classes are logged with {@code logger}. Exceptions do + * not name the mod: one thrown in the mod's {@code onLoad()} is reported with its id. + */ + public Commands forMod(System.Logger logger) + { + return command -> + { + this.register(command); + logger.log(System.Logger.Level.INFO, "Registered the command class '" + command.getName() + "'."); + }; + } + + private synchronized void register(Class command) + { + Objects.requireNonNull(command, "command"); + + if (!this.open.getAsBoolean()) + throw new IllegalStateException("Commands can only be registered on the main thread while the mod loads (constructor or onLoad())."); + + if (this.classes.contains(command)) + throw new IllegalArgumentException("The command class '" + command.getName() + "' is registered already."); + + this.validator.check(command, this.classes); + + List> updated = new ArrayList<>(this.classes); + updated.add(command); + + this.classes = List.copyOf(updated); + } +} diff --git a/core/src/main/java/dev/overlord/zomboidforge/core/commands/ModClientCommands.java b/core/src/main/java/dev/overlord/zomboidforge/core/commands/ModClientCommands.java new file mode 100644 index 0000000..02a9db9 --- /dev/null +++ b/core/src/main/java/dev/overlord/zomboidforge/core/commands/ModClientCommands.java @@ -0,0 +1,45 @@ +package dev.overlord.zomboidforge.core.commands; + +import dev.overlord.zomboidforge.api.ClientCommands; +import dev.overlord.zomboidforge.api.MainThread; +import dev.overlord.zomboidforge.api.PlayerRef; + +import java.util.Map; +import java.util.Objects; + +/** + * The {@link ClientCommands} of one mod: checks on the calling thread, sends through the mod's + * {@link MainThread}, so a command sent off the main thread is one of the mod's queued tasks. + */ +public final class ModClientCommands implements ClientCommands +{ + private final ClientCommandSender sender; + private final MainThread main; + + public ModClientCommands(ClientCommandSender sender, MainThread main) + { + this.sender = Objects.requireNonNull(sender); + this.main = Objects.requireNonNull(main); + } + + @Override + public void send(PlayerRef player, String module, String command, Map args) + { + Objects.requireNonNull(player, "player"); + + this.main.execute(this.sender.prepare(player, ModClientCommands.require(module, "module"), ModClientCommands.require(command, "command"), Objects.requireNonNull(args, "args"))); + } + + @Override + public void sendToAll(String module, String command, Map args) + { + this.main.execute(this.sender.prepare(null, ModClientCommands.require(module, "module"), ModClientCommands.require(command, "command"), Objects.requireNonNull(args, "args"))); + } + + private static String require(String value, String name) + { + if (Objects.requireNonNull(value, name).isEmpty()) throw new IllegalArgumentException("'" + name + "' is empty."); + + return value; + } +} diff --git a/core/src/main/java/dev/overlord/zomboidforge/core/commands/package-info.java b/core/src/main/java/dev/overlord/zomboidforge/core/commands/package-info.java new file mode 100644 index 0000000..3224c22 --- /dev/null +++ b/core/src/main/java/dev/overlord/zomboidforge/core/commands/package-info.java @@ -0,0 +1,10 @@ +/** + * Commands of loaded mods: the registry of admin commands that the compat hooks consult, and + * server commands to clients. + * + * @noinspection UnstableApiUsage, RedundantSuppression + */ +@NotNullByDefault +package dev.overlord.zomboidforge.core.commands; + +import org.jetbrains.annotations.NotNullByDefault; diff --git a/core/src/main/java/dev/overlord/zomboidforge/core/mods/ModClassLoader.java b/core/src/main/java/dev/overlord/zomboidforge/core/mods/ModClassLoader.java index 1d0004e..5df4033 100644 --- a/core/src/main/java/dev/overlord/zomboidforge/core/mods/ModClassLoader.java +++ b/core/src/main/java/dev/overlord/zomboidforge/core/mods/ModClassLoader.java @@ -29,6 +29,9 @@ import java.util.stream.Collectors; * * Everything else on the parent's class path, such as ZomboidForge's own classes and libraries, * is not visible. A mod's own copy of a library that the game also bundles takes precedence. + * + *

The lookup order prevents accidental linkage only. It is not a security boundary: mod code + * can still reach other classes through reflection or {@link ClassLoader#getSystemClassLoader()}. */ final class ModClassLoader extends URLClassLoader { diff --git a/core/src/main/java/dev/overlord/zomboidforge/core/mods/ModLoader.java b/core/src/main/java/dev/overlord/zomboidforge/core/mods/ModLoader.java index 8e8e8ca..d988a9d 100644 --- a/core/src/main/java/dev/overlord/zomboidforge/core/mods/ModLoader.java +++ b/core/src/main/java/dev/overlord/zomboidforge/core/mods/ModLoader.java @@ -1,6 +1,8 @@ package dev.overlord.zomboidforge.core.mods; import dev.overlord.zomboidforge.api.AsyncExecutor; +import dev.overlord.zomboidforge.api.ClientCommands; +import dev.overlord.zomboidforge.api.Commands; import dev.overlord.zomboidforge.api.Events; import dev.overlord.zomboidforge.api.GameVersion; import dev.overlord.zomboidforge.api.MainThread; @@ -36,17 +38,19 @@ public final class ModLoader public record LoadedMod(ModDescriptor descriptor, Path directory, ClassLoader classLoader, Mod mod) {} private record Context( - String id, - String version, - GameVersion gameVersion, - System.Logger logger, - Path directory, - ModConfig config, - Events events, - MainThread main, - ModThread modThread, - AsyncExecutor async, - ModStorage storage + String id, + String version, + GameVersion gameVersion, + System.Logger logger, + Path directory, + ModConfig config, + Events events, + MainThread main, + ModThread modThread, + AsyncExecutor async, + ModStorage storage, + Commands commands, + ClientCommands clientCommands ) implements ModContext {} private ModLoader() {} @@ -93,7 +97,9 @@ public final class ModLoader provided.main(), provided.modThread(), provided.async(), - provided.storage() + provided.storage(), + provided.commands(), + provided.clientCommands() ); loaded.add(new LoadedMod(descriptor, candidate.directory(), loader, ModLoader.create(descriptor, loader, context))); diff --git a/core/src/main/java/dev/overlord/zomboidforge/core/mods/ModServices.java b/core/src/main/java/dev/overlord/zomboidforge/core/mods/ModServices.java index 856554f..2bcff11 100644 --- a/core/src/main/java/dev/overlord/zomboidforge/core/mods/ModServices.java +++ b/core/src/main/java/dev/overlord/zomboidforge/core/mods/ModServices.java @@ -1,14 +1,23 @@ package dev.overlord.zomboidforge.core.mods; import dev.overlord.zomboidforge.api.AsyncExecutor; +import dev.overlord.zomboidforge.api.ClientCommands; +import dev.overlord.zomboidforge.api.Commands; import dev.overlord.zomboidforge.api.Events; import dev.overlord.zomboidforge.api.MainThread; import dev.overlord.zomboidforge.api.ModThread; import dev.overlord.zomboidforge.api.storage.ModStorage; -/** The threads, event registration, and storage of one mod, created before its entry point. */ -public record ModServices(Events events, MainThread main, ModThread modThread, AsyncExecutor async, ModStorage storage) -{ +/** The threads, event and command registration, storage, and client commands of one mod, created before its entry point. */ +public record ModServices( + Events events, + MainThread main, + ModThread modThread, + AsyncExecutor async, + ModStorage storage, + Commands commands, + ClientCommands clientCommands +) { /** Creates the services of one mod. */ @FunctionalInterface public interface Factory diff --git a/core/src/main/java/dev/overlord/zomboidforge/core/mods/ModVersion.java b/core/src/main/java/dev/overlord/zomboidforge/core/mods/ModVersion.java index 4388e7a..cb11b96 100644 --- a/core/src/main/java/dev/overlord/zomboidforge/core/mods/ModVersion.java +++ b/core/src/main/java/dev/overlord/zomboidforge/core/mods/ModVersion.java @@ -13,7 +13,8 @@ import java.util.regex.Pattern; */ public record ModVersion(int major, int minor, int patch, @Nullable String preRelease) implements Comparable { - private static final Pattern FORMAT = Pattern.compile("(\\d+)(?:\\.(\\d+))?(?:\\.(\\d+))?(?:-([0-9A-Za-z.-]+))?"); + // At most 9 digits per number, so every number fits an int. + private static final Pattern FORMAT = Pattern.compile("(\\d{1,9})(?:\\.(\\d{1,9}))?(?:\\.(\\d{1,9}))?(?:-([0-9A-Za-z.-]+))?"); private static final Comparator ORDER = Comparator .comparingInt(ModVersion::major) diff --git a/core/src/main/java/dev/overlord/zomboidforge/core/runtime/MainThreadQueue.java b/core/src/main/java/dev/overlord/zomboidforge/core/runtime/MainThreadQueue.java index c028bd0..390bdca 100644 --- a/core/src/main/java/dev/overlord/zomboidforge/core/runtime/MainThreadQueue.java +++ b/core/src/main/java/dev/overlord/zomboidforge/core/runtime/MainThreadQueue.java @@ -79,25 +79,30 @@ public final class MainThreadQueue int index = count == 0 ? 0 : this.next % count; int empty = 0; - while (empty < count && !this.closed) + try { - ModQueue queue = queues[index]; - index = (index + 1) % count; + while (empty < count && !this.closed) + { + ModQueue queue = queues[index]; + index = (index + 1) % count; - Task task = queue.tasks.poll(); + Task task = queue.tasks.poll(); - if (task == null) { - empty++; - continue; + if (task == null) { + empty++; + continue; + } + + empty = 0; + queue.run(task.action()); + + if (System.nanoTime() >= deadline) break; } - - empty = 0; - queue.run(task.action()); - - if (System.nanoTime() >= deadline) break; } - - this.next = index; + finally + { + this.next = index; + } } /** Rejects further tasks and cancels the queued ones (their futures are cancelled). Any thread. */ diff --git a/core/src/main/java/dev/overlord/zomboidforge/core/runtime/ModTaskEvent.java b/core/src/main/java/dev/overlord/zomboidforge/core/runtime/ModTaskEvent.java index 75df9f0..dac85ce 100644 --- a/core/src/main/java/dev/overlord/zomboidforge/core/runtime/ModTaskEvent.java +++ b/core/src/main/java/dev/overlord/zomboidforge/core/runtime/ModTaskEvent.java @@ -25,8 +25,8 @@ final class ModTaskEvent extends jdk.jfr.Event /** * Runs {@code action} as a {@code zomboidforge.ModTask} event. Mod code must not end the - * calling thread's work, so failures are returned instead of thrown: runtime exceptions, - * missing classes or members ({@link LinkageError}), and stack overflows. + * calling thread's work, so every failure is returned instead of thrown, including errors + * and checked exceptions thrown without being declared. * * @return the failure, or {@code null} when {@code action} returned normally */ @@ -40,9 +40,9 @@ final class ModTaskEvent extends jdk.jfr.Event action.run(); return null; } - catch (RuntimeException | LinkageError | StackOverflowError e) + catch (Throwable t) { - return e; + return t; } finally { diff --git a/core/src/main/java/dev/overlord/zomboidforge/core/storage/ModTables.java b/core/src/main/java/dev/overlord/zomboidforge/core/storage/ModTables.java index 53fe1bf..4bd0a15 100644 --- a/core/src/main/java/dev/overlord/zomboidforge/core/storage/ModTables.java +++ b/core/src/main/java/dev/overlord/zomboidforge/core/storage/ModTables.java @@ -44,6 +44,13 @@ public final class ModTables implements ModStorage /** A stored schema. */ private record Schema(int version, List columns) {} + /** Work on one stored row; may throw {@link SQLException}. */ + @FunctionalInterface + private interface RowAction + { + void accept(Row row) throws SQLException; + } + private final String id; private final StorageDatabase database; private final System.Logger logger; @@ -226,13 +233,12 @@ public final class ModTables implements ModStorage throw new StorageException(table + " has schema version " + stored.version() + ", the mod declares " + this.version + " but no migration from " + stored.version() + "."); String rebuilt = physical + "__migrating"; - List rows = ModTables.rows(connection, physical); SqlTable target = new SqlTable<>(ModTables.this.database, codec, rebuilt); ModTables.execute(connection, "DROP TABLE IF EXISTS " + SqlTable.quoted(rebuilt)); ModTables.create(connection, rebuilt, codec.columns()); - for (Row row : rows) + int migrated = ModTables.forEachRow(connection, physical, row -> { R record; @@ -240,13 +246,13 @@ public final class ModTables implements ModStorage catch (RuntimeException e) { throw new StorageException(table + ": the migration from version " + stored.version() + " failed for row '" + row.key() + "': " + e, e); } target.set(row.key(), record); - } + }); ModTables.execute(connection, "DROP TABLE " + SqlTable.quoted(physical)); ModTables.execute(connection, "ALTER TABLE " + SqlTable.quoted(rebuilt) + " RENAME TO " + SqlTable.quoted(physical)); ModTables.this.saveSchema(connection, this.name, this.version, codec.columns()); - ModTables.this.logger.log(System.Logger.Level.INFO, table + ": migrated " + rows.size() + " row(s) from schema version " + stored.version() + " to " + this.version + "."); + ModTables.this.logger.log(System.Logger.Level.INFO, table + ": migrated " + migrated + " row(s) from schema version " + stored.version() + " to " + this.version + "."); } } @@ -276,10 +282,15 @@ public final class ModTables implements ModStorage ModTables.execute(connection, "CREATE TABLE " + SqlTable.quoted(physical) + " (" + SqlTable.quoted(SqlTable.KEY) + " TEXT PRIMARY KEY NOT NULL" + definitions + ")"); } - /** Every row of {@code physical} with all its columns, sorted by key. */ - private static List rows(Connection connection, String physical) throws SQLException + /** + * Calls {@code action} for every row of {@code physical} with all its columns, sorted by key, + * reading one row at a time. + * + * @return the number of rows + */ + private static int forEachRow(Connection connection, String physical, RowAction action) throws SQLException { - List rows = new ArrayList<>(); + int count = 0; try (Statement statement = connection.createStatement(); ResultSet result = statement.executeQuery("SELECT * FROM " + SqlTable.quoted(physical) + " ORDER BY " + SqlTable.quoted(SqlTable.KEY))) { @@ -299,11 +310,12 @@ public final class ModTables implements ModStorage else values.put(column, value instanceof Integer number ? Long.valueOf(number) : value); } - rows.add(new StoredRow(key, values)); + action.accept(new StoredRow(key, values)); + count++; } } - return rows; + return count; } private static List tableNames(Connection connection, String mod) throws SQLException diff --git a/core/src/main/java/dev/overlord/zomboidforge/core/storage/RecordCodec.java b/core/src/main/java/dev/overlord/zomboidforge/core/storage/RecordCodec.java index 1ce412a..1902866 100644 --- a/core/src/main/java/dev/overlord/zomboidforge/core/storage/RecordCodec.java +++ b/core/src/main/java/dev/overlord/zomboidforge/core/storage/RecordCodec.java @@ -102,7 +102,8 @@ final class RecordCodec if (stored == null && !column.nullable()) throw new StorageException("Column '" + column.name() + "' of '" + this.type.getSimpleName() + "' is null in the database."); - arguments[i] = stored == null ? null : RecordCodec.value(column.kind(), this.types[i], stored); + try { arguments[i] = stored == null ? null : RecordCodec.value(column.kind(), this.types[i], stored); } + catch (RuntimeException e) { throw new StorageException("Column '" + column.name() + "' of '" + this.type.getSimpleName() + "' holds '" + stored + "', which is not a valid '" + this.types[i].getSimpleName() + "': " + e, e); } } try { return this.type.cast(this.constructor.invokeWithArguments(arguments)); } diff --git a/core/src/main/java/dev/overlord/zomboidforge/core/storage/StorageDatabase.java b/core/src/main/java/dev/overlord/zomboidforge/core/storage/StorageDatabase.java index 9a9a529..0641709 100644 --- a/core/src/main/java/dev/overlord/zomboidforge/core/storage/StorageDatabase.java +++ b/core/src/main/java/dev/overlord/zomboidforge/core/storage/StorageDatabase.java @@ -10,7 +10,10 @@ import java.nio.file.Path; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; +import java.sql.Savepoint; import java.sql.Statement; +import java.time.Duration; +import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReentrantLock; import java.util.function.BooleanSupplier; @@ -31,6 +34,9 @@ public final class StorageDatabase implements AutoCloseable /** File name, in the world's save folder. */ public static final String FILE = "zomboidforge.db"; + /** Longest wait of a backup for the running storage operation. */ + static final Duration BACKUP_WAIT = Duration.ofSeconds(10); + /** Work with the connection that has a result; may throw {@link SQLException}. */ @FunctionalInterface public interface Work @@ -104,8 +110,10 @@ public final class StorageDatabase implements AutoCloseable } /** - * Runs {@code work} in a transaction. Nested calls on the same thread join the outer - * transaction; it commits when the outermost call returns and rolls back when any throws. + * Runs {@code work} in a transaction. The outermost call on a thread commits when + * {@code work} returns and rolls back when it throws. A nested call runs inside a savepoint + * of the outer transaction: when its {@code work} throws, only its own writes are rolled + * back, also when the outer work catches the exception. */ public T transaction(Work work) { @@ -118,19 +126,23 @@ public final class StorageDatabase implements AutoCloseable boolean outermost = this.depth == 0; if (outermost) connection.setAutoCommit(false); + + Savepoint savepoint = outermost ? null : connection.setSavepoint(); this.depth++; try { T result = work.run(connection); - if (outermost) connection.commit(); + + if (savepoint == null) connection.commit(); + else connection.releaseSavepoint(savepoint); return result; } - catch (SQLException | RuntimeException | Error e) + catch (Throwable t) { - if (outermost) StorageDatabase.rollback(connection, e); - throw e; + StorageDatabase.rollback(connection, savepoint, t); + throw t; } finally { @@ -149,15 +161,30 @@ public final class StorageDatabase implements AutoCloseable } /** - * Blocks storage for a backup of the save folder: waits for the running operation, writes - * the WAL into the database file ({@code PRAGMA wal_checkpoint(TRUNCATE)}), and keeps the - * lock until {@link #backupFinished()} on the same thread. Other threads' storage calls wait. + * Blocks storage for a backup of the save folder: waits up to {@link #BACKUP_WAIT} for the + * running operation, writes the WAL into the database file + * ({@code PRAGMA wal_checkpoint(TRUNCATE)}), and keeps the lock until + * {@link #backupFinished()} on the same thread. Other threads' storage calls wait. + * + *

When the running operation takes longer, for example a transaction that waits for the + * thread making the backup, the backup runs without the lock and storage stays usable. * * @return a problem to log, or {@code null} */ - public @Nullable String backupStarted() + public @Nullable String backupStarted() { return this.backupStarted(StorageDatabase.BACKUP_WAIT); } + + @Nullable String backupStarted(Duration wait) { - this.lock.lock(); + try + { + if (!this.lock.tryLock(wait.toMillis(), TimeUnit.MILLISECONDS)) + return "Storage was busy for " + wait.toSeconds() + " s; the backup runs without pausing storage, so its copy of '" + StorageDatabase.FILE + "' may be incomplete."; + } + catch (InterruptedException e) + { + Thread.currentThread().interrupt(); + return "Interrupted while waiting for storage; the backup runs without pausing storage, so its copy of '" + StorageDatabase.FILE + "' may be incomplete."; + } Connection connection = this.connection; if (connection == null) return null; @@ -241,9 +268,21 @@ public final class StorageDatabase implements AutoCloseable return connection; } - private static void rollback(Connection connection, Throwable cause) + /** Rolls back the transaction, or only to {@code savepoint} (and releases it) when one is given. */ + private static void rollback(Connection connection, @Nullable Savepoint savepoint, Throwable cause) { - try { connection.rollback(); } - catch (SQLException e) { cause.addSuppressed(e); } + try + { + if (savepoint == null) { + connection.rollback(); + } else { + connection.rollback(savepoint); + connection.releaseSavepoint(savepoint); + } + } + catch (SQLException e) + { + cause.addSuppressed(e); + } } } diff --git a/core/src/test/java/dev/overlord/zomboidforge/core/ForgeTest.java b/core/src/test/java/dev/overlord/zomboidforge/core/ForgeTest.java index 0b581ba..6c584f0 100644 --- a/core/src/test/java/dev/overlord/zomboidforge/core/ForgeTest.java +++ b/core/src/test/java/dev/overlord/zomboidforge/core/ForgeTest.java @@ -11,13 +11,16 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; +import testmods.CommandMod; import testmods.ContextMod; +import testmods.ErrorMod; import testmods.Recorder; import testmods.ThreadMod; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; +import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.Map; @@ -26,6 +29,7 @@ import java.util.function.BooleanSupplier; import java.util.stream.Stream; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; import static org.junit.jupiter.api.Assertions.assertNotSame; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -44,6 +48,12 @@ class ForgeTest private Path gameJar; private Path storageFile; + /** Classes that mods registered as commands, as {@code " after "}; every class is accepted. */ + private final List checkedCommands = new ArrayList<>(); + + /** Client commands that mods sent, as {@code " . "}. */ + private final List sentClientCommands = new ArrayList<>(); + @BeforeEach void setUp() throws IOException { @@ -55,7 +65,15 @@ class ForgeTest Recorder.EVENTS.clear(); } - private Forge forge() { return new Forge(this.directory, ModVersion.parse("0.3.0")); } + private Forge forge() + { + return new Forge( + this.directory, + ModVersion.parse("0.3.0"), + (command, registered) -> this.checkedCommands.add(command.getName() + " after " + registered.size()), + (player, module, command, args) -> () -> this.sentClientCommands.add((player == null ? "all" : player.username()) + " " + module + "." + command + " " + args) + ); + } private Forge load() throws ModLoadException { @@ -104,6 +122,38 @@ class ForgeTest ); } + @Test + void modsRegisterCommandsOnlyWhileTheyLoad() throws Exception + { + TestMods.folder(this.mods, "commands", TestMods.toml("commands", CommandMod.class.getName(), ""), Map.of( + "testmods/CommandMod", TestMods.classFile(CommandMod.class), + "testmods/CommandMod$Command", TestMods.classFile(CommandMod.Command.class) + )); + + Forge forge = this.load(); + + assertEquals(List.of("testmods.CommandMod$Command"), forge.commands().stream().map(Class::getName).toList()); + assertEquals(List.of("testmods.CommandMod$Command after 0"), this.checkedCommands); + + forge.started(); + + assertInstanceOf(IllegalStateException.class, ForgeTest.field(forge.mods().getFirst().mod(), "lateRegistration")); + assertEquals(1, forge.commands().size()); + } + + @Test + void modsSendClientCommandsThroughTheGameSender() throws Exception + { + TestMods.folder(this.mods, "commands", TestMods.toml("commands", CommandMod.class.getName(), ""), Map.of( + "testmods/CommandMod", TestMods.classFile(CommandMod.class), + "testmods/CommandMod$Command", TestMods.classFile(CommandMod.Command.class) + )); + + this.load().started(); + + assertEquals(List.of("all Test.started {count=1}"), this.sentClientCommands); + } + @Test void modsSeeTheirContextAndSettingsInTheConstructor() throws Exception { @@ -197,6 +247,25 @@ class ForgeTest assertEquals(Lifecycle.Phase.BOOTING, forge.phase()); } + @Test + void errorsOfModsInStartedAndStoppingReachNeitherTheGameNorTheOtherMods() throws Exception + { + TestMods.folder(this.mods, "economy", TestMods.toml("economy", "economy.EconomyMod", ForgeTest.USES_GAME), Map.of( + "economy/EconomyMod", TestMods.modClass("economy/EconomyMod", "economy", null, false) + )); + TestMods.folder(this.mods, "errors", TestMods.toml("errors", ErrorMod.class.getName(), "[dependencies]\neconomy = \"1.0\"\n"), Map.of( + "testmods/ErrorMod", TestMods.classFile(ErrorMod.class) + )); + + Forge forge = this.load(); + + forge.started(); + forge.stopping(); + + assertEquals(List.of("economy:new", "economy:onLoad", "economy:onServerStarted", "economy:onStopping"), Recorder.EVENTS, "economy is stopped after errors stopped"); + assertEquals(Lifecycle.Phase.STOPPING, forge.phase()); + } + @Test void failsWhenTheEntryPointIsNoMod() throws IOException { diff --git a/core/src/test/java/dev/overlord/zomboidforge/core/commands/CommandRegistryTest.java b/core/src/test/java/dev/overlord/zomboidforge/core/commands/CommandRegistryTest.java new file mode 100644 index 0000000..2907b21 --- /dev/null +++ b/core/src/test/java/dev/overlord/zomboidforge/core/commands/CommandRegistryTest.java @@ -0,0 +1,78 @@ +package dev.overlord.zomboidforge.core.commands; + +import dev.overlord.zomboidforge.api.Commands; +import dev.overlord.zomboidforge.core.RecordingLogger; + +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.atomic.AtomicBoolean; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +class CommandRegistryTest +{ + private final List checked = new ArrayList<>(); + private final AtomicBoolean open = new AtomicBoolean(true); + private final RecordingLogger logger = new RecordingLogger(); + + /** Records every check as {@code " after "} and rejects {@link Integer}. */ + private final CommandRegistry registry = new CommandRegistry( + (command, registered) -> + { + this.checked.add(command.getSimpleName() + " after " + registered.size()); + if (command == Integer.class) throw new IllegalArgumentException("'java.lang.Integer' cannot be a command."); + }, + this.open::get + ); + + private final Commands commands = this.registry.forMod(this.logger); + + @Test + void registersInOrderAndShowsTheValidatorTheEarlierClasses() + { + this.commands.register(String.class); + this.commands.register(Long.class); + + assertEquals(List.of(String.class, Long.class), this.registry.classes()); + assertEquals(List.of("String after 0", "Long after 1"), this.checked); + assertEquals( + List.of("INFO: Registered the command class 'java.lang.String'.", "INFO: Registered the command class 'java.lang.Long'."), + this.logger.messages + ); + } + + @Test + void rejectedClassesAreNotRegistered() + { + IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> this.commands.register(Integer.class)); + + assertEquals("'java.lang.Integer' cannot be a command.", e.getMessage()); + assertEquals(List.of(), this.registry.classes()); + assertEquals(List.of(), this.logger.messages); + } + + @Test + void rejectsTheSameClassTwice() + { + this.commands.register(String.class); + + IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> this.commands.register(String.class)); + + assertEquals("The command class 'java.lang.String' is registered already.", e.getMessage()); + assertEquals(List.of(String.class), this.registry.classes()); + } + + @Test + void rejectsRegistrationWhileClosed() + { + this.open.set(false); + + IllegalStateException e = assertThrows(IllegalStateException.class, () -> this.commands.register(String.class)); + + assertEquals("Commands can only be registered on the main thread while the mod loads (constructor or onLoad()).", e.getMessage()); + assertEquals(List.of(), this.checked); + } +} diff --git a/core/src/test/java/dev/overlord/zomboidforge/core/commands/ModClientCommandsTest.java b/core/src/test/java/dev/overlord/zomboidforge/core/commands/ModClientCommandsTest.java new file mode 100644 index 0000000..2cbcd81 --- /dev/null +++ b/core/src/test/java/dev/overlord/zomboidforge/core/commands/ModClientCommandsTest.java @@ -0,0 +1,107 @@ +package dev.overlord.zomboidforge.core.commands; + +import dev.overlord.zomboidforge.api.ClientCommands; +import dev.overlord.zomboidforge.api.PlayerRef; +import dev.overlord.zomboidforge.core.RecordingLogger; +import dev.overlord.zomboidforge.core.runtime.MainThreadQueue; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.time.Duration; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.atomic.AtomicReference; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertThrows; + +/** The test thread is the main thread. */ +class ModClientCommandsTest +{ + private static final PlayerRef PLAYER = new PlayerRef(3, "alice"); + + /** What the sender prepared ({@code "prepare ..."}) and sent ({@code "send ... on "}). */ + private final List log = new CopyOnWriteArrayList<>(); + + /** Records both steps; rejects arguments that contain the key {@code "bad"}. */ + private final ClientCommandSender sender = (player, module, command, args) -> + { + if (args.containsKey("bad")) throw new IllegalArgumentException("'args[bad]' cannot be sent."); + + String target = player == null ? "all" : player.username(); + this.log.add("prepare " + target + " " + module + "." + command + " " + args); + + return () -> this.log.add("send " + target + " " + module + "." + command + " on " + Thread.currentThread().getName()); + }; + + private MainThreadQueue queue; + private ClientCommands commands; + + @BeforeEach + void setUp() + { + this.queue = new MainThreadQueue(Duration.ofSeconds(10)); + this.queue.bindToCurrentThread(); + + this.commands = new ModClientCommands(this.sender, this.queue.forMod("shop", new RecordingLogger())); + } + + @Test + void sendsAtOnceOnTheMainThread() + { + this.commands.send(ModClientCommandsTest.PLAYER, "Shop", "bought", Map.of("item", "Base.Axe")); + this.commands.sendToAll("Shop", "opened", Map.of()); + + String main = Thread.currentThread().getName(); + + assertEquals( + List.of( + "prepare alice Shop.bought {item=Base.Axe}", "send alice Shop.bought on " + main, + "prepare all Shop.opened {}", "send all Shop.opened on " + main + ), + this.log + ); + } + + @Test + void checksOnTheCallingThreadAndSendsOnTheMainThreadLater() throws InterruptedException + { + Thread other = Thread.ofPlatform().name("worker").start(() -> this.commands.sendToAll("Shop", "opened", Map.of())); + other.join(); + + assertEquals(List.of("prepare all Shop.opened {}"), this.log); + + this.queue.drain(); + + assertEquals(List.of("prepare all Shop.opened {}", "send all Shop.opened on " + Thread.currentThread().getName()), this.log); + } + + @Test + void rejectedArgumentsThrowToTheCallerOnAnyThread() throws InterruptedException + { + AtomicReference thrown = new AtomicReference<>(); + + Thread other = Thread.ofPlatform().start(() -> + { + try { this.commands.sendToAll("Shop", "opened", Map.of("bad", 1)); } + catch (Throwable t) { thrown.set(t); } + }); + other.join(); + + assertInstanceOf(IllegalArgumentException.class, thrown.get()); + + this.queue.drain(); + assertEquals(List.of(), this.log); + } + + @Test + void rejectsEmptyModuleAndCommand() + { + assertThrows(IllegalArgumentException.class, () -> this.commands.sendToAll("", "opened", Map.of())); + assertThrows(IllegalArgumentException.class, () -> this.commands.send(ModClientCommandsTest.PLAYER, "Shop", "", Map.of())); + assertEquals(List.of(), this.log); + } +} diff --git a/core/src/test/java/dev/overlord/zomboidforge/core/mods/ModVersionTest.java b/core/src/test/java/dev/overlord/zomboidforge/core/mods/ModVersionTest.java index 416d58b..2019e7b 100644 --- a/core/src/test/java/dev/overlord/zomboidforge/core/mods/ModVersionTest.java +++ b/core/src/test/java/dev/overlord/zomboidforge/core/mods/ModVersionTest.java @@ -26,6 +26,15 @@ class ModVersionTest assertThrows(IllegalArgumentException.class, () -> ModVersion.parse("v1.0")); } + @Test + void rejectsNumbersOutsideTheIntRange() + { + assertEquals(new ModVersion(999999999, 0, 0, null), ModVersion.parse("999999999")); + assertTrue(ModVersion.tryParse("99999999999").isEmpty()); + assertTrue(ModVersion.tryParse("1.99999999999").isEmpty()); + assertTrue(ModVersion.tryParse("1.0.99999999999").isEmpty()); + } + @Test void preReleaseSortsBeforeRelease() { diff --git a/core/src/test/java/dev/overlord/zomboidforge/core/runtime/MainThreadQueueTest.java b/core/src/test/java/dev/overlord/zomboidforge/core/runtime/MainThreadQueueTest.java index 9f23f53..5fd6161 100644 --- a/core/src/test/java/dev/overlord/zomboidforge/core/runtime/MainThreadQueueTest.java +++ b/core/src/test/java/dev/overlord/zomboidforge/core/runtime/MainThreadQueueTest.java @@ -152,6 +152,22 @@ class MainThreadQueueTest assertEquals(List.of("ERROR: A main-thread task threw. (java.lang.IllegalStateException: executed)"), this.logger.messages); } + @Test + void logsErrorsOfTasksAndRunsTheNextTask() throws Exception + { + MainThread a = this.queue.forMod("a", this.logger); + + MainThreadQueueTest.fromOtherThread(() -> { + a.execute(() -> { throw new AssertionError("failed"); }); + a.execute(() -> this.ran.add("next")); + }); + + this.queue.drain(); + + assertEquals(List.of("next"), this.ran); + assertEquals(List.of("ERROR: A main-thread task threw. (java.lang.AssertionError: failed)"), this.logger.messages); + } + @Test void closeCancelsQueuedTasksAndRejectsNewOnes() throws Exception { diff --git a/core/src/test/java/dev/overlord/zomboidforge/core/storage/ModTablesTest.java b/core/src/test/java/dev/overlord/zomboidforge/core/storage/ModTablesTest.java index 81a5959..92dac79 100644 --- a/core/src/test/java/dev/overlord/zomboidforge/core/storage/ModTablesTest.java +++ b/core/src/test/java/dev/overlord/zomboidforge/core/storage/ModTablesTest.java @@ -13,6 +13,7 @@ import org.junit.jupiter.api.io.TempDir; import java.nio.file.Files; import java.nio.file.Path; +import java.time.Duration; import java.time.Instant; import java.util.ArrayList; import java.util.List; @@ -34,6 +35,8 @@ class ModTablesTest { private enum Mode { EASY, HARD } + private enum RenamedMode { SIMPLE, HARD } + private record Everything(String text, long big, int small, double ratio, float factor, boolean flag, byte[] bytes, UUID id, Instant when, Mode mode, @Nullable Long optional) {} private record Balance(long coins) {} @@ -46,6 +49,10 @@ class ModTablesTest private record Empty() {} + private record Difficulty(Mode mode) {} + + private record RenamedDifficulty(RenamedMode mode) {} + @TempDir Path directory; @@ -90,6 +97,18 @@ class ModTablesTest assertTrue(Files.isRegularFile(this.file), "the database is created on first use"); } + @Test + void reportsUnreadableStoredValuesAsStorageExceptions() + { + this.storage("shop").table("difficulties", Difficulty.class).set("a", new Difficulty(Mode.EASY)); + + Table renamed = this.storage("shop").table("difficulties", RenamedDifficulty.class); + + StorageException e = assertThrows(StorageException.class, () -> renamed.get("a")); + assertTrue(e.getMessage().startsWith("Column 'mode' of 'RenamedDifficulty' holds 'EASY', which is not a valid 'RenamedMode': "), e.getMessage()); + assertThrows(StorageException.class, () -> renamed.forEach((key, difficulty) -> {})); + } + @Test void readsAndWritesRows() { @@ -140,6 +159,50 @@ class ModTablesTest assertEquals(9, sum); } + @Test + void rollsBackAFailedNestedTransactionThatTheOuterOneCatches() + { + ModStorage storage = this.storage("shop"); + Table balances = storage.table("balances", Balance.class); + + storage.transaction(() -> { + balances.set("a", new Balance(1)); + + assertThrows(IllegalStateException.class, () -> storage.transaction(() -> { + balances.set("a", new Balance(100)); + balances.set("b", new Balance(100)); + throw new IllegalStateException("abort"); + })); + + balances.set("c", new Balance(3)); + }); + + assertEquals(Optional.of(new Balance(1)), balances.get("a")); + assertFalse(balances.contains("b")); + assertEquals(Optional.of(new Balance(3)), balances.get("c")); + } + + @Test + void rollsBackForErrorsAndUndeclaredCheckedExceptions() + { + ModStorage storage = this.storage("shop"); + Table balances = storage.table("balances", Balance.class); + + assertThrows(AssertionError.class, () -> storage.transaction(() -> { + balances.set("a", new Balance(1)); + throw new AssertionError("abort"); + })); + assertThrows(Exception.class, () -> storage.transaction(() -> { + balances.set("b", new Balance(1)); + ModTablesTest.sneakyThrow(new Exception("abort")); + })); + + assertEquals(0, balances.count()); + } + + @SuppressWarnings("unchecked") + private static void sneakyThrow(Throwable t) throws E { throw (E) t; } + @Test void keepsModsApart() { @@ -277,6 +340,38 @@ class ModTablesTest assertTrue(balances.contains("b")); } + @Test + void backupsDoNotWaitForeverForStorage() throws Exception + { + Table balances = this.storage("shop").table("balances", Balance.class); + balances.set("a", new Balance(1)); + + CountDownLatch inside = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + Thread holder = Thread.ofPlatform().start(() -> this.storage("shop").transaction(() -> { + inside.countDown(); + ModTablesTest.await(release); + })); + + assertTrue(inside.await(5, TimeUnit.SECONDS)); + + String problem = this.database.backupStarted(Duration.ofSeconds(1)); + assertEquals("Storage was busy for 1 s; the backup runs without pausing storage, so its copy of 'zomboidforge.db' may be incomplete.", problem); + this.database.backupFinished(); + + release.countDown(); + holder.join(); + + balances.set("b", new Balance(2)); + assertTrue(balances.contains("b"), "storage stays usable after the skipped pause"); + } + + private static void await(CountDownLatch latch) + { + try { latch.await(); } + catch (InterruptedException e) { Thread.currentThread().interrupt(); } + } + @Test void rejectsBadNamesTypesAndUseAfterClose() { diff --git a/core/src/test/java/testmods/CommandMod.java b/core/src/test/java/testmods/CommandMod.java new file mode 100644 index 0000000..d26f480 --- /dev/null +++ b/core/src/test/java/testmods/CommandMod.java @@ -0,0 +1,32 @@ +package testmods; + +import dev.overlord.zomboidforge.api.Mod; + +import org.jetbrains.annotations.Nullable; + +import java.util.Map; + +/** + * Entry point that tests package into a mod jar. Registers {@link Command} in {@code onLoad()} + * and tries again in {@code onServerStarted()}, which is too late; sends a client command to + * every client there. + */ +public final class CommandMod extends Mod +{ + /** Stands in for a command class; the tests' validator accepts any class. */ + public static final class Command {} + + public volatile @Nullable RuntimeException lateRegistration; + + @Override + public void onLoad() { this.commands().register(CommandMod.Command.class); } + + @Override + public void onServerStarted() + { + try { this.commands().register(CommandMod.Command.class); } + catch (RuntimeException e) { this.lateRegistration = e; } + + this.clientCommands().sendToAll("Test", "started", Map.of("count", 1)); + } +} diff --git a/core/src/test/java/testmods/ErrorMod.java b/core/src/test/java/testmods/ErrorMod.java new file mode 100644 index 0000000..c6e7ac0 --- /dev/null +++ b/core/src/test/java/testmods/ErrorMod.java @@ -0,0 +1,16 @@ +package testmods; + +import dev.overlord.zomboidforge.api.Mod; + +/** + * Entry point that tests package into a mod jar. Its lifecycle methods throw errors, which aren't + * {@link RuntimeException}. + */ +public final class ErrorMod extends Mod +{ + @Override + public void onServerStarted() { throw new AssertionError("started"); } + + @Override + public void onStopping() { throw new NoClassDefFoundError("stopping"); } +} diff --git a/gradle-plugin/src/main/java/dev/overlord/zomboidforge/gradle/DownloadGame.java b/gradle-plugin/src/main/java/dev/overlord/zomboidforge/gradle/DownloadGame.java index b0caa11..9fca239 100644 --- a/gradle-plugin/src/main/java/dev/overlord/zomboidforge/gradle/DownloadGame.java +++ b/gradle-plugin/src/main/java/dev/overlord/zomboidforge/gradle/DownloadGame.java @@ -32,7 +32,8 @@ public abstract class DownloadGame extends DefaultTask static final String JAR = "java/projectzomboid.jar"; private static final String APP_ID = "380870"; - private static final String IMAGE = "docker.io/steamcmd/steamcmd:latest"; + // The same image as the Dockerfile's server stage. + private static final String IMAGE = "docker.io/steamcmd/steamcmd:debian-13@sha256:b0b49ef3101c304ed6e3fbc3ea930b2940d7c489563a1ebac524ad5bb46d336d"; private static final int MAX_ATTEMPTS = 3; @Internal diff --git a/gradle-plugin/src/main/java/dev/overlord/zomboidforge/gradle/GenerateModDescriptor.java b/gradle-plugin/src/main/java/dev/overlord/zomboidforge/gradle/GenerateModDescriptor.java index 7584c04..62273bb 100644 --- a/gradle-plugin/src/main/java/dev/overlord/zomboidforge/gradle/GenerateModDescriptor.java +++ b/gradle-plugin/src/main/java/dev/overlord/zomboidforge/gradle/GenerateModDescriptor.java @@ -102,7 +102,7 @@ public abstract class GenerateModDescriptor extends DefaultTask if (!dependencies.isEmpty()) { toml.append("\n[dependencies]\n"); - dependencies.forEach((id, version) -> toml.append(id).append(" = ").append(GenerateModDescriptor.string(version)).append('\n')); + dependencies.forEach((id, version) -> toml.append(GenerateModDescriptor.string(id)).append(" = ").append(GenerateModDescriptor.string(version)).append('\n')); } return toml.toString(); @@ -110,6 +110,18 @@ public abstract class GenerateModDescriptor extends DefaultTask private static String list(List values) { return values.stream().map(GenerateModDescriptor::string).collect(Collectors.joining(", ", "[", "]")); } - /** A TOML basic string. */ - private static String string(String value) { return "\"" + value.replace("\\", "\\\\").replace("\"", "\\\"") + "\""; } + /** A TOML basic string, also used for keys: backslashes, quotes, and control characters are escaped. */ + private static String string(String value) + { + StringBuilder escaped = new StringBuilder("\""); + + for (char c : value.toCharArray()) + { + if (c == '\\' || c == '"') escaped.append('\\').append(c); + else if (c < 0x20 || c == 0x7F) escaped.append(String.format("\\u%04X", (int) c)); + else escaped.append(c); + } + + return escaped.append('"').toString(); + } } diff --git a/gradle-plugin/src/main/java/dev/overlord/zomboidforge/gradle/RunServer.java b/gradle-plugin/src/main/java/dev/overlord/zomboidforge/gradle/RunServer.java index fda50ae..58916a0 100644 --- a/gradle-plugin/src/main/java/dev/overlord/zomboidforge/gradle/RunServer.java +++ b/gradle-plugin/src/main/java/dev/overlord/zomboidforge/gradle/RunServer.java @@ -3,6 +3,7 @@ package dev.overlord.zomboidforge.gradle; import org.gradle.api.DefaultTask; import org.gradle.api.GradleException; import org.gradle.api.file.DirectoryProperty; +import org.gradle.api.file.RegularFileProperty; import org.gradle.api.provider.Property; import org.gradle.api.tasks.Input; import org.gradle.api.tasks.Internal; @@ -15,6 +16,13 @@ import java.io.IOException; import java.io.InputStreamReader; import java.io.UncheckedIOException; import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardOpenOption; +import java.nio.file.attribute.PosixFileAttributeView; +import java.nio.file.attribute.PosixFilePermissions; +import java.security.SecureRandom; +import java.util.Base64; import java.util.List; import java.util.Set; import java.util.concurrent.TimeUnit; @@ -37,6 +45,8 @@ public abstract class RunServer extends DefaultTask /** Seconds the server gets to save the world after a stop request. */ private static final int STOP_TIMEOUT = 120; + private static final SecureRandom RANDOM = new SecureRandom(); + /** Contains one folder per mod, as in {@code /mods}. */ @Internal public abstract DirectoryProperty getModsDirectory(); @@ -50,9 +60,17 @@ public abstract class RunServer extends DefaultTask @Input public abstract Property getDataVolume(); - @Input + /** Not an input, so it is not stored in the task history. */ + @Internal public abstract Property getAdminPassword(); + /** Holds the generated admin password of the volume when {@link #getAdminPassword()} is not set. */ + @Internal + public abstract RegularFileProperty getAdminPasswordFile(); + + @Input + public abstract Property getServerAddress(); + @Input @Optional public abstract Property getContainerEngine(); @@ -60,23 +78,28 @@ public abstract class RunServer extends DefaultTask @TaskAction public void run() throws IOException { - String engine = Executables.containerEngine(this.getContainerEngine().getOrNull()); - String name = this.getContainerName().get(); + String engine = Executables.containerEngine(this.getContainerEngine().getOrNull()); + String name = this.getContainerName().get(); + String address = this.getServerAddress().get(); + // ADMIN_PASSWORD without a value takes the value from the engine's environment, so it is not in the command line. List command = List.of( engine, "run", "--rm", "--name", name, - "--publish", "16261:16261/udp", - "--publish", "16262:16262/udp", - "--env", "ADMIN_PASSWORD=" + this.getAdminPassword().get(), + "--publish", address + ":16261:16261/udp", + "--publish", address + ":16262:16262/udp", + "--env", "ADMIN_PASSWORD", "--volume", this.getDataVolume().get() + ":/data", "--volume", this.getModsDirectory().get().getAsFile().getAbsolutePath() + ":/forge/mods:ro,Z", this.getImage().get() ); - this.getLogger().lifecycle("Starting {} with the mod; connect to localhost:16261. Cancel the build (Ctrl+C) to stop the server.", this.getImage().get()); + ProcessBuilder builder = new ProcessBuilder(command).redirectErrorStream(true); + builder.environment().put("ADMIN_PASSWORD", this.adminPassword()); - Process process = new ProcessBuilder(command).redirectErrorStream(true).start(); + this.getLogger().lifecycle("Starting {} with the mod on {}:16261. Cancel the build (Ctrl+C) to stop the server.", this.getImage().get(), address); + + Process process = builder.start(); Thread output = new Thread(() -> RunServer.forward(process), "runServer output"); output.setDaemon(true); @@ -96,6 +119,42 @@ public abstract class RunServer extends DefaultTask } } + /** + * The configured admin password, else the one in {@link #getAdminPasswordFile()}; a random one + * is generated into the file when it does not exist. The server uses the password only when it + * creates the admin account on the volume's first start. + */ + private String adminPassword() throws IOException + { + String configured = this.getAdminPassword().getOrNull(); + if (configured != null) return configured; + + Path file = this.getAdminPasswordFile().get().getAsFile().toPath(); + + if (Files.exists(file)) return Files.readString(file, StandardCharsets.UTF_8).strip(); + + byte[] random = new byte[18]; + RunServer.RANDOM.nextBytes(random); + + String password = Base64.getUrlEncoder().withoutPadding().encodeToString(random); + + Files.createDirectories(file.getParent()); + Files.writeString(file, password, StandardCharsets.UTF_8, StandardOpenOption.CREATE_NEW); + RunServer.restrictToOwner(file); + + this.getLogger().lifecycle("Generated the admin password '{}' for '{}', kept in '{}'.", password, this.getDataVolume().get(), file); + + return password; + } + + /** Makes {@code file} readable and writable by its owner only, where the file system has POSIX permissions. */ + private static void restrictToOwner(Path file) throws IOException + { + if (!Files.getFileStore(file).supportsFileAttributeView(PosixFileAttributeView.class)) return; + + Files.setPosixFilePermissions(file, PosixFilePermissions.fromString("rw-------")); + } + /** Copies the container's output to the build output, line by line. */ private static void forward(Process process) { diff --git a/gradle-plugin/src/main/java/dev/overlord/zomboidforge/gradle/ZomboidForgeExtension.java b/gradle-plugin/src/main/java/dev/overlord/zomboidforge/gradle/ZomboidForgeExtension.java index 87e5e90..7191c08 100644 --- a/gradle-plugin/src/main/java/dev/overlord/zomboidforge/gradle/ZomboidForgeExtension.java +++ b/gradle-plugin/src/main/java/dev/overlord/zomboidforge/gradle/ZomboidForgeExtension.java @@ -64,9 +64,16 @@ public abstract class ZomboidForgeExtension /** Image for {@code runServer}. Default: the ZomboidForge image tagged "latest". */ public abstract Property getServerImage(); - /** Admin password of the {@code runServer} server. Default: "admin". */ + /** + * Admin password of the {@code runServer} server, used when its volume is created. Default: + * a random password, generated once per volume and kept in + * {@code /zomboidforge/admin-passwords/}. + */ public abstract Property getAdminPassword(); + /** Host address {@code runServer} publishes the game ports on. Default: "127.0.0.1" (this machine only); "0.0.0.0" for every interface. */ + public abstract Property getServerAddress(); + /** Volume for the {@code runServer} server's /data (world, config). Default: "zomboidforge-". */ public abstract Property getDataVolume(); diff --git a/gradle-plugin/src/main/java/dev/overlord/zomboidforge/gradle/ZomboidForgeModPlugin.java b/gradle-plugin/src/main/java/dev/overlord/zomboidforge/gradle/ZomboidForgeModPlugin.java index 27525d9..698c0e1 100644 --- a/gradle-plugin/src/main/java/dev/overlord/zomboidforge/gradle/ZomboidForgeModPlugin.java +++ b/gradle-plugin/src/main/java/dev/overlord/zomboidforge/gradle/ZomboidForgeModPlugin.java @@ -55,6 +55,7 @@ public final class ZomboidForgeModPlugin implements Plugin private static final String TOOLS = "dev.overlord.zomboidforge:mod-tools:"; private static final String TOOLS_MAIN = "dev.overlord.zomboidforge.tools.ModCheck"; private static final String DEFAULT_IMAGE = "git.security-command.org/overlord/zomboidforge:latest"; + private static final String MOD_CONFIG = "config.toml"; private static final int JAVA = 25; @Override @@ -72,7 +73,7 @@ public final class ZomboidForgeModPlugin implements Plugin extension.getApi().convention(version); extension.getSteamBranch().convention("public"); extension.getServerImage().convention(ZomboidForgeModPlugin.DEFAULT_IMAGE); - extension.getAdminPassword().convention("admin"); + extension.getServerAddress().convention("127.0.0.1"); extension.getDataVolume().convention(extension.getId().map(id -> "zomboidforge-" + id)); extension.getGameJar().convention(layout.file(project.getProviders().gradleProperty("zomboidforge.gameJar").map(File::new))); @@ -220,6 +221,8 @@ public final class ZomboidForgeModPlugin implements Plugin project.getTasks().named(LifecycleBasePlugin.ASSEMBLE_TASK_NAME, task -> task.dependsOn(modFolder, modZip)); // Trying the mod. + File passwords = new File(project.getGradle().getGradleUserHomeDir(), "zomboidforge/admin-passwords"); + project.getTasks().register("runServer", RunServer.class, task -> { task.setGroup(ZomboidForgeModPlugin.GROUP); @@ -230,14 +233,17 @@ public final class ZomboidForgeModPlugin implements Plugin task.getContainerName().set(id.map(name -> "zomboidforge-" + name)); task.getDataVolume().set(extension.getDataVolume()); task.getAdminPassword().set(extension.getAdminPassword()); + task.getAdminPasswordFile().set(layout.file(extension.getDataVolume().map(volume -> new File(passwords, volume)))); + task.getServerAddress().set(extension.getServerAddress()); task.getContainerEngine().set(extension.getContainerEngine()); }); project.getTasks().register("deployMod", Sync.class, task -> { task.setGroup(ZomboidForgeModPlugin.GROUP); - task.setDescription("Copies the mod folder into zomboidForge.deployDirectory (a server's mods directory)."); + task.setDescription("Copies the mod folder into zomboidForge.deployDirectory (a server's mods directory); keeps the server's config.toml of the mod."); task.from(modFolder); + task.preserve(filter -> filter.include(ZomboidForgeModPlugin.MOD_CONFIG)); task.into(extension.getDeployDirectory().dir(id).orElse(layout.getBuildDirectory().dir("deploy-not-configured"))); task.onlyIf("zomboidForge.deployDirectory is set", element -> extension.getDeployDirectory().isPresent()); }); diff --git a/gradle-plugin/src/test/java/dev/overlord/zomboidforge/gradle/ZomboidForgeModPluginTest.java b/gradle-plugin/src/test/java/dev/overlord/zomboidforge/gradle/ZomboidForgeModPluginTest.java index 58491de..67ce66d 100644 --- a/gradle-plugin/src/test/java/dev/overlord/zomboidforge/gradle/ZomboidForgeModPluginTest.java +++ b/gradle-plugin/src/test/java/dev/overlord/zomboidforge/gradle/ZomboidForgeModPluginTest.java @@ -22,6 +22,7 @@ import java.util.jar.JarOutputStream; import java.util.zip.ZipFile; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.objectweb.asm.Opcodes.ACC_FINAL; import static org.objectweb.asm.Opcodes.ACC_PRIVATE; @@ -140,6 +141,23 @@ class ZomboidForgeModPluginTest assertEquals(TaskOutcome.UP_TO_DATE, again.task(":checkMod").getOutcome()); } + @Test + void deployReplacesTheModButKeepsTheServerSettings() throws IOException + { + this.modProject(" deployDirectory = layout.projectDirectory.dir(\"server/mods\")", ""); + + Path deployed = this.project.resolve("server/mods/shop"); + this.write("server/mods/shop/config.toml", "limit = 7\n"); + this.write("server/mods/shop/lib/old.jar", ""); + + this.runner("deployMod").build(); + + assertTrue(Files.isRegularFile(deployed.resolve("shop.jar"))); + assertTrue(Files.isRegularFile(deployed.resolve("lib/util.jar"))); + assertFalse(Files.exists(deployed.resolve("lib/old.jar")), "files the mod no longer has are removed"); + assertEquals("limit = 7\n", Files.readString(deployed.resolve("config.toml"))); + } + @Test void checksAGameModAgainstTheGameJar() throws IOException { @@ -159,7 +177,7 @@ class ZomboidForgeModPluginTest String toml = new String(jar.getInputStream(jar.getEntry("META-INF/zomboidforge/mod.toml")).readAllBytes(), StandardCharsets.UTF_8); assertTrue(toml.contains("game = [\"42.21\"]"), toml); - assertTrue(toml.contains("[dependencies]\neconomy = \"2.0\""), toml); + assertTrue(toml.contains("[dependencies]\n\"economy\" = \"2.0\""), toml); } } @@ -189,6 +207,22 @@ class ZomboidForgeModPluginTest assertTrue(result.getOutput().contains("is written by hand; the ZomboidForge plugin generates mod.toml from zomboidForge { }."), result.getOutput()); } + @Test + void writesAnyTextAsValidToml() throws IOException + { + this.modProject(""" + name = "Shop\\tMod \\"one\\"" + dependsOn("eco.nomy", "2.0") + """, ""); + + BuildResult result = this.runner("build").buildAndFail(); + + assertTrue(result.getOutput().contains("'dependencies' contains 'eco.nomy', which is not a valid mod id."), result.getOutput()); + + String toml = Files.readString(this.project.resolve("build/generated/zomboidforge/descriptor/META-INF/zomboidforge/mod.toml")); + assertTrue(toml.contains("name = \"Shop\\u0009Mod \\\"one\\\"\""), toml); + } + @Test void failsWhenTheEntryPointIsMissing() throws IOException { diff --git a/gradle.properties b/gradle.properties index b10731a..a067448 100644 --- a/gradle.properties +++ b/gradle.properties @@ -2,8 +2,8 @@ group=dev.overlord.zomboidforge # 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 +# "42" matches every Build 42 version, "42.21" every 42.21.x build, "42.21.0" exactly. +pz.version=42 # Vanilla dedicated server jar used for compilation and patching. # Default: lib/server/java/projectzomboid.jar (relative to the root project). diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 9580f83..6750488 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -3,6 +3,7 @@ asm = "9.10.1" junit = "6.1.3" jetbrains-annotations = "26.0.2" night-config = "3.9.0" +shadow = "9.6.1" sqlite-jdbc = "3.48.0.0" # Same version as the SQLite JDBC driver bundled in Project Zomboid (sqlite-jdbc.properties). [libraries] @@ -20,3 +21,6 @@ junit-platform-launcher = { module = "org.junit.platform:junit-platform-launcher [bundles] asm = ["asm", "asm-tree", "asm-commons", "asm-util"] + +[plugins] +shadow = { id = "com.gradleup.shadow", version.ref = "shadow" } diff --git a/gradle/verification-metadata.xml b/gradle/verification-metadata.xml new file mode 100644 index 0000000..3ef9887 --- /dev/null +++ b/gradle/verification-metadata.xml @@ -0,0 +1,981 @@ + + + + true + false + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 9b7cb4a..d295f5e 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,4 +1,5 @@ distributionBase=GRADLE_USER_HOME +distributionSha256Sum=bafd5ce9cfaea0fbccfdc8439a1ac42fbd4cd9c89dc9a988228d8a2639a58e6c distributionPath=wrapper/dists distributionUrl=https\://services.gradle.org/distributions/gradle-9.8.0-bin.zip networkTimeout=10000 diff --git a/mod-tools/src/main/java/dev/overlord/zomboidforge/tools/ModCheck.java b/mod-tools/src/main/java/dev/overlord/zomboidforge/tools/ModCheck.java index f2b265a..e5942cd 100644 --- a/mod-tools/src/main/java/dev/overlord/zomboidforge/tools/ModCheck.java +++ b/mod-tools/src/main/java/dev/overlord/zomboidforge/tools/ModCheck.java @@ -174,7 +174,7 @@ public final class ModCheck if (descriptor == null) return new Result(null, null, problems); ModCheck.checkDefaultConfig(arguments.jar(), problems); - ModCheck.checkEntrypoint(arguments.jar(), descriptor, problems); + ModCheck.checkEntrypoint(arguments, descriptor, problems); List candidates = new ArrayList<>(); @@ -283,9 +283,14 @@ public final class ModCheck } } - /** The entry point and its superclasses inside the jar must lead to {@code Mod}. */ - private static void checkEntrypoint(Path jar, ModDescriptor descriptor, List problems) + /** + * The entry point must be in the jar, and its superclasses must lead to {@code Mod}. As in the + * server's class loader, superclasses come from the jar, its libraries, and then its + * dependencies. + */ + private static void checkEntrypoint(Arguments arguments, ModDescriptor descriptor, List problems) { + Path jar = arguments.jar(); String entrypoint = descriptor.entrypoint(); ClassNode type = ModCheck.classNode(jar, entrypoint.replace('.', '/'), problems); @@ -300,6 +305,11 @@ public final class ModCheck boolean constructor = type.methods.stream().anyMatch(ModCheck::isPublicNoArgConstructor); if (!constructor || (type.access & Opcodes.ACC_PUBLIC) == 0) problems.add("The entry point '" + entrypoint + "' needs to be public, with a public constructor without parameters."); + List visible = new ArrayList<>(); + visible.add(jar); + visible.addAll(arguments.libraries()); + visible.addAll(arguments.dependencies()); + ClassNode current = type; for (int depth = 0; depth < 32; depth++) @@ -309,7 +319,13 @@ public final class ModCheck if (ModCheck.MOD_CLASS.equals(superName)) return; if (superName == null) break; - ClassNode parent = ModCheck.classNode(jar, superName, problems); + ClassNode parent = ModCheck.classNode(visible, superName, problems); + + if (parent == null && !ModCheck.isJdkClass(superName)) { + problems.add("The entry point '" + entrypoint + "' extends '" + superName.replace('/', '.') + "', which is not in '" + jar.getFileName() + "', its libraries, or its dependencies."); + return; + } + if (parent == null) break; current = parent; @@ -344,6 +360,21 @@ public final class ModCheck } } + /** Whether {@code internalName} is a JDK class; none of them leads to {@code Mod}. */ + private static boolean isJdkClass(String internalName) { return ClassLoader.getPlatformClassLoader().getResource(internalName + ".class") != null; } + + /** The class from the first of {@code jars} that contains it. */ + private static @Nullable ClassNode classNode(List jars, String internalName, List problems) + { + for (Path jar : jars) + { + ClassNode node = ModCheck.classNode(jar, internalName, problems); + if (node != null) return node; + } + + return null; + } + private static @Nullable ClassNode classNode(Path jar, String internalName, List problems) { byte[] bytes = ModCheck.bytes(jar, internalName + ".class", problems); diff --git a/mod-tools/src/test/java/dev/overlord/zomboidforge/tools/ModCheckTest.java b/mod-tools/src/test/java/dev/overlord/zomboidforge/tools/ModCheckTest.java new file mode 100644 index 0000000..8506e21 --- /dev/null +++ b/mod-tools/src/test/java/dev/overlord/zomboidforge/tools/ModCheckTest.java @@ -0,0 +1,108 @@ +package dev.overlord.zomboidforge.tools; + +import org.jetbrains.annotations.Nullable; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.objectweb.asm.ClassWriter; +import org.objectweb.asm.MethodVisitor; + +import java.io.IOException; +import java.io.OutputStream; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.Map; +import java.util.jar.JarEntry; +import java.util.jar.JarOutputStream; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.objectweb.asm.Opcodes.ACC_PUBLIC; +import static org.objectweb.asm.Opcodes.ALOAD; +import static org.objectweb.asm.Opcodes.INVOKESPECIAL; +import static org.objectweb.asm.Opcodes.RETURN; +import static org.objectweb.asm.Opcodes.V25; + +class ModCheckTest +{ + private static final String MOD = "dev/overlord/zomboidforge/api/Mod"; + private static final String TOML = """ + id = "shop" + version = "1.0.0" + entrypoint = "a.Main" + api = "0.3" + """; + + @TempDir + Path directory; + + @Test + void findsEntryPointSuperclassesInLibraries() throws IOException + { + Path mod = this.jar("shop.jar", ModCheckTest.TOML, Map.of("a/Main", ModCheckTest.type("a/Main", "b/Base"))); + Path library = this.jar("base.jar", null, Map.of("b/Base", ModCheckTest.type("b/Base", ModCheckTest.MOD))); + + ModCheck.Result result = ModCheck.check(new ModCheck.Arguments(mod, null, List.of(library), List.of(), null)); + + assertEquals(List.of(), result.problems()); + } + + @Test + void reportsSuperclassesThatAreNowhere() throws IOException + { + Path mod = this.jar("shop.jar", ModCheckTest.TOML, Map.of("a/Main", ModCheckTest.type("a/Main", "b/Base"))); + + ModCheck.Result result = ModCheck.check(new ModCheck.Arguments(mod, null, List.of(), List.of(), null)); + + assertEquals(List.of("The entry point 'a.Main' extends 'b.Base', which is not in 'shop.jar', its libraries, or its dependencies."), result.problems()); + } + + @Test + void reportsEntryPointsThatDoNotExtendMod() throws IOException + { + Path mod = this.jar("shop.jar", ModCheckTest.TOML, Map.of("a/Main", ModCheckTest.type("a/Main", "java/lang/Thread"))); + + ModCheck.Result result = ModCheck.check(new ModCheck.Arguments(mod, null, List.of(), List.of(), null)); + + assertEquals(List.of("The entry point 'a.Main' does not extend 'dev.overlord.zomboidforge.api.Mod'."), result.problems()); + } + + /** A public class extending {@code superName} with a public constructor without parameters. */ + private static byte[] type(String name, String superName) + { + ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS); + writer.visit(V25, ACC_PUBLIC, name, null, superName, null); + + MethodVisitor init = writer.visitMethod(ACC_PUBLIC, "", "()V", null, null); + init.visitVarInsn(ALOAD, 0); + init.visitMethodInsn(INVOKESPECIAL, superName, "", "()V", false); + init.visitInsn(RETURN); + init.visitMaxs(0, 0); + + writer.visitEnd(); + return writer.toByteArray(); + } + + /** A jar with {@code mod.toml} (unless {@code null}) and {@code classes} (internal name to bytes). */ + private Path jar(String name, @Nullable String toml, Map classes) throws IOException + { + Path jar = this.directory.resolve(name); + + try (OutputStream file = Files.newOutputStream(jar); JarOutputStream out = new JarOutputStream(file)) + { + if (toml != null) { + out.putNextEntry(new JarEntry("META-INF/zomboidforge/mod.toml")); + out.write(toml.getBytes(StandardCharsets.UTF_8)); + out.closeEntry(); + } + + for (Map.Entry entry : classes.entrySet()) { + out.putNextEntry(new JarEntry(entry.getKey() + ".class")); + out.write(entry.getValue()); + out.closeEntry(); + } + } + + return jar; + } +} diff --git a/patcher/build.gradle.kts b/patcher/build.gradle.kts index 71a8fb1..09440ea 100644 --- a/patcher/build.gradle.kts +++ b/patcher/build.gradle.kts @@ -60,3 +60,17 @@ tasks.register("patchServerJar") { ) }) } + +// Used by ci/release.sh (Dockerfile stage game-version) to name the image before the full build. +tasks.register("printGameVersion") { + description = "Prints the game version of the server jar (pz.jar)." + group = "help" + + val serverJar = projectZomboid.serverJar + + classpath = sourceSets.main.get().runtimeClasspath + mainClass = "dev.overlord.zomboidforge.patcher.GameVersionReader" + argumentProviders.add(CommandLineArgumentProvider { + listOf(serverJar.get().asFile.absolutePath) + }) +} diff --git a/patcher/src/main/java/dev/overlord/zomboidforge/patcher/GameVersionReader.java b/patcher/src/main/java/dev/overlord/zomboidforge/patcher/GameVersionReader.java index 2cba48f..686681d 100644 --- a/patcher/src/main/java/dev/overlord/zomboidforge/patcher/GameVersionReader.java +++ b/patcher/src/main/java/dev/overlord/zomboidforge/patcher/GameVersionReader.java @@ -13,6 +13,8 @@ import org.objectweb.asm.tree.IntInsnNode; import org.objectweb.asm.tree.MethodInsnNode; import org.objectweb.asm.tree.MethodNode; +import java.io.IOException; +import java.nio.file.Path; import java.util.ArrayList; import java.util.List; @@ -32,6 +34,18 @@ public final class GameVersionReader private GameVersionReader() {} + /** Usage: {@code GameVersionReader }. Prints the jar's game version, e.g. {@code 42.21.0}. */ + static void main(String[] args) throws IOException + { + if (args.length != 1) + { + System.err.println("Usage: GameVersionReader "); + System.exit(2); + } + + System.out.println(JarPatcher.readGameVersion(Path.of(args[0]))); + } + public static GameVersion read(byte[] coreClass) { ClassNode core = new ClassNode(); diff --git a/patcher/src/main/java/dev/overlord/zomboidforge/patcher/HookArgument.java b/patcher/src/main/java/dev/overlord/zomboidforge/patcher/HookArgument.java new file mode 100644 index 0000000..dc5395c --- /dev/null +++ b/patcher/src/main/java/dev/overlord/zomboidforge/patcher/HookArgument.java @@ -0,0 +1,99 @@ +package dev.overlord.zomboidforge.patcher; + +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.Type; +import org.objectweb.asm.tree.AbstractInsnNode; +import org.objectweb.asm.tree.ClassNode; +import org.objectweb.asm.tree.LocalVariableNode; +import org.objectweb.asm.tree.MethodNode; +import org.objectweb.asm.tree.VarInsnNode; + +import java.util.List; +import java.util.Objects; + +/** + * A value of the patched method that a {@link Hook} receives as an argument. The hook's + * parameters are the types of its arguments, in order. + */ +public sealed interface HookArgument +{ + /** + * The local variable slot that holds the value at the instruction {@code at} of + * {@code method}. Fails with an {@link IllegalStateException} when the value does not + * exist there. + */ + Slot resolve(ClassNode node, MethodNode method, AbstractInsnNode at); + + /** A local variable slot and the type of the value in it. */ + record Slot(int index, Type type) + { + /** The instruction that pushes the value onto the operand stack. */ + public VarInsnNode load() { return new VarInsnNode(this.type.getOpcode(Opcodes.ILOAD), this.index); } + } + + /** + * Parameter {@code index} of the patched method, counted from 0 in the order of its + * descriptor; {@code this} of an instance method is not counted. + */ + record Parameter(int index) implements HookArgument + { + public Parameter + { + if (index < 0) throw new IllegalArgumentException("Not a parameter index: " + index); + } + + @Override + public Slot resolve(ClassNode node, MethodNode method, AbstractInsnNode at) + { + Type[] types = Type.getArgumentTypes(method.desc); + + if (this.index >= types.length) throw new IllegalStateException("'" + node.name + "." + method.name + method.desc + "' has no parameter " + this.index + "."); + + int slot = (method.access & Opcodes.ACC_STATIC) != 0 ? 0 : 1; + for (int i = 0; i < this.index; i++) slot += types[i].getSize(); + + return new Slot(slot, types[this.index]); + } + + @Override + public String toString() { return "parameter " + this.index; } + } + + /** + * The local variable {@code name} of the patched method, from its local variable table. + * Exactly one variable of that name has to be in scope at the anchor. + */ + record Local(String name) implements HookArgument + { + public Local + { + Objects.requireNonNull(name); + } + + @Override + public Slot resolve(ClassNode node, MethodNode method, AbstractInsnNode at) + { + List variables = Objects.requireNonNullElse(method.localVariables, List.of()); + int position = method.instructions.indexOf(at); + + List matches = variables.stream() + .filter(variable -> variable.name.equals(this.name)) + .filter(variable -> method.instructions.indexOf(variable.start) <= position && position < method.instructions.indexOf(variable.end)) + .toList(); + + if (matches.size() != 1) { + throw new IllegalStateException( + "Expected exactly one local variable '" + this.name + "' in scope at the anchor in '" + + node.name + "." + method.name + method.desc + "', found " + matches.size() + ); + } + + LocalVariableNode variable = matches.getFirst(); + + return new Slot(variable.index, Type.getType(variable.desc)); + } + + @Override + public String toString() { return "local '" + this.name + "'"; } + } +} diff --git a/patcher/src/main/java/dev/overlord/zomboidforge/patcher/JarPatcher.java b/patcher/src/main/java/dev/overlord/zomboidforge/patcher/JarPatcher.java index 46c67a1..c8a701b 100644 --- a/patcher/src/main/java/dev/overlord/zomboidforge/patcher/JarPatcher.java +++ b/patcher/src/main/java/dev/overlord/zomboidforge/patcher/JarPatcher.java @@ -8,6 +8,7 @@ import org.objectweb.asm.ClassReader; import org.objectweb.asm.tree.ClassNode; import java.io.IOException; +import java.io.InputStream; import java.io.UncheckedIOException; import java.nio.file.Files; import java.nio.file.Path; @@ -161,7 +162,7 @@ public final class JarPatcher { ZipEntry entry = entries.nextElement(); List patches = patchesByEntry.get(entry.getName()); - byte[] bytes = jar.getInputStream(entry).readAllBytes(); + byte[] bytes = JarPatcher.read(jar, entry); if (patches != null) { bytes = transform(jar, bytes, patches); @@ -205,10 +206,7 @@ public final class JarPatcher ClassNode node = new ClassNode(); new ClassReader(bytes).accept(node, 0); - for (ClassPatch patch : patches) { - JarPatcher.verifyAnchor(patch, node); - patch.apply(node); - } + for (ClassPatch patch : patches) JarPatcher.apply(patch, node); HierarchyClassWriter writer = new HierarchyClassWriter(name -> JarPatcher.read(jar, name + ".class")); node.accept(writer); @@ -216,9 +214,14 @@ public final class JarPatcher return writer.toByteArray(); } - private static void verifyAnchor(ClassPatch patch, ClassNode node) + /** Verifies the anchor of {@code patch}, then applies it; failures name the patch. */ + private static void apply(ClassPatch patch, ClassNode node) { - try { patch.anchor().verify(node); } + try + { + patch.anchor().verify(node); + patch.apply(node); + } catch (IllegalStateException e) { throw new IllegalStateException("'" + patch.getClass().getSimpleName() + "': " + e.getMessage(), e); } } @@ -227,7 +230,12 @@ public final class JarPatcher ZipEntry entry = jar.getEntry(entryName); if (entry == null) return null; - try { return jar.getInputStream(entry).readAllBytes(); } + try { return JarPatcher.read(jar, entry); } catch (IOException e) { throw new UncheckedIOException(e); } } + + private static byte[] read(ZipFile jar, ZipEntry entry) throws IOException + { + try (InputStream in = jar.getInputStream(entry)) { return in.readAllBytes(); } + } } diff --git a/patcher/src/main/java/dev/overlord/zomboidforge/patcher/Patches/CancellableHookPatch.java b/patcher/src/main/java/dev/overlord/zomboidforge/patcher/Patches/CancellableHookPatch.java new file mode 100644 index 0000000..1dd4858 --- /dev/null +++ b/patcher/src/main/java/dev/overlord/zomboidforge/patcher/Patches/CancellableHookPatch.java @@ -0,0 +1,93 @@ +package dev.overlord.zomboidforge.patcher.Patches; + +import dev.overlord.zomboidforge.patcher.Anchor; +import dev.overlord.zomboidforge.patcher.ClassPatch; +import dev.overlord.zomboidforge.patcher.Hook; +import dev.overlord.zomboidforge.patcher.HookArgument; + +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.Type; +import org.objectweb.asm.tree.ClassNode; +import org.objectweb.asm.tree.InsnList; +import org.objectweb.asm.tree.InsnNode; +import org.objectweb.asm.tree.JumpInsnNode; +import org.objectweb.asm.tree.LabelNode; +import org.objectweb.asm.tree.MethodInsnNode; +import org.objectweb.asm.tree.MethodNode; + +import java.util.List; +import java.util.Objects; + +/** + * Makes a call in the target class depend on a {@link Hook}: the hook runs directly before the + * call and returns {@code true} to skip it. + * + *

{@code
+ * if (!Hooks.hook(arguments)) Owner.call(...);
+ * }
+ * + * The receiver and the arguments of the call are evaluated before the hook runs; a skipped call + * pops them. The call returns {@code void}, so a skipped call leaves no value missing. The hook + * receives the {@link HookArgument}s, which are read from local variable slots. + */ +public abstract class CancellableHookPatch implements ClassPatch +{ + private final String target; + private final Anchor.Call anchor; + private final Hook hook; + private final List arguments; + + /** A hook with one parameter per element of {@code arguments}, in order, returning {@code boolean}. */ + protected CancellableHookPatch(String target, Anchor.Call anchor, Hook hook, List arguments) + { + if (!Type.getReturnType(anchor.desc()).equals(Type.VOID_TYPE)) + throw new IllegalArgumentException("Anchor call '" + anchor.owner() + "." + anchor.name() + anchor.desc() + "' must return 'V'."); + + if (anchor.name().equals("")) + throw new IllegalArgumentException("Anchor call '" + anchor.owner() + "." + anchor.name() + anchor.desc() + "' is a constructor, which cannot be skipped."); + + HookCall.checkShape(hook, arguments, Type.BOOLEAN_TYPE); + + this.target = Objects.requireNonNull(target); + this.anchor = anchor; + this.hook = hook; + this.arguments = List.copyOf(arguments); + } + + @Override + public final String target() { return this.target; } + @Override + public final Anchor.Call anchor() { return this.anchor; } + @Override + public final Hook hook() { return this.hook; } + + @Override + public final void apply(ClassNode node) + { + MethodNode method = this.anchor.in().resolve(node); + MethodInsnNode call = this.anchor.resolve(node); + InsnList code = HookCall.invoke(this.hook, this.arguments, Type.BOOLEAN_TYPE, node, method, call); + LabelNode run = new LabelNode(); + LabelNode end = new LabelNode(); + + code.add(new JumpInsnNode(Opcodes.IFEQ, run)); + code.add(CancellableHookPatch.discardOperands(call)); + code.add(new JumpInsnNode(Opcodes.GOTO, end)); + code.add(run); + + method.instructions.insertBefore(call, code); + method.instructions.insert(call, end); + } + + /** Pops the arguments of {@code call}, last first, then its receiver. */ + private static InsnList discardOperands(MethodInsnNode call) + { + InsnList code = new InsnList(); + Type[] arguments = Type.getArgumentTypes(call.desc); + + for (int i = arguments.length - 1; i >= 0; i--) code.add(new InsnNode(arguments[i].getSize() == 2 ? Opcodes.POP2 : Opcodes.POP)); + if (call.getOpcode() != Opcodes.INVOKESTATIC) code.add(new InsnNode(Opcodes.POP)); + + return code; + } +} diff --git a/patcher/src/main/java/dev/overlord/zomboidforge/patcher/Patches/HookCall.java b/patcher/src/main/java/dev/overlord/zomboidforge/patcher/Patches/HookCall.java new file mode 100644 index 0000000..be939a4 --- /dev/null +++ b/patcher/src/main/java/dev/overlord/zomboidforge/patcher/Patches/HookCall.java @@ -0,0 +1,93 @@ +package dev.overlord.zomboidforge.patcher.Patches; + +import dev.overlord.zomboidforge.patcher.Hook; +import dev.overlord.zomboidforge.patcher.HookArgument; + +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.Type; +import org.objectweb.asm.tree.AbstractInsnNode; +import org.objectweb.asm.tree.ClassNode; +import org.objectweb.asm.tree.InsnList; +import org.objectweb.asm.tree.MethodInsnNode; +import org.objectweb.asm.tree.MethodNode; + +import java.util.ArrayList; +import java.util.List; + +/** + * The call of a {@link Hook} with its {@link HookArgument}s, shared by the hook patch types. A + * hook may also take values that are already on the operand stack where it is called; those + * come first in its parameter list, followed by one parameter per argument. + */ +final class HookCall +{ + private HookCall() {} + + /** {@link #checkShape(Hook, List, List, Type)} without values on the stack. */ + static void checkShape(Hook hook, List arguments, Type returnType) { HookCall.checkShape(hook, List.of(), arguments, returnType); } + + /** + * Fails unless {@code hook} returns {@code returnType}, takes the types {@code onStack} first, + * and then one parameter per argument. The types of those parameters are checked by + * {@link #invoke}, once the arguments are resolved. + */ + static void checkShape(Hook hook, List onStack, List arguments, Type returnType) + { + Type actualReturn = Type.getReturnType(hook.desc()); + Type[] parameters = Type.getArgumentTypes(hook.desc()); + + if (!actualReturn.equals(returnType)) + throw new IllegalArgumentException("Hook '" + hook + "' must return '" + returnType.getDescriptor() + "'."); + + if (parameters.length != onStack.size() + arguments.size()) + throw new IllegalArgumentException("Hook '" + hook + "' must take " + (onStack.size() + arguments.size()) + " parameter(s): " + HookCall.describe(onStack, arguments) + "."); + + for (int i = 0; i < onStack.size(); i++) + { + if (!parameters[i].equals(onStack.get(i))) + throw new IllegalArgumentException("Parameter " + i + " of hook '" + hook + "' must be '" + onStack.get(i).getDescriptor() + "'."); + } + } + + /** {@link #invoke(Hook, List, List, Type, ClassNode, MethodNode, AbstractInsnNode)} without values on the stack. */ + static InsnList invoke(Hook hook, List arguments, Type returnType, ClassNode node, MethodNode method, AbstractInsnNode at) + { + return HookCall.invoke(hook, List.of(), arguments, returnType, node, method, at); + } + + /** + * Instructions that push {@code arguments} and call {@code hook}, for insertion directly + * before or after {@code at} in {@code method}, where the values of the types {@code onStack} + * are on top of the operand stack. Fails when the hook's descriptor does not match. + */ + static InsnList invoke(Hook hook, List onStack, List arguments, Type returnType, ClassNode node, MethodNode method, AbstractInsnNode at) + { + InsnList code = new InsnList(); + List types = new ArrayList<>(onStack); + + for (HookArgument argument : arguments) + { + HookArgument.Slot slot = argument.resolve(node, method, at); + + types.add(slot.type()); + code.add(slot.load()); + } + + String expected = Type.getMethodDescriptor(returnType, types.toArray(Type[]::new)); + if (!hook.desc().equals(expected)) + throw new IllegalStateException("Hook '" + hook + "' must have descriptor '" + expected + "' for " + HookCall.describe(onStack, arguments) + "."); + + code.add(new MethodInsnNode(Opcodes.INVOKESTATIC, hook.owner(), hook.name(), hook.desc(), false)); + + return code; + } + + /** E.g. {@code the arguments [parameter 0]} or {@code the stack value(s) [Ljava/lang/Class;] and the arguments [parameter 0]}. */ + private static String describe(List onStack, List arguments) + { + String argumentsText = "the arguments " + arguments; + if (onStack.isEmpty()) return argumentsText; + + return "the stack value(s) " + onStack.stream().map(Type::getDescriptor).toList() + " and " + argumentsText; + } +} diff --git a/patcher/src/main/java/dev/overlord/zomboidforge/patcher/Patches/HookInjectionPatch.java b/patcher/src/main/java/dev/overlord/zomboidforge/patcher/Patches/HookInjectionPatch.java index b344017..dd5210f 100644 --- a/patcher/src/main/java/dev/overlord/zomboidforge/patcher/Patches/HookInjectionPatch.java +++ b/patcher/src/main/java/dev/overlord/zomboidforge/patcher/Patches/HookInjectionPatch.java @@ -3,34 +3,40 @@ package dev.overlord.zomboidforge.patcher.Patches; import dev.overlord.zomboidforge.patcher.Anchor; import dev.overlord.zomboidforge.patcher.ClassPatch; import dev.overlord.zomboidforge.patcher.Hook; +import dev.overlord.zomboidforge.patcher.HookArgument; -import org.objectweb.asm.Opcodes; +import org.objectweb.asm.Type; import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.tree.MethodInsnNode; +import org.objectweb.asm.tree.MethodNode; +import java.util.List; import java.util.Objects; /** - * Inserts a call to a {@link Hook} directly after a call in the target class. The hook takes - * no arguments and returns nothing, so the operand stack and the stack map frames of the - * patched method stay unchanged. + * Inserts a call to a {@link Hook} directly after a call in the target class. The hook returns + * nothing and receives the {@link HookArgument}s, which are read from local variable slots, so + * the operand stack after the inserted code is the same as before it. */ public abstract class HookInjectionPatch implements ClassPatch { - private static final String HOOK_DESC = "()V"; + private final String target; + private final Anchor.Call anchor; + private final Hook hook; + private final List arguments; - private final String target; - private final Anchor.Call anchor; - private final Hook hook; + /** A hook without arguments, {@code ()V}. */ + protected HookInjectionPatch(String target, Anchor.Call anchor, Hook hook) { this(target, anchor, hook, List.of()); } - protected HookInjectionPatch(String target, Anchor.Call anchor, Hook hook) + /** A hook with one parameter per element of {@code arguments}, in order, returning {@code void}. */ + protected HookInjectionPatch(String target, Anchor.Call anchor, Hook hook, List arguments) { - if (!hook.desc().equals(HookInjectionPatch.HOOK_DESC)) - throw new IllegalArgumentException("Hook '" + hook + "' must have descriptor '" + HookInjectionPatch.HOOK_DESC + "'."); + HookCall.checkShape(hook, arguments, Type.VOID_TYPE); - this.target = Objects.requireNonNull(target); - this.anchor = Objects.requireNonNull(anchor); - this.hook = hook; + this.target = Objects.requireNonNull(target); + this.anchor = Objects.requireNonNull(anchor); + this.hook = hook; + this.arguments = List.copyOf(arguments); } @Override @@ -43,16 +49,9 @@ public abstract class HookInjectionPatch implements ClassPatch @Override public final void apply(ClassNode node) { - MethodInsnNode call = this.anchor.resolve(node); + MethodNode method = this.anchor.in().resolve(node); + MethodInsnNode call = this.anchor.resolve(node); - this.anchor.in().resolve(node).instructions.insert( - call, new MethodInsnNode( - Opcodes.INVOKESTATIC, - this.hook.owner(), - this.hook.name(), - this.hook.desc(), - false - ) - ); + method.instructions.insert(call, HookCall.invoke(this.hook, this.arguments, Type.VOID_TYPE, node, method, call)); } } diff --git a/patcher/src/main/java/dev/overlord/zomboidforge/patcher/Patches/ReturnHookPatch.java b/patcher/src/main/java/dev/overlord/zomboidforge/patcher/Patches/ReturnHookPatch.java new file mode 100644 index 0000000..d713f30 --- /dev/null +++ b/patcher/src/main/java/dev/overlord/zomboidforge/patcher/Patches/ReturnHookPatch.java @@ -0,0 +1,75 @@ +package dev.overlord.zomboidforge.patcher.Patches; + +import dev.overlord.zomboidforge.patcher.Anchor; +import dev.overlord.zomboidforge.patcher.ClassPatch; +import dev.overlord.zomboidforge.patcher.Hook; +import dev.overlord.zomboidforge.patcher.HookArgument; + +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.Type; +import org.objectweb.asm.tree.AbstractInsnNode; +import org.objectweb.asm.tree.ClassNode; +import org.objectweb.asm.tree.MethodNode; +import org.objectweb.asm.util.Printer; + +import java.util.List; +import java.util.Locale; +import java.util.Objects; + +/** + * Passes the value that one return instruction of a method is about to return to a + * {@link Hook}, which returns the value to return instead: + * + *
{@code
+ * return Hooks.hook(value, arguments);
+ * }
+ * + * The anchor is a {@link Anchor.Sequence} whose last instruction is that return instruction; + * the instructions before it identify which return of the method is meant. The hook's first + * parameter and its return type are the method's return type, followed by one parameter per + * {@link HookArgument}. Other returns of the method are unchanged. + */ +public abstract class ReturnHookPatch implements ClassPatch +{ + private final String target; + private final Anchor.Sequence anchor; + private final Hook hook; + private final List arguments; + private final Type returned; + + protected ReturnHookPatch(String target, Anchor.Sequence anchor, Hook hook, List arguments) + { + Type returned = Type.getReturnType(anchor.in().desc()); + + if (returned.equals(Type.VOID_TYPE)) + throw new IllegalArgumentException("Method '" + anchor.in().name() + anchor.in().desc() + "' returns no value."); + + HookCall.checkShape(hook, List.of(returned), arguments, returned); + + this.target = Objects.requireNonNull(target); + this.anchor = anchor; + this.hook = hook; + this.arguments = List.copyOf(arguments); + this.returned = returned; + } + + @Override + public final String target() { return this.target; } + @Override + public final Anchor.Sequence anchor() { return this.anchor; } + @Override + public final Hook hook() { return this.hook; } + + @Override + public final void apply(ClassNode node) + { + MethodNode method = this.anchor.in().resolve(node); + AbstractInsnNode instruction = this.anchor.resolve(node).getLast(); + int returnOpcode = this.returned.getOpcode(Opcodes.IRETURN); + + if (instruction.getOpcode() != returnOpcode) + throw new IllegalStateException("The last instruction of the anchor must be '" + Printer.OPCODES[returnOpcode].toLowerCase(Locale.ROOT) + "'."); + + method.instructions.insertBefore(instruction, HookCall.invoke(this.hook, List.of(this.returned), this.arguments, this.returned, node, method, instruction)); + } +} diff --git a/patcher/src/test/java/dev/overlord/zomboidforge/patcher/CancellableHookPatchTest.java b/patcher/src/test/java/dev/overlord/zomboidforge/patcher/CancellableHookPatchTest.java new file mode 100644 index 0000000..43065db --- /dev/null +++ b/patcher/src/test/java/dev/overlord/zomboidforge/patcher/CancellableHookPatchTest.java @@ -0,0 +1,196 @@ +package dev.overlord.zomboidforge.patcher; + +import dev.overlord.zomboidforge.patcher.Patches.CancellableHookPatch; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.objectweb.asm.ClassWriter; +import org.objectweb.asm.MethodVisitor; +import org.objectweb.asm.Type; + +import java.net.URL; +import java.net.URLClassLoader; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.objectweb.asm.Opcodes.ACC_PUBLIC; +import static org.objectweb.asm.Opcodes.ACC_STATIC; +import static org.objectweb.asm.Opcodes.ALOAD; +import static org.objectweb.asm.Opcodes.INVOKESTATIC; +import static org.objectweb.asm.Opcodes.INVOKEVIRTUAL; +import static org.objectweb.asm.Opcodes.LLOAD; +import static org.objectweb.asm.Opcodes.RETURN; +import static org.objectweb.asm.Opcodes.V25; + +class CancellableHookPatchTest +{ + private static final String CALLS = Type.getInternalName(CancellableHookPatchTest.Calls.class); + private static final String CALLS_DESC = Type.getDescriptor(CancellableHookPatchTest.Calls.class); + + @TempDir + Path dir; + + /** Stands in for the anchor calls and the hooks, and records the calls. */ + public static final class Calls + { + public static final List LOG = new ArrayList<>(); + + /** What the hooks return. */ + public static boolean cancel; + + public static void staticCall(long number, String text) { Calls.LOG.add("call " + number + " " + text); } + + public void virtualCall(String text) { Calls.LOG.add("virtual " + text); } + + public static void after() { Calls.LOG.add("after"); } + + public static boolean staticHook(String text, long number) + { + Calls.LOG.add("hook " + text + " " + number); + + return Calls.cancel; + } + + public static boolean virtualHook(String text) + { + Calls.LOG.add("virtual hook " + text); + + return Calls.cancel; + } + } + + /** Skips {@code Calls.staticCall(number, text)} in {@code runStatic}; the hook gets {@code text} and {@code number}. */ + private static final class StaticCallPatch extends CancellableHookPatch + { + StaticCallPatch() { + super( + "t/Target", + new Anchor.Call(new Anchor.Method("runStatic", "(JLjava/lang/String;)V"), CancellableHookPatchTest.CALLS, "staticCall", "(JLjava/lang/String;)V"), + new Hook(CancellableHookPatchTest.CALLS, "staticHook", "(Ljava/lang/String;J)Z"), + List.of(new HookArgument.Parameter(1), new HookArgument.Parameter(0)) + ); + } + } + + /** Skips {@code calls.virtualCall(text)} in {@code runVirtual}; the hook gets {@code text}. */ + private static final class VirtualCallPatch extends CancellableHookPatch + { + VirtualCallPatch() { + super( + "t/Target", + new Anchor.Call(new Anchor.Method("runVirtual", "(" + CancellableHookPatchTest.CALLS_DESC + "Ljava/lang/String;)V"), CancellableHookPatchTest.CALLS, "virtualCall", "(Ljava/lang/String;)V"), + new Hook(CancellableHookPatchTest.CALLS, "virtualHook", "(Ljava/lang/String;)Z"), + List.of(new HookArgument.Parameter(1)) + ); + } + } + + /** + * {@code static runStatic(long number, String text)}: {@code Calls.staticCall(number, text); Calls.after();} + * and {@code static runVirtual(Calls calls, String text)}: {@code calls.virtualCall(text); Calls.after();}. + */ + private static byte[] target() + { + ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES); + cw.visit(V25, ACC_PUBLIC, "t/Target", null, "java/lang/Object", null); + + MethodVisitor runStatic = cw.visitMethod(ACC_PUBLIC | ACC_STATIC, "runStatic", "(JLjava/lang/String;)V", null, null); + runStatic.visitVarInsn(LLOAD, 0); + runStatic.visitVarInsn(ALOAD, 2); + runStatic.visitMethodInsn(INVOKESTATIC, CancellableHookPatchTest.CALLS, "staticCall", "(JLjava/lang/String;)V", false); + runStatic.visitMethodInsn(INVOKESTATIC, CancellableHookPatchTest.CALLS, "after", "()V", false); + runStatic.visitInsn(RETURN); + runStatic.visitMaxs(0, 0); + + MethodVisitor runVirtual = cw.visitMethod(ACC_PUBLIC | ACC_STATIC, "runVirtual", "(" + CancellableHookPatchTest.CALLS_DESC + "Ljava/lang/String;)V", null, null); + runVirtual.visitVarInsn(ALOAD, 0); + runVirtual.visitVarInsn(ALOAD, 1); + runVirtual.visitMethodInsn(INVOKEVIRTUAL, CancellableHookPatchTest.CALLS, "virtualCall", "(Ljava/lang/String;)V", false); + runVirtual.visitMethodInsn(INVOKESTATIC, CancellableHookPatchTest.CALLS, "after", "()V", false); + runVirtual.visitInsn(RETURN); + runVirtual.visitMaxs(0, 0); + + cw.visitEnd(); + return cw.toByteArray(); + } + + /** Patches {@link #target()} with both patches and runs {@code runStatic(7, "a")} and {@code runVirtual(new Calls(), "b")}. */ + private List runPatched(boolean cancel) throws Exception + { + Path in = this.dir.resolve("in.jar"); + Path out = this.dir.resolve("patched.jar"); + + try (ZipOutputStream zip = new ZipOutputStream(Files.newOutputStream(in))) + { + zip.putNextEntry(new ZipEntry("t/Target.class")); + zip.write(CancellableHookPatchTest.target()); + zip.closeEntry(); + } + + assertEquals(1, new JarPatcher(List.of(new StaticCallPatch(), new VirtualCallPatch())).patch(in, out)); + + CancellableHookPatchTest.Calls.cancel = cancel; + + try (URLClassLoader loader = new URLClassLoader(new URL[]{out.toUri().toURL()}, CancellableHookPatchTest.class.getClassLoader())) + { + Class target = loader.loadClass("t.Target"); + + target.getMethod("runStatic", long.class, String.class).invoke(null, 7L, "a"); + target.getMethod("runVirtual", CancellableHookPatchTest.Calls.class, String.class).invoke(null, new CancellableHookPatchTest.Calls(), "b"); + } + + return CancellableHookPatchTest.Calls.LOG; + } + + @BeforeEach + void clearLog() { CancellableHookPatchTest.Calls.LOG.clear(); } + + @Test + void runsTheCallWhenTheHookReturnsFalse() throws Exception + { + assertEquals( + List.of("hook a 7", "call 7 a", "after", "virtual hook b", "virtual b", "after"), + this.runPatched(false) + ); + } + + @Test + void skipsTheCallWhenTheHookReturnsTrue() throws Exception + { + assertEquals( + List.of("hook a 7", "after", "virtual hook b", "after"), + this.runPatched(true) + ); + } + + @Test + void rejectsAnchorCallThatReturnsAValue() + { + Anchor.Call anchor = new Anchor.Call(new Anchor.Method("run", "()V"), "t/Dep", "value", "()I"); + + assertThrows(IllegalArgumentException.class, () -> new CancellableHookPatch("t/Target", anchor, new Hook("t/Hooks", "hook", "()Z"), List.of()) {}); + } + + @Test + void rejectsConstructorAnchor() + { + Anchor.Call anchor = new Anchor.Call(new Anchor.Method("run", "()V"), "t/Dep", "", "()V"); + + assertThrows(IllegalArgumentException.class, () -> new CancellableHookPatch("t/Target", anchor, new Hook("t/Hooks", "hook", "()Z"), List.of()) {}); + } + + @Test + void rejectsHookThatDoesNotReturnBoolean() + { + Anchor.Call anchor = new Anchor.Call(new Anchor.Method("run", "()V"), "t/Dep", "call", "()V"); + + assertThrows(IllegalArgumentException.class, () -> new CancellableHookPatch("t/Target", anchor, new Hook("t/Hooks", "hook", "()V"), List.of()) {}); + } +} diff --git a/patcher/src/test/java/dev/overlord/zomboidforge/patcher/HookArgumentTest.java b/patcher/src/test/java/dev/overlord/zomboidforge/patcher/HookArgumentTest.java new file mode 100644 index 0000000..3ef308d --- /dev/null +++ b/patcher/src/test/java/dev/overlord/zomboidforge/patcher/HookArgumentTest.java @@ -0,0 +1,117 @@ +package dev.overlord.zomboidforge.patcher; + +import org.junit.jupiter.api.Test; +import org.objectweb.asm.Type; +import org.objectweb.asm.tree.ClassNode; +import org.objectweb.asm.tree.InsnNode; +import org.objectweb.asm.tree.LabelNode; +import org.objectweb.asm.tree.LocalVariableNode; +import org.objectweb.asm.tree.MethodNode; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.objectweb.asm.Opcodes.ACC_PUBLIC; +import static org.objectweb.asm.Opcodes.ACC_STATIC; +import static org.objectweb.asm.Opcodes.ALOAD; +import static org.objectweb.asm.Opcodes.ASM9; +import static org.objectweb.asm.Opcodes.LLOAD; +import static org.objectweb.asm.Opcodes.NOP; +import static org.objectweb.asm.Opcodes.RETURN; + +class HookArgumentTest +{ + private static final String STRING = "Ljava/lang/String;"; + + private static ClassNode target() + { + ClassNode node = new ClassNode(); + node.name = "t/Target"; + + return node; + } + + @Test + void parameterSlotsSkipThisAndCountWideTypesTwice() + { + MethodNode staticMethod = new MethodNode(ASM9, ACC_PUBLIC | ACC_STATIC, "run", "(JLjava/lang/String;)V", null, null); + MethodNode instanceMethod = new MethodNode(ASM9, ACC_PUBLIC, "run", "(JLjava/lang/String;)V", null, null); + ClassNode node = HookArgumentTest.target(); + + assertEquals(new HookArgument.Slot(0, Type.LONG_TYPE), new HookArgument.Parameter(0).resolve(node, staticMethod, new InsnNode(RETURN))); + assertEquals(new HookArgument.Slot(2, Type.getType(HookArgumentTest.STRING)), new HookArgument.Parameter(1).resolve(node, staticMethod, new InsnNode(RETURN))); + assertEquals(new HookArgument.Slot(3, Type.getType(HookArgumentTest.STRING)), new HookArgument.Parameter(1).resolve(node, instanceMethod, new InsnNode(RETURN))); + } + + @Test + void slotLoadsWithTheOpcodeOfItsType() + { + assertEquals(LLOAD, new HookArgument.Slot(0, Type.LONG_TYPE).load().getOpcode()); + assertEquals(ALOAD, new HookArgument.Slot(2, Type.getType(HookArgumentTest.STRING)).load().getOpcode()); + } + + @Test + void reportsMissingParameter() + { + MethodNode method = new MethodNode(ASM9, ACC_STATIC, "run", "(I)V", null, null); + + IllegalStateException e = assertThrows( + IllegalStateException.class, + () -> new HookArgument.Parameter(1).resolve(HookArgumentTest.target(), method, new InsnNode(RETURN)) + ); + + assertEquals("'t/Target.run(I)V' has no parameter 1.", e.getMessage()); + } + + @Test + void rejectsNegativeParameterIndex() + { + assertThrows(IllegalArgumentException.class, () -> new HookArgument.Parameter(-1)); + } + + /** {@code run()}: {@code nop} (before), label, {@code nop} (inside), label, {@code return}; {@code name} is in scope only inside. */ + @Test + void localResolvesOnlyWhereItIsInScope() + { + MethodNode method = new MethodNode(ASM9, ACC_STATIC, "run", "()V", null, null); + InsnNode before = new InsnNode(NOP); + InsnNode inside = new InsnNode(NOP); + LabelNode start = new LabelNode(); + LabelNode end = new LabelNode(); + + method.instructions.add(before); + method.instructions.add(start); + method.instructions.add(inside); + method.instructions.add(end); + method.instructions.add(new InsnNode(RETURN)); + method.localVariables.add(new LocalVariableNode("name", HookArgumentTest.STRING, null, start, end, 4)); + + HookArgument.Local name = new HookArgument.Local("name"); + + assertEquals(new HookArgument.Slot(4, Type.getType(HookArgumentTest.STRING)), name.resolve(HookArgumentTest.target(), method, inside)); + + IllegalStateException e = assertThrows(IllegalStateException.class, () -> name.resolve(HookArgumentTest.target(), method, before)); + assertEquals("Expected exactly one local variable 'name' in scope at the anchor in 't/Target.run()V', found 0", e.getMessage()); + } + + @Test + void localRejectsTwoVariablesOfTheSameNameInScope() + { + MethodNode method = new MethodNode(ASM9, ACC_STATIC, "run", "()V", null, null); + InsnNode inside = new InsnNode(NOP); + LabelNode start = new LabelNode(); + LabelNode end = new LabelNode(); + + method.instructions.add(start); + method.instructions.add(inside); + method.instructions.add(end); + method.localVariables.add(new LocalVariableNode("name", HookArgumentTest.STRING, null, start, end, 0)); + method.localVariables.add(new LocalVariableNode("name", "I", null, start, end, 1)); + + IllegalStateException e = assertThrows( + IllegalStateException.class, + () -> new HookArgument.Local("name").resolve(HookArgumentTest.target(), method, inside) + ); + + assertEquals("Expected exactly one local variable 'name' in scope at the anchor in 't/Target.run()V', found 2", e.getMessage()); + } +} diff --git a/patcher/src/test/java/dev/overlord/zomboidforge/patcher/HookInjectionPatchTest.java b/patcher/src/test/java/dev/overlord/zomboidforge/patcher/HookInjectionPatchTest.java index e17c6cd..8c97a4f 100644 --- a/patcher/src/test/java/dev/overlord/zomboidforge/patcher/HookInjectionPatchTest.java +++ b/patcher/src/test/java/dev/overlord/zomboidforge/patcher/HookInjectionPatchTest.java @@ -2,15 +2,19 @@ package dev.overlord.zomboidforge.patcher; import dev.overlord.zomboidforge.patcher.Patches.HookInjectionPatch; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import org.objectweb.asm.ClassWriter; +import org.objectweb.asm.Label; import org.objectweb.asm.MethodVisitor; +import org.objectweb.asm.Type; import java.net.URL; import java.net.URLClassLoader; import java.nio.file.Files; import java.nio.file.Path; +import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.zip.ZipEntry; @@ -20,6 +24,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.objectweb.asm.Opcodes.ACC_PUBLIC; import static org.objectweb.asm.Opcodes.ACC_STATIC; +import static org.objectweb.asm.Opcodes.ASTORE; import static org.objectweb.asm.Opcodes.DUP; import static org.objectweb.asm.Opcodes.GETSTATIC; import static org.objectweb.asm.Opcodes.INVOKESPECIAL; @@ -171,4 +176,105 @@ class HookInjectionPatchTest "t/Target", HookInjectionPatchTest.ANCHOR, new Hook("t/Hooks", "hook", "(I)V") ) {}); } + + @Test + void rejectsHookThatReturnsAValue() + { + assertThrows(IllegalArgumentException.class, () -> new HookInjectionPatch( + "t/Target", HookInjectionPatchTest.ANCHOR, new Hook("t/Hooks", "hook", "()Z") + ) {}); + } + + // Hooks with arguments + + private static final String CALLS = Type.getInternalName(HookInjectionPatchTest.Calls.class); + + private static final Anchor.Call ARGUMENTS_ANCHOR = new Anchor.Call( + new Anchor.Method("run", "(JLjava/lang/String;)V"), HookInjectionPatchTest.CALLS, "anchor", "()V" + ); + + private static final List ARGUMENTS = List.of( + new HookArgument.Parameter(1), + new HookArgument.Parameter(0), + new HookArgument.Local("word") + ); + + /** Stands in for the anchor call and the hook of {@link ArgumentPatch} and records the calls. */ + public static final class Calls + { + public static final List LOG = new ArrayList<>(); + + private Calls() {} + + public static void anchor() { Calls.LOG.add("anchor"); } + + public static void hook(String text, long number, String word) { Calls.LOG.add("hook " + text + " " + number + " " + word); } + } + + private static final class ArgumentPatch extends HookInjectionPatch + { + ArgumentPatch(String hookDesc) { + super("t/Target", HookInjectionPatchTest.ARGUMENTS_ANCHOR, new Hook(HookInjectionPatchTest.CALLS, "hook", hookDesc), HookInjectionPatchTest.ARGUMENTS); + } + } + + /** {@code static run(long number, String text)}: {@code String word = "local"; Calls.anchor();}. */ + private static byte[] argumentsTarget() + { + ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES); + cw.visit(V25, ACC_PUBLIC, "t/Target", null, "java/lang/Object", null); + + Label start = new Label(); + Label end = new Label(); + + MethodVisitor run = cw.visitMethod(ACC_PUBLIC | ACC_STATIC, "run", "(JLjava/lang/String;)V", null, null); + run.visitLdcInsn("local"); + run.visitVarInsn(ASTORE, 3); + run.visitLabel(start); + run.visitMethodInsn(INVOKESTATIC, HookInjectionPatchTest.CALLS, "anchor", "()V", false); + run.visitInsn(RETURN); + run.visitLabel(end); + run.visitLocalVariable("word", "Ljava/lang/String;", null, start, end, 3); + run.visitMaxs(0, 0); + + cw.visitEnd(); + return cw.toByteArray(); + } + + @BeforeEach + void clearLog() { HookInjectionPatchTest.Calls.LOG.clear(); } + + @Test + void passesParametersAndLocalsToHook() throws Exception + { + Path in = this.jar(Map.of("t/Target.class", HookInjectionPatchTest.argumentsTarget())); + Path out = this.dir.resolve("patched.jar"); + + new JarPatcher(List.of(new ArgumentPatch("(Ljava/lang/String;JLjava/lang/String;)V"))).patch(in, out); + + try (URLClassLoader loader = new URLClassLoader(new URL[]{out.toUri().toURL()}, HookInjectionPatchTest.class.getClassLoader())) + { + loader.loadClass("t.Target").getMethod("run", long.class, String.class).invoke(null, 7L, "text"); + } + + assertEquals(List.of("anchor", "hook text 7 local"), HookInjectionPatchTest.Calls.LOG); + } + + @Test + void reportsHookWhoseParametersDoNotMatchTheArguments() throws Exception + { + Path in = this.jar(Map.of("t/Target.class", HookInjectionPatchTest.argumentsTarget())); + ArgumentPatch patch = new ArgumentPatch("(Ljava/lang/String;ILjava/lang/String;)V"); + + IllegalStateException e = assertThrows( + IllegalStateException.class, + () -> new JarPatcher(List.of(patch)).patch(in, this.dir.resolve("out.jar")) + ); + + assertEquals( + "'ArgumentPatch': Hook '" + patch.hook() + "' must have descriptor '(Ljava/lang/String;JLjava/lang/String;)V'" + + " for the arguments [parameter 1, parameter 0, local 'word'].", + e.getMessage() + ); + } } diff --git a/patcher/src/test/java/dev/overlord/zomboidforge/patcher/ReturnHookPatchTest.java b/patcher/src/test/java/dev/overlord/zomboidforge/patcher/ReturnHookPatchTest.java new file mode 100644 index 0000000..1ef388b --- /dev/null +++ b/patcher/src/test/java/dev/overlord/zomboidforge/patcher/ReturnHookPatchTest.java @@ -0,0 +1,185 @@ +package dev.overlord.zomboidforge.patcher; + +import dev.overlord.zomboidforge.patcher.Patches.ReturnHookPatch; + +import org.jetbrains.annotations.Nullable; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.objectweb.asm.ClassWriter; +import org.objectweb.asm.Label; +import org.objectweb.asm.MethodVisitor; +import org.objectweb.asm.Type; + +import java.net.URL; +import java.net.URLClassLoader; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.objectweb.asm.Opcodes.ACC_PUBLIC; +import static org.objectweb.asm.Opcodes.ACC_STATIC; +import static org.objectweb.asm.Opcodes.ACONST_NULL; +import static org.objectweb.asm.Opcodes.ALOAD; +import static org.objectweb.asm.Opcodes.ARETURN; +import static org.objectweb.asm.Opcodes.IFEQ; +import static org.objectweb.asm.Opcodes.ILOAD; +import static org.objectweb.asm.Opcodes.LRETURN; +import static org.objectweb.asm.Opcodes.V25; + +class ReturnHookPatchTest +{ + private static final String CALLS = Type.getInternalName(ReturnHookPatchTest.Calls.class); + + private static final Anchor.Method PICK = new Anchor.Method("pick", "(Ljava/lang/String;Z)Ljava/lang/String;"); + private static final Anchor.Method WIDE = new Anchor.Method("wide", "()J"); + + @TempDir + Path dir; + + /** The hooks. */ + public static final class Calls + { + private Calls() {} + + public static String replaceNull(@Nullable String value, String input) { return "hook " + value + " " + input; } + + public static long doubled(long value) { return value * 2; } + } + + /** Replaces the {@code null} that {@code pick} returns; the hook gets {@code input}. */ + private static final class NullPatch extends ReturnHookPatch + { + NullPatch() { + super( + "t/Target", + new Anchor.Sequence(ReturnHookPatchTest.PICK, new Anchor.Instruction.Opcode(ACONST_NULL), new Anchor.Instruction.Opcode(ARETURN)), + new Hook(ReturnHookPatchTest.CALLS, "replaceNull", "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;"), + List.of(new HookArgument.Parameter(0)) + ); + } + } + + /** Doubles the {@code long} that {@code wide} returns. */ + private static final class WidePatch extends ReturnHookPatch + { + WidePatch() { + super( + "t/Target", + new Anchor.Sequence(ReturnHookPatchTest.WIDE, new Anchor.Instruction.Constant(5L), new Anchor.Instruction.Opcode(LRETURN)), + new Hook(ReturnHookPatchTest.CALLS, "doubled", "(J)J"), + List.of() + ); + } + } + + /** Anchored on {@code aconst_null} alone, not on a return instruction. */ + private static final class NoReturnPatch extends ReturnHookPatch + { + NoReturnPatch() { + super( + "t/Target", + new Anchor.Sequence(ReturnHookPatchTest.PICK, new Anchor.Instruction.Opcode(ACONST_NULL)), + new Hook(ReturnHookPatchTest.CALLS, "replaceNull", "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;"), + List.of(new HookArgument.Parameter(0)) + ); + } + } + + /** + * {@code static pick(String input, boolean keep)}: {@code return keep ? input : null;} and + * {@code static wide()}: {@code return 5L;}. + */ + private Path target() throws Exception + { + ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES); + cw.visit(V25, ACC_PUBLIC, "t/Target", null, "java/lang/Object", null); + + Label returnNull = new Label(); + + MethodVisitor pick = cw.visitMethod(ACC_PUBLIC | ACC_STATIC, "pick", ReturnHookPatchTest.PICK.desc(), null, null); + pick.visitVarInsn(ILOAD, 1); + pick.visitJumpInsn(IFEQ, returnNull); + pick.visitVarInsn(ALOAD, 0); + pick.visitInsn(ARETURN); + pick.visitLabel(returnNull); + pick.visitInsn(ACONST_NULL); + pick.visitInsn(ARETURN); + pick.visitMaxs(0, 0); + + MethodVisitor wide = cw.visitMethod(ACC_PUBLIC | ACC_STATIC, "wide", ReturnHookPatchTest.WIDE.desc(), null, null); + wide.visitLdcInsn(5L); + wide.visitInsn(LRETURN); + wide.visitMaxs(0, 0); + + cw.visitEnd(); + + Path jar = this.dir.resolve("in.jar"); + + try (ZipOutputStream zip = new ZipOutputStream(Files.newOutputStream(jar))) + { + zip.putNextEntry(new ZipEntry("t/Target.class")); + zip.write(cw.toByteArray()); + zip.closeEntry(); + } + + return jar; + } + + @Test + void replacesTheAnchoredReturnValueOnly() throws Exception + { + Path out = this.dir.resolve("patched.jar"); + + new JarPatcher(List.of(new NullPatch(), new WidePatch())).patch(this.target(), out); + + try (URLClassLoader loader = new URLClassLoader(new URL[]{out.toUri().toURL()}, ReturnHookPatchTest.class.getClassLoader())) + { + Class target = loader.loadClass("t.Target"); + + assertEquals("kept", target.getMethod("pick", String.class, boolean.class).invoke(null, "kept", true)); + assertEquals("hook null input", target.getMethod("pick", String.class, boolean.class).invoke(null, "input", false)); + assertEquals(10L, target.getMethod("wide").invoke(null)); + } + } + + @Test + void reportsAnchorThatDoesNotEndInAReturn() throws Exception + { + Path in = this.target(); + + IllegalStateException e = assertThrows( + IllegalStateException.class, + () -> new JarPatcher(List.of(new NoReturnPatch())).patch(in, this.dir.resolve("out.jar")) + ); + + assertEquals("'NoReturnPatch': The last instruction of the anchor must be 'areturn'.", e.getMessage()); + } + + @Test + void rejectsMethodWithoutReturnValue() + { + Anchor.Sequence anchor = new Anchor.Sequence(new Anchor.Method("run", "()V"), new Anchor.Instruction.Opcode(ARETURN)); + + assertThrows(IllegalArgumentException.class, () -> new ReturnHookPatch("t/Target", anchor, new Hook("t/Hooks", "hook", "()V"), List.of()) {}); + } + + @Test + void rejectsHookWhoseFirstParameterIsNotTheReturnType() + { + Anchor.Sequence anchor = new Anchor.Sequence(ReturnHookPatchTest.WIDE, new Anchor.Instruction.Opcode(LRETURN)); + + assertThrows(IllegalArgumentException.class, () -> new ReturnHookPatch("t/Target", anchor, new Hook("t/Hooks", "hook", "(I)J"), List.of()) {}); + } + + @Test + void rejectsHookThatReturnsAnotherType() + { + Anchor.Sequence anchor = new Anchor.Sequence(ReturnHookPatchTest.WIDE, new Anchor.Instruction.Opcode(LRETURN)); + + assertThrows(IllegalArgumentException.class, () -> new ReturnHookPatch("t/Target", anchor, new Hook("t/Hooks", "hook", "(J)I"), List.of()) {}); + } +}