From 30b18b84dd592ff2dd07fa68475f5efcca69a59d Mon Sep 17 00:00:00 2001
From: ampynjord <82981605+ampynjord@users.noreply.github.com>
Date: Thu, 19 Nov 2026 12:19:14 +0100
Subject: [PATCH 01/47] Experimental Linux dedicated server: Wine + Madeira
Dock in Docker
The Windows game runs under Wine on Linux; Valve's own client library is driven by
Madeira Dock (real sign-in and licence check, no Steam desktop). Launcher: a Wine/Dock
start mode and a stop file for a clean container stop. server/ holds the Dockerfile,
Compose files, entrypoint (install-game, login, import-save, status, run), the Steam QR
sign-in helper, the Vulkan no-op layer, tests and docs; a workflow builds and smoke-tests
the image and publishes to GHCR only on a manual run.
---
.github/workflows/dedicated-server.yml | 128 +++++++++++++++
launcher/Core.cs | 30 +++-
launcher/MainForm.cs | 15 +-
launcher/Server.cs | 12 ++
server/.dockerignore | 6 +
server/.env.example | 22 +++
server/.gitattributes | 2 +
server/.gitignore | 4 +
server/Dockerfile | 76 +++++++++
server/README.md | 69 ++++++++
server/compose.build.yaml | 8 +
server/compose.gpu.yaml | 9 ++
server/compose.yaml | 45 ++++++
server/config/settings.lua | 174 ++++++++++++++++++++
server/docs/ARCHITECTURE.md | 45 ++++++
server/docs/OPERATIONS.md | 36 +++++
server/scripts/entrypoint.sh | 193 +++++++++++++++++++++++
server/scripts/healthcheck.sh | 9 ++
server/scripts/lib.sh | 32 ++++
server/scripts/mklite.py | 178 +++++++++++++++++++++
server/scripts/steam_session.py | 134 ++++++++++++++++
server/tests/__init__.py | 0
server/tests/check.sh | 30 ++++
server/tests/selftest_lite.py | 57 +++++++
server/tests/test_steam_session.py | 66 ++++++++
server/vklayer/VkLayer_mpf_nulldraw.json | 14 ++
server/vklayer/vk_nulldraw.c | 171 ++++++++++++++++++++
27 files changed, 1563 insertions(+), 2 deletions(-)
create mode 100644 .github/workflows/dedicated-server.yml
create mode 100644 server/.dockerignore
create mode 100644 server/.env.example
create mode 100644 server/.gitattributes
create mode 100644 server/.gitignore
create mode 100644 server/Dockerfile
create mode 100644 server/README.md
create mode 100644 server/compose.build.yaml
create mode 100644 server/compose.gpu.yaml
create mode 100644 server/compose.yaml
create mode 100644 server/config/settings.lua
create mode 100644 server/docs/ARCHITECTURE.md
create mode 100644 server/docs/OPERATIONS.md
create mode 100644 server/scripts/entrypoint.sh
create mode 100644 server/scripts/healthcheck.sh
create mode 100644 server/scripts/lib.sh
create mode 100644 server/scripts/mklite.py
create mode 100644 server/scripts/steam_session.py
create mode 100644 server/tests/__init__.py
create mode 100644 server/tests/check.sh
create mode 100644 server/tests/selftest_lite.py
create mode 100644 server/tests/test_steam_session.py
create mode 100644 server/vklayer/VkLayer_mpf_nulldraw.json
create mode 100644 server/vklayer/vk_nulldraw.c
diff --git a/.github/workflows/dedicated-server.yml b/.github/workflows/dedicated-server.yml
new file mode 100644
index 00000000..7bcc2c03
--- /dev/null
+++ b/.github/workflows/dedicated-server.yml
@@ -0,0 +1,128 @@
+# The Linux dedicated server (server/): static checks, the package built from this repository, the Docker image built and smoke-tested.
+# NOTHING IS PUBLISHED by a push or a pull request. The image is pushed to GHCR only by a manual run (workflow_dispatch) with
+# "publish" ticked, on the upstream repository, after the checks and the smoke tests below pass.
+name: Dedicated server
+
+on:
+ pull_request:
+ paths: ["server/**", "launcher/**", ".github/workflows/dedicated-server.yml"]
+ push:
+ branches: [main, "feature/dedicated-server"]
+ paths: ["server/**", "launcher/**", ".github/workflows/dedicated-server.yml"]
+ workflow_dispatch:
+ inputs:
+ publish:
+ description: "Push the image to GHCR (only the upstream repository, only after the tests pass)"
+ type: boolean
+ default: false
+ version:
+ description: "Version tag to publish besides 'experimental' (for example 0.9.1-server.1); empty: only 'experimental'"
+ type: string
+ default: ""
+
+concurrency:
+ group: dedicated-server-${{ github.ref }}
+ cancel-in-progress: true
+
+permissions:
+ contents: read
+
+jobs:
+ static:
+ runs-on: ubuntu-24.04
+ timeout-minutes: 10
+ steps:
+ - uses: actions/checkout@v4
+ - name: Tools
+ run: sudo apt-get update -qq && sudo apt-get install -y -qq shellcheck
+ - name: Static checks (shell, Python, Compose, no secrets, no binaries)
+ run: bash server/tests/check.sh
+
+ package:
+ # The same build as ci.yml (native module, launcher with warnings as errors, tests, archives); the server archive is the input of the image.
+ runs-on: windows-2022
+ timeout-minutes: 40
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-python@v5
+ with:
+ python-version: "3.12"
+ - run: python -m pip install lupa==2.8
+ - name: Build, test, pack
+ shell: pwsh
+ run: |
+ cmd /c build.bat 2>&1 | Tee-Object -FilePath build.log
+ if ($LASTEXITCODE -ne 0) { exit 1 }
+ - uses: actions/upload-artifact@v4
+ with:
+ name: server-package
+ path: release/*-server.zip
+ retention-days: 14
+ if-no-files-found: error
+
+ image:
+ needs: [static, package]
+ runs-on: ubuntu-24.04
+ timeout-minutes: 45
+ permissions:
+ contents: read
+ packages: write
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/download-artifact@v4
+ with:
+ name: server-package
+ path: server/dist
+ - name: Package for the image
+ working-directory: server/dist
+ run: |
+ ls -l
+ cp ./*-server.zip MPFever-server.zip
+ echo "PKG_VERSION=$(ls ./*-server.zip | head -1 | sed -E 's#.*MPFever-(.*)-server\.zip#\1#')" >> "$GITHUB_ENV"
+ - uses: docker/setup-buildx-action@v3
+ - name: Build the image (not pushed)
+ uses: docker/build-push-action@v6
+ with:
+ context: server
+ load: true
+ tags: mpfever-server:ci
+ build-args: |
+ VERSION=${{ env.PKG_VERSION }}
+ VCS_REF=${{ github.sha }}
+ cache-from: type=gha
+ cache-to: type=gha,mode=max
+ - name: Smoke tests
+ run: |
+ set -eu
+ img=mpfever-server:ci
+ # runs unprivileged
+ test "$(docker run --rm --entrypoint id "$img" -u)" = 1001
+ # contains no game file, no Valve file, no secret
+ docker run --rm --entrypoint find "$img" / -xdev \( -iname 'TransportFever3.exe' -o -iname 'steamclient*.dll' -o -iname 'steam.exe' -o -iname 'steam.json' -o -iname '*.sav' \) -not -path '/proc/*' | tee /tmp/found
+ test ! -s /tmp/found
+ # licence texts and Dock are present, a healthcheck is defined
+ docker run --rm --entrypoint sh "$img" -c 'test -f /opt/mpfever/dockhost.exe && test -f /opt/mpfever/licenses/madeira-dock/COPYING && test -f /opt/mpfever/pkg/MPFever.exe && test -f /opt/mpfever/pkg/winhttp.dll'
+ docker inspect --format '{{.Config.Healthcheck.Test}}' "$img" | grep -q healthcheck.sh
+ # an empty volume gives explicit messages, not a crash
+ docker volume create ci-data >/dev/null; docker volume create ci-game >/dev/null
+ set +e
+ out=$(docker run --rm -v ci-data:/data -v ci-game:/game "$img" status 2>&1); echo "$out"
+ echo "$out" | grep -q "login" && echo "$out" | grep -q "install-game"
+ out=$(docker run --rm -e WORLD=x -v ci-data:/data -v ci-game:/game "$img" run 2>&1); rc=$?; echo "$out"
+ test $rc -eq 40 && echo "$out" | grep -q "run login"
+ # the Dock build is the pinned one, the Vulkan layer loads
+ docker run --rm --entrypoint sh "$img" -c 'ls -l /opt/mpfever/libVkLayer_mpf_nulldraw.so /etc/vulkan/implicit_layer.d/'
+ - name: Log in to GHCR
+ if: github.event_name == 'workflow_dispatch' && inputs.publish && github.repository == 'dkdknight/MPFever'
+ uses: docker/login-action@v3
+ with:
+ registry: ghcr.io
+ username: ${{ github.actor }}
+ password: ${{ secrets.GITHUB_TOKEN }}
+ - name: Publish (manual run only)
+ if: github.event_name == 'workflow_dispatch' && inputs.publish && github.repository == 'dkdknight/MPFever'
+ run: |
+ set -eu
+ repo=ghcr.io/dkdknight/mpfever-server
+ docker tag mpfever-server:ci "$repo:experimental"; docker push "$repo:experimental"
+ if [ -n "${{ inputs.version }}" ]; then docker tag mpfever-server:ci "$repo:${{ inputs.version }}"; docker push "$repo:${{ inputs.version }}"; fi
diff --git a/launcher/Core.cs b/launcher/Core.cs
index 5619a69b..2cc8e638 100644
--- a/launcher/Core.cs
+++ b/launcher/Core.cs
@@ -1,4 +1,4 @@
-using System;
+using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
@@ -876,6 +876,27 @@ public void Launch(string gameDir)
int eq = kv.IndexOf('=');
if (eq > 0) psi.EnvironmentVariables[kv.Substring(0, eq).Trim()] = kv.Substring(eq + 1);
}
+ if (GameInstall.WineMode)
+ {
+ // Linux dedicated server (server/): the Windows game runs under Wine. With MPFEVER_DOCK (the Windows path of Madeira Dock's
+ // dockhost.exe) Valve's own client library signs in, checks the licence and starts the game with these arguments, as Steam would;
+ // otherwise the game's executable is started directly (a Steam client must then already run in the Wine prefix).
+ var dock = Environment.GetEnvironmentVariable("MPFEVER_DOCK");
+ psi.FileName = "wine";
+ if (!string.IsNullOrEmpty(dock))
+ {
+ psi.EnvironmentVariables["MADEIRA_STEAM_HOST_ARGUMENTS"] = psi.Arguments;
+ psi.EnvironmentVariables["MADEIRA_STEAM_HOST_LAUNCH"] = "1";
+ psi.Arguments = "\"" + dock + "\"";
+ }
+ else
+ psi.Arguments = "\"" + exe + "\" " + psi.Arguments;
+ psi.EnvironmentVariables["WINEDLLOVERRIDES"] = "winhttp=n,b;mscoree,mshtml=";
+ psi.EnvironmentVariables["WINEDEBUG"] = "-all";
+ psi.EnvironmentVariables["MPFEVER_DIR"] = GameInstall.WinPath(Dir);
+ if (psi.EnvironmentVariables["MPFEVER_SIGS"] != null) psi.EnvironmentVariables["MPFEVER_SIGS"] = GameInstall.WinPath(psi.EnvironmentVariables["MPFEVER_SIGS"]);
+ Log.W("Wine: " + psi.FileName + " " + psi.Arguments);
+ }
if (Reporter.OtherGamesRunning(-1) > 0) OtherGameSeen = true;
proc = Process.Start(psi);
proc.EnableRaisingEvents = true;
@@ -2395,6 +2416,12 @@ public static string PublicIPv6()
static class GameInstall
{
public const string AppId = "3493540";
+ /// This launcher runs on Linux (under Mono): the dedicated server of server/.
+ public static readonly bool IsLinux = Environment.OSVersion.Platform == PlatformID.Unix;
+ /// MPFEVER_WINE=1: this Linux launcher starts the Windows game under Wine (same executable and same winhttp.dll module as the players').
+ public static readonly bool WineMode = IsLinux && Environment.GetEnvironmentVariable("MPFEVER_WINE") == "1";
+ /// A Linux path as Wine sees it (Z: is the Linux root).
+ public static string WinPath(string p) => string.IsNullOrEmpty(p) ? p : "Z:" + p.Replace('/', '\\');
/// (0.6.3) The game folder the player chose by hand (setting "gamedir"), for a game MPFever does not find itself (a
/// GOG copy, a folder of its own): looked at after the usual places only. MPFEVER_GOG=0: not.
@@ -2635,6 +2662,7 @@ public static string SteamPath()
// library was left, so the mod went nowhere and no savegame was found): the first of these that holds steam.exe,
// then the running Steam's folder
var cands = new List();
+ if (WineMode) { var ws = Environment.GetEnvironmentVariable("MPFEVER_STEAMPATH"); if (!string.IsNullOrEmpty(ws)) cands.Add(ws); }
try { cands.Add(Registry.GetValue(@"HKEY_CURRENT_USER\Software\Valve\Steam", "SteamPath", null) as string); } catch { }
try { cands.Add(Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Valve\Steam", "InstallPath", null) as string); } catch { }
try { cands.Add(Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Valve\Steam", "InstallPath", null) as string); } catch { }
diff --git a/launcher/MainForm.cs b/launcher/MainForm.cs
index f47be6b2..0c437034 100644
--- a/launcher/MainForm.cs
+++ b/launcher/MainForm.cs
@@ -1,4 +1,4 @@
-using System;
+using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
@@ -5725,6 +5725,19 @@ void ResyncLocked(string reason)
if (!(saveDone.TryGetValue("ok", out var okv) && okv is bool ok && ok)) { Log.Err(T("Resynchronisation abandonnée : sauvegarde refusée.", "Resynchronisation cancelled: save refused.")); return; }
Thread.Sleep(1000); // the file is closed by the game after its callback
string file = GameInstall.FindSave(ResyncSaveName);
+ if (GameInstall.IsLinux)
+ {
+ // (Linux server) the game's save file may still be written after its callback: wait for it and for its size to stop moving
+ long last = -1; int still = 0;
+ for (int w = 0; w < 120 && still < 4; w++)
+ {
+ file = GameInstall.FindSave(ResyncSaveName);
+ long sz = -1; try { if (file != null && File.GetLastWriteTimeUtc(file) >= t0.AddSeconds(-5)) sz = new FileInfo(file).Length; } catch { }
+ if (sz > 0 && sz == last) still++; else still = 0;
+ last = sz;
+ Thread.Sleep(500);
+ }
+ }
if (file == null || File.GetLastWriteTimeUtc(file) < t0.AddSeconds(-5))
{
Log.Err(F("Resynchronisation abandonnée : fichier « {0}.sav » introuvable.", "Resynchronisation cancelled: file « {0}.sav » not found.", ResyncSaveName));
diff --git a/launcher/Server.cs b/launcher/Server.cs
index 2f7ac2f6..68ce28c8 100644
--- a/launcher/Server.cs
+++ b/launcher/Server.cs
@@ -728,6 +728,18 @@ void ServerLoop()
void ServerTick()
{
if (server == null || hostGame == null) return;
+ // (Linux server, server/) a container stop cannot close the window: MPFEVER_STOPFILE, when that file appears, stops the server
+ // properly (the world is saved first, the players are told), exactly as the console's "stop" does
+ if (GameInstall.IsLinux)
+ {
+ var stopFile = Environment.GetEnvironmentVariable("MPFEVER_STOPFILE");
+ if (!string.IsNullOrEmpty(stopFile) && File.Exists(stopFile))
+ {
+ try { File.Delete(stopFile); } catch { }
+ StopServer(true);
+ return;
+ }
+ }
bool st, paused; int sp;
lock (sessionGate) { st = started; paused = pauseAt.HasValue; sp = speed; }
if (!st)
diff --git a/server/.dockerignore b/server/.dockerignore
new file mode 100644
index 00000000..b596f0ac
--- /dev/null
+++ b/server/.dockerignore
@@ -0,0 +1,6 @@
+*
+!Dockerfile
+!scripts/
+!config/
+!vklayer/
+!dist/
diff --git a/server/.env.example b/server/.env.example
new file mode 100644
index 00000000..66b2eb00
--- /dev/null
+++ b/server/.env.example
@@ -0,0 +1,22 @@
+# Copy to .env. Everything but WORLD has a default. Changing a value never needs a rebuild: docker compose up -d
+# The savegame to host: its name without .sav, imported with `import-save` (README.md).
+WORLD=myworld
+SERVER_NAME=MPFever Server
+# TCP port players connect to (forward it on your router for the Internet).
+PORT=28090
+PASSWORD=
+MAX_PLAYERS=8
+# shared (one company for all) or separate (one per player)
+COMPANY_MODE=shared
+START_SPEED=1
+PAUSE_WHEN_EMPTY=false
+AUTOSAVE_MINUTES=10
+BACKUPS=10
+# List the server in MPFever's public list
+PUBLIC=false
+MOTD=
+# Resource limits. Measured for a small world: about 11 GB of RAM and 0.7 core.
+MEM_LIMIT=14g
+CPUS=2
+# Another image or version (rollback): MPFEVER_IMAGE=ghcr.io/dkdknight/mpfever-server:
+#MPFEVER_IMAGE=
diff --git a/server/.gitattributes b/server/.gitattributes
new file mode 100644
index 00000000..abc51ec4
--- /dev/null
+++ b/server/.gitattributes
@@ -0,0 +1,2 @@
+* text=auto eol=lf
+*.ps1 eol=crlf
diff --git a/server/.gitignore b/server/.gitignore
new file mode 100644
index 00000000..ae32d339
--- /dev/null
+++ b/server/.gitignore
@@ -0,0 +1,4 @@
+dist/
+.env
+__pycache__/
+*.pyc
diff --git a/server/Dockerfile b/server/Dockerfile
new file mode 100644
index 00000000..118b8347
--- /dev/null
+++ b/server/Dockerfile
@@ -0,0 +1,76 @@
+# syntax=docker/dockerfile:1
+# MPFever dedicated server (experimental): the Windows game under Wine 11 on Linux, Steam through Madeira Dock (Valve's own client library),
+# no GPU needed. See README.md and docs/ARCHITECTURE.md.
+#
+# Build context: this folder. The MPFever package (launcher, native module, mod, built from this repository by build.bat / CI) is an input:
+# server/dist/MPFever-server.zip (the release\MPFever--server.zip of a build)
+# The image contains no Transport Fever 3 file and no Valve file: the game is imported from the user's own copy (install-game) and Valve's
+# client library is fetched from Valve at the first start.
+
+ARG UBUNTU=ubuntu:24.04
+
+# ---------------------------------------------------------------- Madeira Dock, from source at a pinned commit (GPL-3.0-or-later)
+FROM ${UBUNTU} AS dock
+ARG DOCK_REPO=https://github.com/willfaust/madeira-dock.git
+ARG DOCK_REF=67780ba92e60dbfac4fe80eaf2ce34b9ea1a1c60
+RUN apt-get update -qq && apt-get install -y -qq --no-install-recommends ca-certificates git gcc-mingw-w64-x86-64 >/dev/null \
+ && git clone -q "$DOCK_REPO" /src && git -C /src checkout -q "$DOCK_REF" && test "$(git -C /src rev-parse HEAD)" = "$DOCK_REF"
+WORKDIR /src
+RUN x86_64-w64-mingw32-gcc -std=c11 -O2 -Wall -Wno-cast-function-type -static -s -o /dockhost.exe \
+ src/main.c src/probe.c src/session.c src/launch.c src/validation.c src/auth.c src/client_layout.c src/scm.c src/hold.c -ladvapi32 -luser32
+
+# ---------------------------------------------------------------- the Vulkan layer that makes drawing a no-op
+FROM ${UBUNTU} AS vklayer
+RUN apt-get update -qq && apt-get install -y -qq --no-install-recommends gcc libc6-dev libvulkan-dev >/dev/null
+COPY vklayer/vk_nulldraw.c /src/vk_nulldraw.c
+RUN gcc -O2 -shared -fPIC -Wall -Werror -o /libVkLayer_mpf_nulldraw.so /src/vk_nulldraw.c -lpthread
+
+# ---------------------------------------------------------------- runtime
+FROM ${UBUNTU} AS runtime
+ARG WINE_VERSION=11.0.0.0~noble-1
+ENV DEBIAN_FRONTEND=noninteractive
+RUN dpkg --add-architecture i386 \
+ && apt-get update -qq \
+ && apt-get install -y -qq --no-install-recommends ca-certificates curl wget gnupg2 procps xvfb xauth \
+ libvulkan1 mesa-vulkan-drivers libgl1 libasound2t64 libgnutls30t64 libfreetype6 fonts-dejavu-core \
+ python3-minimal python3-qrcode mono-complete libgdiplus \
+ && mkdir -pm755 /etc/apt/keyrings \
+ && wget -qO /etc/apt/keyrings/winehq-archive.key https://dl.winehq.org/wine-builds/winehq.key \
+ && wget -qNP /etc/apt/sources.list.d/ https://dl.winehq.org/wine-builds/ubuntu/dists/noble/winehq-noble.sources \
+ && apt-get update -qq \
+ && apt-get install -y -qq --install-recommends \
+ winehq-stable=${WINE_VERSION} wine-stable=${WINE_VERSION} wine-stable-amd64=${WINE_VERSION} wine-stable-i386=${WINE_VERSION} \
+ && rm -rf /var/lib/apt/lists/* \
+ && useradd -m -d /data -u 1001 -s /bin/bash tf3 \
+ && mkdir -p /data /game /opt/mpfever && chown tf3:tf3 /data /game
+
+# the MPFever package built from this repository (launcher patched for Wine + Dock, native module, mod, signatures)
+COPY dist/MPFever-server.zip /tmp/mpfever-server.zip
+RUN python3 -m zipfile -e /tmp/mpfever-server.zip /tmp/pkg && mkdir -p /opt/mpfever/pkg \
+ && cp -r /tmp/pkg/*/mod /tmp/pkg/*/winhttp.dll /tmp/pkg/*/mpfever_sigs.txt /tmp/pkg/*/MPFever.exe /tmp/pkg/*/MPFever.exe.config /tmp/pkg/*/LICENSE.txt /opt/mpfever/pkg/ \
+ && rm -rf /tmp/pkg /tmp/mpfever-server.zip
+
+COPY --from=dock /dockhost.exe /opt/mpfever/dockhost.exe
+COPY --from=dock /src/LICENSE /src/COPYING /src/LICENSE-EXCEPTION.md /opt/mpfever/licenses/madeira-dock/
+COPY --from=vklayer /libVkLayer_mpf_nulldraw.so /opt/mpfever/libVkLayer_mpf_nulldraw.so
+COPY vklayer/VkLayer_mpf_nulldraw.json /etc/vulkan/implicit_layer.d/VkLayer_mpf_nulldraw.json
+COPY scripts/ /opt/mpfever/scripts/
+COPY config/ /opt/mpfever/config/
+RUN sed -i 's/\r$//' /opt/mpfever/scripts/*.sh && chmod 755 /opt/mpfever/scripts/*.sh
+
+ARG VCS_REF=unknown
+ARG VERSION=experimental
+LABEL org.opencontainers.image.title="MPFever dedicated server (experimental)" \
+ org.opencontainers.image.description="Transport Fever 3 under Wine with Madeira Dock; contains no game or Valve files" \
+ org.opencontainers.image.source="https://github.com/dkdknight/MPFever" \
+ org.opencontainers.image.licenses="GPL-3.0-or-later" \
+ org.opencontainers.image.revision="${VCS_REF}" org.opencontainers.image.version="${VERSION}"
+
+USER tf3
+WORKDIR /data
+VOLUME ["/data", "/game"]
+EXPOSE 28090
+STOPSIGNAL SIGTERM
+HEALTHCHECK --interval=60s --timeout=10s --start-period=300s --retries=3 CMD ["/opt/mpfever/scripts/healthcheck.sh"]
+ENTRYPOINT ["/opt/mpfever/scripts/entrypoint.sh"]
+CMD ["run"]
diff --git a/server/README.md b/server/README.md
new file mode 100644
index 00000000..9970e50d
--- /dev/null
+++ b/server/README.md
@@ -0,0 +1,69 @@
+# MPFever dedicated server for Linux (experimental)
+
+A server that runs the **real Transport Fever 3 simulation** in one Docker container: the Windows game under Wine, started through
+[Madeira Dock](https://github.com/willfaust/madeira-dock) and Valve's own Steam client library. No GPU, no screen, no Steam desktop.
+Players join it with the usual MPFever client (same version) from Windows.
+
+> **Status: experimental.** It works for short sessions on a small world with a real Windows client (see "Validation" in
+> [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md)). It needs **your own** Transport Fever 3 licence: the image contains no game file and no Valve file.
+
+## What you need
+
+- A Linux x86-64 host or VPS (Docker with Compose v2), **12 GB of RAM or more** free for the container, about 1 core, **a file system with sparse-file
+ support** (ext4, xfs, btrfs) and about 6 GB of disk. No GPU.
+- A Steam account that **owns Transport Fever 3**, with the Steam mobile app (to approve the sign-in once). Use an account that is not played on
+ at the same time as the server (one Steam account plays one game at a time).
+- A copy of the game on a PC where it is installed (to build the small "lite" install), and a savegame (`.sav`) of the world to host.
+
+## Install
+
+```
+mkdir mpfever-server && cd mpfever-server
+curl -fsSLO https://raw.githubusercontent.com/dkdknight/MPFever/main/server/compose.yaml
+curl -fsSL https://raw.githubusercontent.com/dkdknight/MPFever/main/server/.env.example -o .env
+```
+
+Edit `.env` (at least `WORLD`, the savegame's name without `.sav`). Then, once:
+
+1. **Pull the image**: `docker compose pull`
+2. **Import the game** from your own Steam library (read-only mount; the 3D data is left out, 66 GB become about 1 GB on disk):
+ ```
+ docker compose run --rm -v "/path/to/Steam/steamapps:/src:ro" mpfever-server install-game /src
+ ```
+ (`/path/to/Steam/steamapps` is the library folder that holds `common/Transport Fever 3` and `appmanifest_3493540.acf`.)
+3. **Sign in to Steam** (QR code in the terminal, approve it in the Steam mobile app; no password is typed or stored):
+ ```
+ docker compose run --rm mpfever-server login
+ ```
+ Only a Steam refresh token is kept, in the `mpfever-data` volume (`secrets/steam.json`, mode 0600). It is valid for several months; when it expires the
+ server says so and you run `login` again.
+4. **Import your savegame** (the `.sav` and the files next to it with the same name):
+ ```
+ docker compose run --rm -v "/path/to/saves:/in:ro" mpfever-server import-save /in/myworld.sav
+ ```
+5. **Start**: `docker compose up -d`. It restarts by itself after a reboot or a crash. `docker compose logs -f` shows the server's log.
+
+Check at any time what is missing: `docker compose run --rm mpfever-server status`.
+Players connect to `:28090` (forward the TCP port on your router for the Internet). Stop with `docker compose stop` (the world is saved first).
+
+## Configuration
+
+All settings are in `.env` and take effect with `docker compose up -d`, no rebuild. The game's save files and the launcher's backups (`srv/backups`, `backups=` in `.env`)
+live in the `mpfever-data` volume: back it up (`docker run --rm -v mpfever-data:/d -v "$PWD":/b ubuntu tar czf /b/mpfever-data.tgz -C /d .`). The game volume `mpfever-game` can be rebuilt
+with `install-game` at any time. Server console commands (`save`, `kick`, ...) are those of `MPFever.exe --server` (see the server's `SERVER.txt`).
+
+## Update and roll back
+
+Images are tagged by version (`ghcr.io/dkdknight/mpfever-server:`) and `experimental`. Update: `docker compose pull && docker compose up -d`. Roll back: set
+`MPFEVER_IMAGE=ghcr.io/dkdknight/mpfever-server:` in `.env` and `docker compose up -d`; the data volume is untouched. Players need the MPFever client of the server's version.
+See [docs/OPERATIONS.md](docs/OPERATIONS.md) for backups, Valve updates, security and troubleshooting.
+
+## Build it yourself
+
+`build.bat` at the repository root builds the launcher and package (`release/MPFever--server.zip`); copy it to `server/dist/MPFever-server.zip` and run
+`docker compose -f compose.yaml -f compose.build.yaml build`. The same steps run in CI (`.github/workflows/dedicated-server.yml`).
+
+## Licence
+
+GPL-3.0-or-later like MPFever. The image contains Madeira Dock (GPL-3.0-or-later, built from source at a pinned commit, licence texts in `/opt/mpfever/licenses`), Wine (LGPL), Mono, Mesa.
+Transport Fever 3 and Steam belong to their owners and are never redistributed here.
diff --git a/server/compose.build.yaml b/server/compose.build.yaml
new file mode 100644
index 00000000..500da85f
--- /dev/null
+++ b/server/compose.build.yaml
@@ -0,0 +1,8 @@
+# Local build instead of the published image: docker compose -f compose.yaml -f compose.build.yaml build
+# Needs dist/MPFever-server.zip (see Dockerfile).
+services:
+ mpfever-server:
+ build:
+ context: .
+ args:
+ VERSION: ${VERSION:-local}
diff --git a/server/compose.gpu.yaml b/server/compose.gpu.yaml
new file mode 100644
index 00000000..0a1113b2
--- /dev/null
+++ b/server/compose.gpu.yaml
@@ -0,0 +1,9 @@
+# Optional: use a real GPU (Intel/AMD through /dev/dri) instead of software rendering. Not validated.
+# docker compose -f compose.yaml -f compose.gpu.yaml up -d
+services:
+ mpfever-server:
+ devices:
+ - /dev/dri:/dev/dri
+ environment:
+ MPF_VKNULL: "0"
+ MPFEVER_ENV_HOST: ""
diff --git a/server/compose.yaml b/server/compose.yaml
new file mode 100644
index 00000000..058f516d
--- /dev/null
+++ b/server/compose.yaml
@@ -0,0 +1,45 @@
+# MPFever dedicated server (experimental). Setup and first start: README.md. docker compose up -d
+services:
+ mpfever-server:
+ image: ${MPFEVER_IMAGE:-ghcr.io/dkdknight/mpfever-server:experimental}
+ container_name: mpfever-server
+ restart: unless-stopped
+ init: true
+ stop_grace_period: 60s # the world is saved and the game closed on `docker compose stop`
+ ports:
+ - "${PORT:-28090}:${PORT:-28090}"
+ environment:
+ WORLD: ${WORLD:?set WORLD in .env (the savegame to host)}
+ SERVER_NAME: ${SERVER_NAME:-MPFever Server}
+ PORT: ${PORT:-28090}
+ PASSWORD: ${PASSWORD:-}
+ MAX_PLAYERS: ${MAX_PLAYERS:-8}
+ COMPANY_MODE: ${COMPANY_MODE:-shared}
+ START_SPEED: ${START_SPEED:-1}
+ PAUSE_WHEN_EMPTY: ${PAUSE_WHEN_EMPTY:-false}
+ PLAYER_SPEED_CONTROL: ${PLAYER_SPEED_CONTROL:-true}
+ AUTOSAVE_MINUTES: ${AUTOSAVE_MINUTES:-10}
+ BACKUPS: ${BACKUPS:-10}
+ PUBLIC: ${PUBLIC:-false}
+ PUBLIC_ADDRESS: ${PUBLIC_ADDRESS:-}
+ MOTD: ${MOTD:-}
+ volumes:
+ - data:/data # Wine prefix, Valve client, Steam session (secrets/), saves, launcher and its logs and backups
+ - game:/game # the "lite" game install (about 1 GB on disk)
+ mem_limit: ${MEM_LIMIT:-14g}
+ cpus: ${CPUS:-2}
+ read_only: true
+ tmpfs:
+ - /tmp:size=512m
+ cap_drop: [ALL]
+ security_opt:
+ - no-new-privileges:true
+ logging:
+ driver: json-file
+ options: { max-size: "20m", max-file: "5" }
+
+volumes:
+ data:
+ name: ${DATA_VOLUME:-mpfever-data}
+ game:
+ name: ${GAME_VOLUME:-mpfever-game}
diff --git a/server/config/settings.lua b/server/config/settings.lua
new file mode 100644
index 00000000..f94799e5
--- /dev/null
+++ b/server/config/settings.lua
@@ -0,0 +1,174 @@
+function data()
+return {
+ audioEffectSettings = {
+ bulldozer = true,
+ construction = true,
+ },
+ autosaveIntervalMinutes = 10,
+ autosaveKeepNumber = 10,
+ backgroundContrastMode = "Both",
+ bloomQuality = 0,
+ cameraTool = false,
+ cloudTransparencyMode = "Center",
+ controllerCameraFlags = {
+ invertRotate = false,
+ invertTilt = false,
+ invertZoom = false,
+ swapSticks = false,
+ },
+ controllerCameraSpeed = {
+ cockpitMove = 0.5,
+ cockpitRotate = 0.5,
+ gameRotate = 0.5,
+ gameScroll = 0.5,
+ gameZoom = 0.5,
+ },
+ controllerNavigateSwapSticks = false,
+ crashSaveEnabled = true,
+ crashSaveSingleFile = false,
+ cssEffectsVelocity = 1,
+ customCameraManagerResolutions = { },
+ customColors = {
+ { -1, -1, -1, },
+ { -1, -1, -1, },
+ { -1, -1, -1, },
+ { -1, -1, -1, },
+ { -1, -1, -1, },
+ { -1, -1, -1, },
+ { -1, -1, -1, },
+ { -1, -1, -1, },
+ { -1, -1, -1, },
+ { -1, -1, -1, },
+ },
+ debugInfoShowFps = false,
+ debugMode = false,
+ deferredProposal = false,
+ disableConstructionParticles = false,
+ disableMessageBox = false,
+ distanceSpeedUnit = "Metric",
+ enableCelebrations = true,
+ enableDeferredTextures = true,
+ enableKeyboardMouse = true,
+ enableMeshStreaming = true,
+ enableSeamlessStreetBuilder = true,
+ experimentalMailboxPresent = false,
+ experimentalMapFeatures = false,
+ experimentalOptimizeShaders = false,
+ experimentalSwapChainSize = -1,
+ experimentalTerrainGeneratorEditor = false,
+ experimentalTunnelAndBridgeMinHeight = false,
+ externalModPath = "",
+ firstStart = true,
+ fontScaleClass = "SMALL",
+ forceUnit = "KN",
+ fullscreenSize = { 0, 0, },
+ gamepadDeadzone = 0.2,
+ geometryQuality = 0,
+ graphicalDeviceOverride = -1,
+ grassQuality = 0,
+ guideSystemActive = true,
+ hasShownInitialDeluxeThankYou = false,
+ hudEffectMode = "CockpitOnly",
+ hudMode = 1,
+ industryClosureNotification = true,
+ industrySpawnNotification = true,
+ invertPan = false,
+ invertRotate = false,
+ invertRotateKeys = false,
+ invertTilt = false,
+ invertZoom = false,
+ keyboardCameraSpeed = {
+ cameraTool = 0.5,
+ cockpit = 0.5,
+ game = 0.5,
+ },
+ lineAssignVisibleOnly = false,
+ mainMenuState = {
+ activeModsState = { "mpfever_1", },
+ },
+ masterVolume = 1,
+ maxDegreeOfAnisotropy = 1,
+ menuMusicEnabled = true,
+ modHubVerboseLogging = false,
+ moneyMode = "RAW",
+ moneyPrefix = "$",
+ moneySuffix = "",
+ mouseEnableRightClickBack = true,
+ mouseMovementSensitivity = 5,
+ mouseWheelSensitivity = 0.5,
+ musicEnabled = true,
+ musicEraDependent = true,
+ musicVolume = 1,
+ newVehicleNotification = true,
+ numMSAASamples = 1,
+ oldScreenMode = "FULLSCREEN",
+ oldVsync = true,
+ oldWindowSize = { -1, -1, },
+ panningMode = "perspective",
+ parallelEdgesMaxDistance = 2000,
+ playlist = "music/default/default.plist",
+ powerUnit = "KW",
+ refreshRate = 0,
+ renderer = "VULKAN",
+ rendererDebugGpuCrash = false,
+ rendererDebugMode = false,
+ resolutionScale = 0.25,
+ screenMode = "BORDERLESS",
+ scrollAtBorder = false,
+ shadowQuality = 0,
+ showIntelHDwarning = true,
+ showMissingResourcesDialog = true,
+ showReleaseNotes = true,
+ showSplashScreen = true,
+ showVideoMemoryUsageWarning = true,
+ soundVolume = 1,
+ splashMusicEnabled = true,
+ ssrQuality = 0,
+ streamingTextureLodOffsetModel = -4,
+ streamingTextureLodOffsetTerrain = -2,
+ terrainQuality = 0,
+ terrainTesselationEnabled = true,
+ terrainTextureQuality = 0,
+ terrainTriplanarDistance = 3000,
+ textureQuality = 0,
+ townCargoNeedsNotification = true,
+ uiAutoScaling = true,
+ uiscaling = 1,
+ updateMessageID = 0,
+ uploadCrashDumps = true,
+ uploadHangDumps = false,
+ useHardwareCursor = true,
+ useLegacyHdr = false,
+ useReflection = false,
+ useSsao = true,
+ videoMemoryUsageWarningThreshold = 0.95,
+ viewportScale = 1,
+ voiceOverEnabled = true,
+ voiceOverVolume = 1,
+ vramBudgetFixedGpuMB = -1,
+ vramBudgetMeshesEnableCache = true,
+ vramBudgetMeshesEnableLimit = true,
+ vramBudgetMeshesSizeMB = -1,
+ vramBudgetMinGpuMB = 4096,
+ vramBudgetReserve = 0.2,
+ vramBudgetTerrainHeightmapTexturesEnableCache = true,
+ vramBudgetTerrainHeightmapTexturesEnableLimit = true,
+ vramBudgetTerrainHeightmapTexturesSizeMB = 64,
+ vramBudgetTerrainMaterialTexturesEnableCache = true,
+ vramBudgetTerrainMaterialTexturesEnableLimit = true,
+ vramBudgetTerrainMaterialTexturesSizeMB = 128,
+ vramBudgetTexturesEnableCache = true,
+ vramBudgetTexturesEnableLimit = true,
+ vramBudgetTexturesSizeMB = 128,
+ vsync = true,
+ waitForStartReadyGame = true,
+ weightUnit = "T",
+ windowSize = { 320, 200, },
+ zoomOutFromCursor = false,
+ zoomPrecise = true,
+ zoomPreciseAccel = 0.25,
+ zoomPreciseDeccel = 8,
+ zoomPreciseMaxSpeed = 4,
+ zoomToCursor = false,
+ }
+end
\ No newline at end of file
diff --git a/server/docs/ARCHITECTURE.md b/server/docs/ARCHITECTURE.md
new file mode 100644
index 00000000..9cf5096d
--- /dev/null
+++ b/server/docs/ARCHITECTURE.md
@@ -0,0 +1,45 @@
+# Architecture, decisions, measures
+
+## The pieces
+
+| Part | What | Why |
+|---|---|---|
+| Game | `TransportFever3.exe` (Windows) under **Wine 11** (pinned package) on Ubuntu 24.04 | A native Linux build of the game drifts from Windows clients (different C++ library, `std::` distributions inlined in the game): same executable = same simulation. Not Proton: no DXVK, rendering is a no-op. |
+| Launcher | `MPFever.exe --server --server-start headless` under **Mono**, with a Linux/Wine mode (`launcher/Core.cs`: `GameInstall.WineMode`, `MPFEVER_WINE=1`; `Server.cs`: `MPFEVER_STOPFILE`) | Provides all the host logic and the same `winhttp.dll` native module and mod as the players'. Built from this repository by `build.bat`. |
+| Steam | **Madeira Dock** (`dockhost.exe`, built from source at a pinned commit) driving **Valve's own `steamclient64.dll`** | The game requires a running Valve client. Dock signs in with the account owner's refresh token, asks Valve's client for the licence and has it start the game: no `steam.exe`, no `steamwebhelper` (about 280 MB instead of 2.7 GB). No emulation of Steamworks, no DRM bypass: every decision is Valve's. |
+| Rendering | Lavapipe (software Vulkan) + the layer `vklayer/` (`MPF_VKNULL=1`, `MPF_VKNULL_MODE=all`, `MPF_VKNULL_TRIM=1`) and `MPFEVER_HEADLESS_NORENDER=1;MPFEVER_HEADLESS_FPS=10` | Draws, copies and render passes become no-ops; mapped GPU memory nobody reads is given back. A real GPU is used if the layer is off (`compose.gpu.yaml`, not validated). |
+| Disk | "Lite" game install (`scripts/mklite.py`) | The engine reads archives at fixed offsets, so archives keep their layout: textures, audio and blobs become file holes (sparse), images stay valid but empty. 66 GB become about 1 GB on disk. Generated from the host's own copy; never distributed. |
+| Display | `Xvfb` only | The game closes without an X server. Nothing is exposed (no VNC, no noVNC). |
+
+## Layers and data
+
+- **Image** (versioned, immutable): Wine, Mono, launcher package, Dock, Vulkan layer, scripts. No secret, no TF3 file, no Valve file.
+- **`/data` volume**: Wine prefix, Valve client (fetched from Valve, pinned hash), `secrets/steam.json`, saves (inside the Steam `userdata` of the prefix), `srv/` (launcher logs, backups).
+- **`/game` volume**: the lite game install. **Configuration**: `.env` (environment), written to `mpfever_server.properties` at each start.
+- **Sign-in**: `scripts/steam_session.py login` (Steam's `IAuthenticationService` QR flow, the same as the Steam mobile app's "sign in with QR") stores a refresh token;
+ at each game start `feed` writes Dock's one-use transfer file (`MDOCK001`) with it. The token never appears on a command line, in the environment or in the image.
+- **Start** (`scripts/entrypoint.sh run`): checks (disk, sparse support, RAM, game, session, save), first-start prefix creation (marker file, so a restart reinstalls nothing), pinned Valve client,
+ launcher with restart-on-exit (5 quick failures in a minute stop the container with a message), `SIGTERM` writes the stop file: the world is saved, the game closed, then the container exits.
+
+## Measured (small world, MPFever 0.9.0 package, no GPU, one real Windows client)
+
+| | |
+|---|---|
+| Game RAM | 10.1 to 10.3 GB (11.0 to 11.2 GB before the GPU-memory trim); heap of about 9 GB is the game's own |
+| Steam side (Dock + Valve service) | about 280 MB (Steam desktop under Wine: 2.7 GB) |
+| CPU | about 0.7 core at x0.98 game speed |
+| Disk | about 0.9 GB game + about 3 GB prefix and client |
+| Sync with a real Windows client | `IDENTICAL on 2 games`, 0 desynchronisations, runs of 3 to 13 minutes |
+
+## Validation status (honest)
+
+Validated on the maintainer's machine with the earlier hand-prepared volumes: Dock sign-in with the cached Steam session, licence check, launch, restart after a game crash, cold start of the container, synchronisation
+with a real Windows 0.9.0 client for short runs (join, resynchronisation, identical checks).
+**Not validated yet**: first start on an empty volume with `install-game`, `login` (QR) and the token transfer to Dock; `import-save`; graceful stop through the stop file; runs of 30 minutes or more;
+several clients (a Steam account plays one game at a time: a second account is needed); large worlds; forced CPU/memory minimums; a full image rebuild (the image was last assembled on top of an older Wine layer);
+the GPU variant; the published image (nothing is published until the checklist of the pull request is done).
+
+## Decisions not to redo
+
+Native Linux game: abandoned (drift). Steam desktop under Wine: replaced by Dock (2.7 GB web helper floor; stubbing it crashes Steam). Aurelia (headless Steam CLI) downloads the game but cannot run TF3 without a Steam client.
+A server without the game installed is impossible with the Steam build without circumventing the DRM (refused): the game comes from the host's own licence. `autoupdate=0` is mandatory (the official updater replaces the launcher and module).
diff --git a/server/docs/OPERATIONS.md b/server/docs/OPERATIONS.md
new file mode 100644
index 00000000..7d67f2ca
--- /dev/null
+++ b/server/docs/OPERATIONS.md
@@ -0,0 +1,36 @@
+# Operations: Valve client, updates, security, troubleshooting
+
+## Valve's Steam client and Madeira Dock (compatibility and risk)
+
+Dock calls **internal interfaces of Valve's client library** by position in its method tables, so it only drives builds it has verified (identified by the SHA-256 of `steamclient64.dll`)
+and refuses any other one (result 30, before any sign-in). This image pins:
+
+| | |
+|---|---|
+| `steamclient64.dll` | January 2026 build, 25 546 904 bytes, SHA-256 `71b391fe9f3e2006cbc81a5c75eef3eb4186012deabfdb2c8b7e8d4850ecf640` (PE timestamp 1769726215) |
+| Package fetched from Valve | `https://client-update.akamai.steamstatic.com/bins_win32.zip.23e34a6d4b10596a44561a5100dac5585d2517da`, SHA-256 `8b712b2a3412a9066b7725f4e1c5cef9a7ca5b187b6585a5b92d25d09df0ba62` (checked before use) |
+| Madeira Dock | github.com/willfaust/madeira-dock, commit `67780ba92e60dbfac4fe80eaf2ce34b9ea1a1c60` (GPL-3.0-or-later), built in the image |
+
+Dock never starts `steam.exe`, so the pinned client is **never updated by Steam itself**. Risks, stated plainly:
+1. Valve could remove that archive from its server or change its authentication protocol. The server then stops with an explicit message (hash mismatch, download failure, or Dock's refusal in `srv/dock.log`). There is no second Steam implementation to fall back on:
+ the remedy is a new Dock revision with a verified layout, and a new pinned hash here (`scripts/lib.sh`, `Dockerfile`).
+2. Dock is a young third-party project, not endorsed by Valve. Overlay, cloud saves and achievements are not supported by it; the server does not use them.
+3. The sign-in is the account owner's own, through Steam's authentication service; tokens are stored only in `secrets/steam.json`. Using unofficial tooling on a Steam account carries the usual risk of Valve's rules: use an account you accept that for.
+4. One Steam account plays one game at a time: playing on that account elsewhere while the server runs can interrupt it (observed: a few minutes of both running was tolerated, no guarantee). A dedicated account (Family Sharing) is recommended.
+
+## Update, roll back, back up
+
+- Update: `docker compose pull && docker compose up -d`. Roll back: `MPFEVER_IMAGE=ghcr.io/dkdknight/mpfever-server:` in `.env`. The launcher package is replaced at each start; `.env` and the volumes stay.
+- Players must run the MPFever client of the server's version (the launcher says "other version than the host's" otherwise).
+- Back up the `mpfever-data` volume (saves, `srv/backups`, session). Never copy `secrets/steam.json` anywhere else; revoke it from your Steam account (Settings, Security, devices) if it leaks.
+- Resetting: remove the volumes (`docker compose down -v`) to start from nothing; the game volume is rebuilt by `install-game`.
+
+## Security
+
+Runs as uid 1001, read-only root file system, all capabilities dropped, `no-new-privileges`, only the game port published, no graphical or remote-desktop interface.
+The image holds no secret; `.env` holds the server password if you set one: keep it out of version control.
+
+## Troubleshooting
+
+`docker compose run --rm mpfever-server status` lists what is missing. Launcher log: `docker compose logs`, files `srv/launcher.out`, `srv/logs/`, Dock report `srv/dock.log` (stage names and numbers only; result codes in madeira-dock's README).
+Exit code 20/21 Valve client download or hash, 30 game missing, 40/41 Steam session missing or expired, 42 savegame missing, 50 launcher failing repeatedly.
diff --git a/server/scripts/entrypoint.sh b/server/scripts/entrypoint.sh
new file mode 100644
index 00000000..8bba7a56
--- /dev/null
+++ b/server/scripts/entrypoint.sh
@@ -0,0 +1,193 @@
+#!/bin/bash
+# MPFever dedicated server entrypoint (runs as an unprivileged user).
+# run start the server (default)
+# login sign in to Steam once with a QR code (no password, no GUI); the session is remembered
+# install-game build the lite game install from your own Steam library folder (mounted read-only)
+# import-save .. copy savegame files into the server account's save folder
+# status check everything the server needs and print what is missing
+# shell a shell in the container
+set -u
+. /opt/mpfever/scripts/lib.sh
+
+MODE=${1:-run}; [ $# -gt 0 ] && shift
+
+# ---------------------------------------------------------------- helpers
+
+ensure_dirs() {
+ mkdir -p "$DATA" "$SRV" "$RUN" "$STEAM_DIR/steamapps/common" "$STEAM_DIR/config" 2>/dev/null \
+ && mkdir -p -m 700 "$SECRETS" 2>/dev/null && [ -w "$DATA" ] \
+ || die "$DATA is not writable by uid $(id -u): fix the volume ownership (chown -R $(id -u):$(id -g) )" 10
+}
+
+init_prefix() { # idempotent: only the first start builds the Wine prefix
+ if [ ! -f "$DATA/.prefix-v1" ]; then
+ log "first start: creating the Wine prefix (about a minute)"
+ wineboot -u >/dev/null 2>&1 || true; wineserver -w
+ touch "$DATA/.prefix-v1"
+ fi
+ # the game's own Visual C++ runtime, native, for Wine (the builtin stubs are incomplete)
+ local f d="$WINEPREFIX/drive_c/windows/system32"
+ for f in "$GAME"/msvcp140*.dll "$GAME"/vcruntime140*.dll "$GAME"/concrt140.dll; do
+ [ -f "$f" ] && [ ! -f "$d/$(basename "$f")" ] && cp "$f" "$d/"
+ done
+ return 0
+}
+
+ensure_client() { # Valve's pinned client library, fetched from Valve's own server, once
+ [ "$(sha256_of "$STEAM_DIR/steamclient64.dll")" = "$CLIENT_DLL_SHA256" ] && return 0
+ log "fetching Valve's Steam client package from Valve (pinned, about 60 MB)"
+ local z; z=$(mktemp -p "$DATA" client.XXXXXX.zip)
+ curl -fsSL --retry 3 -o "$z" "$CLIENT_URL" || { rm -f "$z"; die "cannot download Valve's client package from $CLIENT_URL" 20; }
+ [ "$(sha256_of "$z")" = "$CLIENT_ZIP_SHA256" ] || { rm -f "$z"; die "the downloaded Steam client package does not match the pinned hash: refusing it" 21; }
+ python3 -m zipfile -e "$z" "$STEAM_DIR" && rm -f "$z"
+ [ "$(sha256_of "$STEAM_DIR/steamclient64.dll")" = "$CLIENT_DLL_SHA256" ] || die "steamclient64.dll does not match the pinned build" 21
+}
+
+link_game() {
+ [ -f "$GAME/TransportFever3.exe" ] || die "no game install in $GAME: run install-game (README.md, step 2)" 30
+ [ -f "$STEAM_DIR/steamapps/appmanifest_$APPID.acf" ] || die "the Steam app manifest is missing: run install-game again" 30
+ [ -L "$GAME_LINK" ] || { rmdir "$GAME_LINK" 2>/dev/null; ln -sfn "$GAME" "$GAME_LINK"; }
+ if [ ! -f "$STEAM_DIR/steamapps/libraryfolders.vdf" ]; then # the single library the Valve client needs to find the game
+ printf '"libraryfolders"\n{\n\t"0"\n\t{\n\t\t"path"\t\t"C:\\\\Program Files (x86)\\\\Steam"\n\t\t"label"\t\t""\n\t\t"apps"\n\t\t{\n\t\t\t"%s"\t\t"0"\n\t\t}\n\t}\n}\n' "$APPID" > "$STEAM_DIR/steamapps/libraryfolders.vdf"
+ fi
+}
+
+account_id() { python3 -c 'import json,sys; print(int(json.load(open(sys.argv[1]))["steamid"]) - 76561197960265728)' "$SESSION_FILE"; }
+
+save_dir() { echo "$STEAM_DIR/userdata/$(account_id)/$APPID/local/save"; }
+local_dir() { echo "$STEAM_DIR/userdata/$(account_id)/$APPID/local"; }
+
+# ---------------------------------------------------------------- modes
+
+cmd_status() {
+ local bad=0
+ ensure_dirs
+ echo "data volume : $DATA ($(free_gb "$DATA") GB free) game volume: $GAME ($(free_gb "$GAME") GB free)"
+ if supports_sparse "$GAME"; then echo "sparse files: yes"; else echo "sparse files: NO (the lite game install needs ext4, xfs or btrfs)"; bad=1; fi
+ [ -f "$GAME/TransportFever3.exe" ] && echo "game : installed" || { echo "game : missing (install-game)"; bad=1; }
+ python3 "$OPT/scripts/steam_session.py" status --file "$SESSION_FILE" || { echo "steam : not signed in (login)"; bad=1; }
+ [ "$(sha256_of "$STEAM_DIR/steamclient64.dll")" = "$CLIENT_DLL_SHA256" ] && echo "steam client: pinned build present" || echo "steam client: will be fetched at start"
+ if [ -n "${WORLD:-}" ] && [ -f "$SESSION_FILE" ]; then
+ [ -f "$(save_dir)/$WORLD.sav" ] && echo "savegame : $WORLD.sav present" || { echo "savegame : $WORLD.sav missing (import-save)"; bad=1; }
+ fi
+ return $bad
+}
+
+cmd_login() {
+ ensure_dirs
+ exec python3 "$OPT/scripts/steam_session.py" login --file "$SESSION_FILE"
+}
+
+cmd_install_game() {
+ local src=${1:?usage: install-game }
+ ensure_dirs
+ [ -d "$src/common/Transport Fever 3" ] && [ -f "$src/appmanifest_$APPID.acf" ] \
+ || die "$src is not a Steam library folder holding Transport Fever 3 (expected common/Transport Fever 3 and appmanifest_$APPID.acf)" 31
+ supports_sparse "$GAME" || die "$GAME does not support sparse files: put the game volume on ext4, xfs or btrfs" 32
+ local need=3; [ "$(free_gb "$GAME")" -ge $need ] || die "less than $need GB free on $GAME" 33
+ log "building the lite install (a few minutes: the host's own files are read once, the 3D data is left out)"
+ python3 "$OPT/scripts/mklite.py" "$src/common/Transport Fever 3" "$GAME" || die "lite install failed" 34
+ cp "$src/appmanifest_$APPID.acf" "$STEAM_DIR/steamapps/"
+ log "game installed ($(du -sh --apparent-size "$GAME" | cut -f1) apparent, $(du -sh "$GAME" | cut -f1) on disk)"
+}
+
+cmd_import_save() {
+ [ $# -gt 0 ] || die "usage: import-save [more files of the same save]" 2
+ [ -f "$SESSION_FILE" ] || die "sign in first (login): the save folder depends on the Steam account" 40
+ local d f; d=$(save_dir); mkdir -p "$d"
+ for f in "$@"; do cp -v "$f" "$d/"; done
+}
+
+cmd_run() {
+ ensure_dirs
+ : "${WORLD:?set WORLD to the name of a savegame (without .sav)}"
+ [ -f "$SESSION_FILE" ] || die "no Steam session: run login first (README.md, step 3)" 40
+ python3 "$OPT/scripts/steam_session.py" status --file "$SESSION_FILE" >/dev/null \
+ || die "the Steam session has expired: run login again" 41
+ [ -f "$GAME/TransportFever3.exe" ] || die "no game install in $GAME: run install-game (README.md, step 2)" 30
+ supports_sparse "$GAME" || warn "$GAME has no sparse-file support: only a full copy of the game works there"
+ local ram; ram=$(awk '/MemTotal/ {printf "%d", $2/1048576}' /proc/meminfo)
+ [ "$ram" -ge 12 ] || warn "only $ram GB of RAM visible: the game needs about 11 GB"
+ init_prefix; ensure_client; link_game
+ [ -f "$(save_dir)/$WORLD.sav" ] || die "savegame '$WORLD.sav' not found: run import-save (README.md, step 4)" 42
+ # the game's settings: a minimal profile (lowest graphics) the first time; MPFever activates its mod in it
+ [ -f "$(local_dir)/settings.lua" ] || { mkdir -p "$(local_dir)"; cp "$OPT/config/settings.lua" "$(local_dir)/settings.lua"; }
+
+ # the launcher package of this image version, and the server settings from the environment (the file is rewritten at every start)
+ cp -a "$OPT/pkg/." "$SRV/"
+ cd "$SRV" || die "cannot enter $SRV" 10
+ printf 'servermode=headless\nautoupdate=0\n' > mpfever_settings.txt
+ {
+ echo "server-name=${SERVER_NAME:-MPFever Server}"
+ echo "world=$WORLD"
+ echo "port=${PORT:-28090}"
+ echo "password=${PASSWORD:-}"
+ echo "max-players=${MAX_PLAYERS:-8}"
+ echo "company-mode=${COMPANY_MODE:-shared}"
+ echo "start-speed=${START_SPEED:-1}"
+ echo "pause-when-empty=${PAUSE_WHEN_EMPTY:-false}"
+ echo "player-speed-control=${PLAYER_SPEED_CONTROL:-true}"
+ echo "autosave-minutes=${AUTOSAVE_MINUTES:-10}"
+ echo "backups=${BACKUPS:-10}"
+ echo "restart-on-crash=true"
+ echo "public=${PUBLIC:-false}"
+ echo "public-address=${PUBLIC_ADDRESS:-}"
+ echo "motd=${MOTD:-}"
+ } > mpfever_server.properties
+
+ # Madeira Dock: Valve's own client library signs in with the remembered session, checks the licence and starts the game
+ AUTH="$RUN/dock-auth.mdock"; STOPFILE="$RUN/stop"
+ rm -f "$AUTH" "$STOPFILE"
+ python3 "$OPT/scripts/steam_session.py" feed --file "$SESSION_FILE" --out "$AUTH" --app "$APPID" & FEEDER=$!
+ export MADEIRA_STEAM_HOST_PROBE=1 MADEIRA_STEAM_HOST_SESSION=1 MADEIRA_STEAM_HOST_LOGIN=1 MADEIRA_STEAM_HOST_APPID=$APPID
+ export MADEIRA_DOCK_AUTH_FILE="Z:${AUTH//\//\\}"
+ export MADEIRA_STEAM_HOST_CLIENT_DIR='C:\Program Files (x86)\Steam'
+ export MADEIRA_STEAM_HOST_EXPECTED_INSTALL='C:\Program Files (x86)\Steam\steamapps\common\Transport Fever 3'
+ export MADEIRA_STEAM_HOST_LOG=$SRV/dock.log
+ export MPFEVER_DOCK='Z:\opt\mpfever\dockhost.exe'
+ export MPFEVER_WINE=1 MPFEVER_STEAMPATH="$STEAM_DIR" MPFEVER_JOINREVIEW=0 MPFEVER_STOPFILE=$STOPFILE
+ # no 3D output: software Vulkan with a layer that makes every draw and copy a no-op and gives back the GPU memory nobody reads;
+ # MPF_VKNULL=0 (docker compose: GPU=1) leaves a real GPU alone
+ export MPF_VKNULL=${MPF_VKNULL:-1} MPF_VKNULL_MODE=all MPF_VKNULL_TRIM=${MPF_VKNULL_TRIM:-1}
+ export MPFEVER_ENV_HOST="${MPFEVER_ENV_HOST:-MPFEVER_HEADLESS_NORENDER=1;MPFEVER_HEADLESS_FPS=10}"
+
+ rm -f /tmp/.X1-lock /tmp/.X11-unix/X1
+ Xvfb :1 -screen 0 1024x768x24 -nolisten tcp >/dev/null 2>&1 & XVFB=$!
+ sleep 2
+
+ STOPPING=0; LAUNCHER=0
+ on_term() {
+ STOPPING=1; log "stop requested: saving the world and closing the game"
+ touch "$STOPFILE"
+ local i; for i in $(seq 1 "${STOP_TIMEOUT:-50}"); do kill -0 "$LAUNCHER" 2>/dev/null || break; sleep 1; done
+ kill "$LAUNCHER" 2>/dev/null; wineserver -k 2>/dev/null
+ }
+ trap on_term TERM INT
+
+ log "starting the server '${SERVER_NAME:-MPFever Server}': world '$WORLD', port ${PORT:-28090}, Steam account $(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["account"])' "$SESSION_FILE")"
+ local quick=0 t0
+ while [ "$STOPPING" = 0 ]; do
+ t0=$(date +%s)
+ mono MPFever.exe --server --server-start headless >> "$SRV/launcher.out" 2>&1 & LAUNCHER=$!
+ # the launcher's own log (one file per start) is the useful log: show it in `docker logs`
+ sleep 5; tail -n 0 -F "$(ls -t "$SRV"/logs/launcher-*.log 2>/dev/null | head -1)" 2>/dev/null & TAILER=$!
+ wait "$LAUNCHER"; rc=$?
+ kill "$TAILER" 2>/dev/null
+ [ "$STOPPING" = 1 ] && break
+ [ "$(date +%s)" -lt $((t0 + 60)) ] && quick=$((quick + 1)) || quick=0
+ [ "$quick" -lt 5 ] || { kill "$FEEDER" "$XVFB" 2>/dev/null; die "the launcher stopped 5 times within a minute (last status $rc): see $SRV/launcher.out and $SRV/dock.log" 50; }
+ log "the launcher stopped (status $rc): starting it again in 10 s"; sleep 10
+ done
+ kill "$FEEDER" "$XVFB" 2>/dev/null; wineserver -k 2>/dev/null
+ log "stopped"
+}
+
+case "$MODE" in
+ run) cmd_run ;;
+ login) cmd_login ;;
+ install-game) cmd_install_game "$@" ;;
+ import-save) cmd_import_save "$@" ;;
+ status) cmd_status ;;
+ shell) exec bash ;;
+ *) die "unknown mode '$MODE' (run, login, install-game, import-save, status, shell)" 2 ;;
+esac
diff --git a/server/scripts/healthcheck.sh b/server/scripts/healthcheck.sh
new file mode 100644
index 00000000..d2c9cb4d
--- /dev/null
+++ b/server/scripts/healthcheck.sh
@@ -0,0 +1,9 @@
+#!/bin/bash
+# Docker healthcheck: healthy when the launcher runs and its log moved in the last 2 minutes (it writes at least every few seconds
+# while the world runs; a frozen game is restarted by the launcher's own watchdog, a missing process by the entrypoint).
+pgrep -f 'mono MPFever.exe' >/dev/null || { echo "launcher not running"; exit 1; }
+f=$(ls -t /data/srv/logs/launcher-*.log 2>/dev/null | head -1)
+[ -n "$f" ] || { echo "no launcher log yet"; exit 1; }
+age=$(( $(date +%s) - $(stat -c %Y "$f") ))
+[ "$age" -lt 120 ] || { echo "launcher log silent for ${age}s"; exit 1; }
+echo ok
diff --git a/server/scripts/lib.sh b/server/scripts/lib.sh
new file mode 100644
index 00000000..705c04db
--- /dev/null
+++ b/server/scripts/lib.sh
@@ -0,0 +1,32 @@
+# shellcheck shell=bash
+# Shared definitions of the MPFever dedicated server scripts (sourced by entrypoint.sh).
+
+export HOME=/data
+export DATA=/data GAME=/game
+export WINEPREFIX=$DATA/wine WINEARCH=win64 WINEDEBUG=-all WINEDLLOVERRIDES="mscoree,mshtml=" DISPLAY=:1
+export STEAM_DIR="$WINEPREFIX/drive_c/Program Files (x86)/Steam"
+export SRV=$DATA/srv RUN=$DATA/run SECRETS=$DATA/secrets
+export SESSION_FILE=$SECRETS/steam.json
+export APPID=3493540
+GAME_LINK="$STEAM_DIR/steamapps/common/Transport Fever 3"
+OPT=/opt/mpfever
+
+# Valve's Steam client build driven by Madeira Dock, pinned (docs/COMPATIBILITY.md). Never updated by itself.
+CLIENT_URL=https://client-update.akamai.steamstatic.com/bins_win32.zip.23e34a6d4b10596a44561a5100dac5585d2517da
+CLIENT_ZIP_SHA256=8b712b2a3412a9066b7725f4e1c5cef9a7ca5b187b6585a5b92d25d09df0ba62
+CLIENT_DLL_SHA256=71b391fe9f3e2006cbc81a5c75eef3eb4186012deabfdb2c8b7e8d4850ecf640
+
+log() { echo "$(date -u +%H:%M:%S) [mpfever-server] $*"; }
+warn() { echo "$(date -u +%H:%M:%S) [mpfever-server] WARNING: $*" >&2; }
+die() { echo "$(date -u +%H:%M:%S) [mpfever-server] ERROR: $1" >&2; exit "${2:-1}"; }
+
+sha256_of() { sha256sum "$1" 2>/dev/null | cut -d' ' -f1; }
+
+# true if the game volume supports sparse files (the lite install needs them)
+supports_sparse() {
+ local f; f=$(mktemp -p "$1" .sparse-test.XXXXXX) || return 1
+ truncate -s 64M "$f"; local blocks; blocks=$(stat -c %b "$f"); rm -f "$f"
+ [ "$blocks" -lt 1024 ]
+}
+
+free_gb() { df -BG --output=avail "$1" | tail -1 | tr -dc '0-9'; }
diff --git a/server/scripts/mklite.py b/server/scripts/mklite.py
new file mode 100644
index 00000000..5722ad2b
--- /dev/null
+++ b/server/scripts/mklite.py
@@ -0,0 +1,178 @@
+# LITE copy (v3) of a Transport Fever 3 install or of a mod, for a server without rendering. Run on Linux, from the host's own files.
+# Every archive keeps its exact byte layout (the engine reads entries at the offsets of its central directory). For the entries stored
+# without compression:
+# .dds .wav .ogg .blob : the data is not copied (a hole in the file: no disk space, reads as zeros) except its first KEEP bytes
+# .tga : rewritten as a valid image of the same size, all pixels 0 (RLE or raw as the original), the rest is a hole
+# .png : rewritten as a valid PNG of the same size and format, all pixels 0 (one tiny zlib stream), the rest is a hole
+# Loose files of a mod folder are treated the same way (same rules, same code). Everything else is copied as it is.
+import os, sys, struct, zipfile, zlib, shutil, time
+
+KEEP = 512
+HOLE_EXT = {'.dds', '.wav', '.ogg', '.blob'}
+CH = 8 * 1024 * 1024
+
+
+def tga_stub(data, avail):
+ """a TGA of the same size with zero pixels, in at most avail bytes, or None if the format is not handled"""
+ if len(data) < 18:
+ return None
+ idlen, cmap, itype = data[0], data[1], data[2]
+ w, h = struct.unpack(' 0:
+ k = min(n, 128)
+ out.append(0x80 | (k - 1)); out += zero; n -= k
+ if len(out) > avail:
+ return None
+ return bytes(out), len(out)
+
+
+def png_stub(data, avail):
+ if data[:8] != b'\x89PNG\r\n\x1a\n':
+ return None
+ pos = 8; chunks = []; ihdr = None
+ while pos + 8 <= len(data):
+ ln, typ = struct.unpack('>I4s', data[pos:pos + 8])
+ body = data[pos + 8:pos + 8 + ln]
+ chunks.append((typ, body)); pos += 12 + ln
+ if typ == b'IHDR':
+ ihdr = body
+ if typ == b'IEND':
+ break
+ if ihdr is None or len(ihdr) < 13:
+ return None
+ w, h, depth, ctype, comp, flt, interlace = struct.unpack('>IIBBBBB', ihdr[:13])
+ if interlace != 0 or w == 0 or h == 0:
+ return None
+ ch = {0: 1, 2: 3, 3: 1, 4: 2, 6: 4}.get(ctype)
+ if ch is None:
+ return None
+ rowbytes = (w * ch * depth + 7) // 8
+ raw = b'\x00' * ((rowbytes + 1) * h) # filter byte 0 + zero pixels
+ idat = zlib.compress(raw, 9)
+ out = bytearray(b'\x89PNG\r\n\x1a\n')
+ done = False
+ for typ, body in chunks:
+ if typ == b'IDAT':
+ if not done:
+ done = True
+ out += struct.pack('>I', len(idat)) + b'IDAT' + idat + struct.pack('>I', zlib.crc32(b'IDAT' + idat) & 0xffffffff)
+ continue
+ out += struct.pack('>I', len(body)) + typ + body + struct.pack('>I', zlib.crc32(typ + body) & 0xffffffff)
+ if not done or len(out) > avail:
+ return None
+ return bytes(out), len(out)
+
+
+def plan_entry(ext, data_len, read):
+ """(bytes to write at the start of the entry's data, offset from which it is a hole) or None to keep the entry"""
+ if ext in HOLE_EXT:
+ return (None, KEEP) if data_len > KEEP else None
+ if ext in ('.tga', '.png'):
+ r = (tga_stub if ext == '.tga' else png_stub)(read(), data_len)
+ if r is None:
+ return None
+ new, used = r
+ used = max(len(new), used)
+ return (new, used) if data_len > used + 64 else None
+ return None
+
+
+def process_zip(s, d, stats):
+ size = os.path.getsize(s)
+ plans = [] # (data_start, data_end, new_bytes_or_None, hole_from_offset)
+ with zipfile.ZipFile(s) as z, open(s, 'rb') as fi:
+ for i in z.infolist():
+ if i.is_dir() or i.compress_type != zipfile.ZIP_STORED:
+ continue
+ ext = os.path.splitext(i.filename)[1].lower()
+ if ext not in HOLE_EXT and ext not in ('.tga', '.png'):
+ continue
+ fi.seek(i.header_offset); h = fi.read(30)
+ if h[:4] != b'PK\x03\x04':
+ continue
+ nlen, elen = struct.unpack(' pos:
+ copy_range(fi, fo, pos, ds, stats)
+ if new is None: # keep the first hole_from bytes, hole the rest
+ copy_range(fi, fo, ds, ds + hole_from, stats)
+ else:
+ fo.seek(ds); fo.write(new); stats['written'] += len(new)
+ stats['hole'] += de - (ds + hole_from)
+ pos = de
+ if pos < size:
+ copy_range(fi, fo, pos, size, stats)
+ stats['plans'] += len(plans)
+
+
+def copy_range(fi, fo, a, b, stats):
+ fi.seek(a); fo.seek(a); n = b - a
+ while n > 0:
+ buf = fi.read(min(CH, n))
+ if not buf:
+ break
+ fo.write(buf); n -= len(buf); stats['copied'] += len(buf)
+
+
+def process_loose(s, d, stats):
+ ext = os.path.splitext(s)[1].lower()
+ size = os.path.getsize(s)
+ if ext in HOLE_EXT or ext in ('.tga', '.png'):
+ with open(s, 'rb') as fi:
+ def read():
+ fi.seek(0); return fi.read()
+ p = plan_entry(ext, size, read)
+ if p:
+ new, hole_from = p
+ with open(d, 'wb') as fo:
+ fo.truncate(size)
+ if new is None:
+ fi.seek(0); fo.write(fi.read(hole_from))
+ else:
+ fo.write(new)
+ stats['hole'] += size - hole_from; stats['plans'] += 1
+ return
+ shutil.copy2(s, d)
+
+
+if __name__ == '__main__':
+ SRC, DST = sys.argv[1], sys.argv[2]
+ stats = dict(hole=0, copied=0, written=0, plans=0)
+ t0 = time.time(); nz = 0
+ for dp, dn, fn in os.walk(SRC):
+ out = os.path.join(DST, os.path.relpath(dp, SRC))
+ os.makedirs(out, exist_ok=True)
+ for f in fn:
+ s = os.path.join(dp, f); d = os.path.join(out, f)
+ if f.lower().endswith('.zip'):
+ nz += 1; process_zip(s, d, stats)
+ if nz % 200 == 0:
+ print('zips', nz, int(time.time() - t0), 's', flush=True)
+ else:
+ process_loose(s, d, stats)
+ print('DONE zips', nz, 'entries rewritten/holed', stats['plans'], 'hole GB', round(stats['hole'] / 2**30, 2),
+ 'copied GB', round(stats['copied'] / 2**30, 2), 'stubs MB', round(stats['written'] / 2**20, 1), 'in', int(time.time() - t0), 's')
diff --git a/server/scripts/steam_session.py b/server/scripts/steam_session.py
new file mode 100644
index 00000000..4ee55e63
--- /dev/null
+++ b/server/scripts/steam_session.py
@@ -0,0 +1,134 @@
+#!/usr/bin/env python3
+"""Steam session of the dedicated server: sign in once (QR code, no password, no graphical interface), keep the refresh token, and hand it to
+Madeira Dock at every game start as its one-use transfer file (format MDOCK001, see madeira-dock src/auth.c).
+
+ steam_session.py login [--file steam.json] QR sign-in with the Steam mobile app; stores the refresh token (mode 0600)
+ steam_session.py status [--file steam.json] account, SteamID, token expiry (exit 1: no usable session)
+ steam_session.py feed --file steam.json --out PATH --app 3493540 keeps PATH present for Dock (it deletes the file when it reads it)
+
+The token is never printed, never put on a command line or in an environment variable. Only Steam's own authentication service
+(IAuthenticationService on api.steampowered.com) is contacted, with the account owner's approval in the Steam mobile app."""
+import argparse, base64, json, os, struct, sys, time, urllib.parse, urllib.request
+
+API = "https://api.steampowered.com/IAuthenticationService/%s/v1/"
+STEAMID64_BASE = 76561197960265728 # account id -> SteamID64 (individual, public universe, desktop instance)
+
+
+def build_transfer(steamid, app, account, token):
+ """The bytes of the MDOCK001 transfer file (same checks as Dock's parser)."""
+ name, tok = account.encode("ascii"), token.encode("ascii")
+ sid = int(steamid)
+ if (sid >> 56) != 1 or ((sid >> 52) & 15) != 1 or ((sid >> 32) & 0xfffff) != 1 or not (sid & 0xffffffff):
+ raise ValueError("not an individual SteamID64")
+ if not 1 <= len(name) <= 64 or not all(33 <= c <= 126 for c in name):
+ raise ValueError("bad account name")
+ if not 1 <= len(tok) <= 8192 or not all(chr(c).isalnum() or chr(c) in "._-" for c in tok):
+ raise ValueError("bad token")
+ if not 0 < app < 0xffffffff:
+ raise ValueError("bad app id")
+ return b"MDOCK001" + struct.pack(" Sign in with QR) and approve:\n", flush=True)
+ try:
+ import qrcode
+ q = qrcode.QRCode(border=1)
+ q.add_data(url)
+ q.print_ascii(invert=True)
+ except Exception:
+ pass
+ print("\nOr open this link in the Steam mobile app:\n %s\n" % url, flush=True)
+
+
+def cmd_login(a):
+ r = call("BeginAuthSessionViaQR", {"device_friendly_name": "MPFever dedicated server", "platform_type": 1})
+ cid, rid, interval = r["client_id"], r["request_id"], max(int(r.get("interval", 5)), 2)
+ show_qr(r["challenge_url"])
+ deadline = time.time() + 600
+ while time.time() < deadline:
+ time.sleep(interval)
+ p = call("PollAuthSessionStatus", {"client_id": cid, "request_id": rid})
+ if p.get("new_client_id"): # the QR code was renewed
+ cid = p["new_client_id"]
+ if p.get("new_challenge_url"):
+ show_qr(p["new_challenge_url"])
+ if p.get("refresh_token") and p.get("account_name"):
+ claims = jwt_claims(p["refresh_token"])
+ sess = {"account": p["account_name"], "steamid": str(claims["sub"]), "refresh_token": p["refresh_token"],
+ "expires": claims.get("exp"), "created": int(time.time())}
+ os.makedirs(os.path.dirname(os.path.abspath(a.file)), mode=0o700, exist_ok=True)
+ write_private(a.file, json.dumps(sess).encode())
+ print("Signed in as %s (SteamID %s). Session saved (valid until %s)." % (
+ sess["account"], sess["steamid"], time.strftime("%Y-%m-%d", time.gmtime(sess["expires"])) if sess["expires"] else "?"))
+ return 0
+ print("Timed out: the code was not approved within 10 minutes.", file=sys.stderr)
+ return 1
+
+
+def load(path):
+ with open(path) as f:
+ s = json.load(f)
+ for k in ("account", "steamid", "refresh_token"):
+ if not s.get(k):
+ raise ValueError("incomplete session file (%s)" % k)
+ return s
+
+
+def cmd_status(a):
+ try:
+ s = load(a.file)
+ except Exception as e:
+ print("no usable Steam session: %s" % e, file=sys.stderr)
+ return 1
+ exp = s.get("expires")
+ left = (exp - time.time()) / 86400 if exp else None
+ print("account %s, SteamID %s, token %s" % (s["account"], s["steamid"],
+ "valid for %.0f more days" % left if left is not None and left > 0 else ("EXPIRED" if left is not None else "expiry unknown")))
+ return 0 if left is None or left > 0 else 1
+
+
+def cmd_feed(a):
+ s = load(a.file)
+ data = build_transfer(s["steamid"], a.app, s["account"], s["refresh_token"])
+ while True:
+ if not os.path.exists(a.out):
+ write_private(a.out, data)
+ time.sleep(1)
+
+
+def main(argv=None):
+ ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
+ sub = ap.add_subparsers(dest="cmd", required=True)
+ for name in ("login", "status", "feed"):
+ p = sub.add_parser(name)
+ p.add_argument("--file", default=os.environ.get("STEAM_SESSION_FILE", "/data/secrets/steam.json"))
+ if name == "feed":
+ p.add_argument("--out", required=True)
+ p.add_argument("--app", type=int, default=3493540)
+ a = ap.parse_args(argv)
+ return {"login": cmd_login, "status": cmd_status, "feed": cmd_feed}[a.cmd](a)
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/server/tests/__init__.py b/server/tests/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/server/tests/check.sh b/server/tests/check.sh
new file mode 100644
index 00000000..eb845e64
--- /dev/null
+++ b/server/tests/check.sh
@@ -0,0 +1,30 @@
+#!/usr/bin/env bash
+# Static, reproducible checks of server/ (no game, no network, no Docker build): run from the repository root or from server/.
+set -euo pipefail
+cd "$(dirname "$0")/.."
+fail=0
+step() { echo "== $*"; }
+
+step "shell syntax"
+for f in scripts/*.sh tests/check.sh; do bash -n "$f" || fail=1; done
+if command -v shellcheck >/dev/null; then step "shellcheck"; shellcheck -S warning scripts/*.sh || fail=1; fi
+
+step "python"
+python3 -m py_compile scripts/*.py || fail=1
+python3 -m unittest -q tests.test_steam_session 2>&1 | tail -3 || fail=1
+python3 tests/selftest_lite.py | tail -2 || fail=1
+
+step "compose"
+WORLD=check docker compose -f compose.yaml config -q || fail=1
+WORLD=check docker compose -f compose.yaml -f compose.build.yaml config -q || fail=1
+WORLD=check docker compose -f compose.yaml -f compose.gpu.yaml config -q || fail=1
+
+step "no secrets, no binaries, no proprietary files"
+if git ls-files --error-unmatch . >/dev/null 2>&1; then files=$(git ls-files .); else files=$(find . -type f -not -path './dist/*' | sed 's#^\./##'); fi
+bad=$(echo "$files" | grep -Ei '\.(exe|dll|so|zip|sav|ba[rs]|7z|pdb)$' || true)
+[ -z "$bad" ] || { echo "binary or game file in server/: $bad"; fail=1; }
+leak=$(echo "$files" | grep -v '^tests/' | xargs grep -lE 'eyJ[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{20,}|"refresh_token"[[:space:]]*:[[:space:]]*"[A-Za-z0-9._-]{20,}"|7656119[89][0-9]{9}' 2>/dev/null || true)
+[ -z "$leak" ] || { echo "possible secret in: $leak"; fail=1; }
+[ -f .env ] && { echo ".env must not be committed"; git ls-files --error-unmatch .env >/dev/null 2>&1 && fail=1; }
+
+[ "$fail" = 0 ] && echo "ALL CHECKS PASSED" || { echo "CHECKS FAILED"; exit 1; }
diff --git a/server/tests/selftest_lite.py b/server/tests/selftest_lite.py
new file mode 100644
index 00000000..ec1462a4
--- /dev/null
+++ b/server/tests/selftest_lite.py
@@ -0,0 +1,57 @@
+import os, struct, zlib, random, shutil, sys, tempfile
+sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'scripts'))
+import mklite as M
+random.seed(1)
+tmp = tempfile.mkdtemp(prefix='fakemod_')
+src = os.path.join(tmp, 'src', 'mymod', 'res'); dst = os.path.join(tmp, 'dst')
+os.makedirs(src)
+def png(w, h):
+ raw = b''.join(b'\x00' + bytes(random.randrange(256) for _ in range(w * 4)) for _ in range(h))
+ def ch(t, b): return struct.pack('>I', len(b)) + t + b + struct.pack('>I', zlib.crc32(t + b) & 0xffffffff)
+ return b'\x89PNG\r\n\x1a\n' + ch(b'IHDR', struct.pack('>IIBBBBB', w, h, 8, 6, 0, 0, 0)) + ch(b'IDAT', zlib.compress(raw, 1)) + ch(b'IEND', b'')
+def tga_rle(w, h):
+ out = bytearray(b'\x00\x00\x0a' + b'\x00' * 9 + struct.pack('I4s', o[pos:pos+8]); b = o[pos+8:pos+8+ln]
+ crc_ok &= (struct.unpack('>I', o[pos+8+ln:pos+12+ln])[0] == zlib.crc32(t + b) & 0xffffffff)
+ if t == b'IDAT': idat += b
+ pos += 12 + ln
+ if t == b'IEND': break
+ raw = zlib.decompress(idat); msg = 'png decodes to %d bytes (expected %d), crc ok=%s, all zero=%s' % (len(raw), (256*4+1)*256, crc_ok, raw.count(0) == len(raw) - 0)
+ if n == 'tex/b.tga':
+ w, h = 128, 128; px = 0; pos = 18
+ while px < w * h:
+ c = o[pos]; pos += 1; k = (c & 127) + 1
+ if c & 128: pos += 4
+ else: pos += 4 * k
+ px += k
+ msg = 'rle tga decodes %d pixels (expected %d), stream ends at byte %d of %d' % (px, w*h, pos, len(o))
+ print('%-14s size kept=%s %s' % (n, sz_ok, msg))
+ ok &= sz_ok
+print('ALL SIZES KEPT' if ok else 'SIZE MISMATCH')
+du = sum(getattr(os.stat(os.path.join(dp, f)), 'st_blocks', 0) * 512 for dp, dn, fn in os.walk(dst) for f in fn)
+print('allocated in dst (bytes):', du, ' logical:', sum(len(d) for d in files.values()))
+shutil.rmtree(tmp)
+sys.exit(0 if ok else 1)
diff --git a/server/tests/test_steam_session.py b/server/tests/test_steam_session.py
new file mode 100644
index 00000000..82714a4d
--- /dev/null
+++ b/server/tests/test_steam_session.py
@@ -0,0 +1,66 @@
+"""Checks of scripts/steam_session.py that need no network: the MDOCK001 transfer file against an independent copy of Madeira Dock's parser rules
+(src/auth.c), the JWT claims, and the owner-only mode of the stored session."""
+import base64, json, os, stat, struct, sys, tempfile, unittest
+
+sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "scripts"))
+import steam_session as S
+
+STEAMID = "76561198000000001"
+def _b64(d):
+ return base64.urlsafe_b64encode(json.dumps(d).encode()).rstrip(b"=").decode()
+
+
+TOKEN = _b64({"alg": "EdDSA", "typ": "JWT"}) + "." + _b64({"sub": STEAMID, "exp": 2000000000}) + ".c2ln-_x"
+
+
+def dock_parse(b):
+ """The checks of dock_auth_parse (madeira-dock src/auth.c): returns (steamid, app, account, token) or None."""
+ if len(b) < 24 or len(b) > 24 + 64 + 8192 or b[:8] != b"MDOCK001":
+ return None
+ sid, app, ns, nt = struct.unpack("> 56) != 1 or ((sid >> 52) & 15) != 1 or ((sid >> 32) & 0xfffff) != 1 or not (sid & 0xffffffff) or not app or app == 0xffffffff:
+ return None
+ if not ns or ns > 64 or not nt or nt > 8192 or len(b) != 24 + ns + nt:
+ return None
+ name, tok = b[24:24 + ns], b[24 + ns:]
+ if any(c < 33 or c > 126 for c in name) or not all(chr(c).isalnum() or chr(c) in "._-" for c in tok):
+ return None
+ return sid, app, name.decode(), tok.decode()
+
+
+class Transfer(unittest.TestCase):
+ def test_roundtrip_accepted_by_dock_rules(self):
+ b = S.build_transfer(STEAMID, 3493540, "some_account", TOKEN)
+ self.assertEqual(dock_parse(b), (int(STEAMID), 3493540, "some_account", TOKEN))
+
+ def test_rejects_bad_input(self):
+ for args in [("12345", 3493540, "a", TOKEN), (STEAMID, 0, "a", TOKEN), (STEAMID, 3493540, "", TOKEN),
+ (STEAMID, 3493540, "a b", TOKEN), (STEAMID, 3493540, "a", ""), (STEAMID, 3493540, "a", "tok en"),
+ (STEAMID, 3493540, "a" * 65, TOKEN), (STEAMID, 3493540, "a", "x" * 8193)]:
+ with self.assertRaises(ValueError):
+ S.build_transfer(*args)
+
+ def test_jwt_claims(self):
+ self.assertEqual(S.jwt_claims(TOKEN)["sub"], STEAMID)
+
+
+class Storage(unittest.TestCase):
+ @unittest.skipIf(os.name == "nt", "POSIX modes")
+ def test_private_file_mode(self):
+ with tempfile.TemporaryDirectory() as d:
+ p = os.path.join(d, "steam.json")
+ S.write_private(p, b"{}")
+ self.assertEqual(stat.S_IMODE(os.stat(p).st_mode), 0o600)
+
+ def test_status_missing_and_expired(self):
+ with tempfile.TemporaryDirectory() as d:
+ p = os.path.join(d, "steam.json")
+ self.assertEqual(S.main(["status", "--file", p]), 1)
+ json.dump({"account": "a", "steamid": STEAMID, "refresh_token": TOKEN, "expires": 1}, open(p, "w"))
+ self.assertEqual(S.main(["status", "--file", p]), 1)
+ json.dump({"account": "a", "steamid": STEAMID, "refresh_token": TOKEN, "expires": 4000000000}, open(p, "w"))
+ self.assertEqual(S.main(["status", "--file", p]), 0)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/server/vklayer/VkLayer_mpf_nulldraw.json b/server/vklayer/VkLayer_mpf_nulldraw.json
new file mode 100644
index 00000000..37bed020
--- /dev/null
+++ b/server/vklayer/VkLayer_mpf_nulldraw.json
@@ -0,0 +1,14 @@
+{
+ "file_format_version": "1.1.2",
+ "layer": {
+ "name": "VK_LAYER_MPF_nulldraw",
+ "type": "GLOBAL",
+ "library_path": "/opt/mpfever/libVkLayer_mpf_nulldraw.so",
+ "api_version": "1.3.0",
+ "implementation_version": "1",
+ "description": "MPFever dedicated server: draw and copy commands are no-ops, mapped GPU memory is given back (no GPU needed)",
+ "functions": { "vkNegotiateLoaderLayerInterfaceVersion": "vkNegotiateLoaderLayerInterfaceVersion" },
+ "enable_environment": { "MPF_VKNULL": "1" },
+ "disable_environment": { "MPF_VKNULL_OFF": "1" }
+ }
+}
diff --git a/server/vklayer/vk_nulldraw.c b/server/vklayer/vk_nulldraw.c
new file mode 100644
index 00000000..2aadb7ed
--- /dev/null
+++ b/server/vklayer/vk_nulldraw.c
@@ -0,0 +1,171 @@
+/* POC (local): implicit Vulkan layer that turns draw/dispatch commands into no-ops.
+ * Goal: a game server with no GPU (software Vulkan) does not pay for pixels nobody sees.
+ * Independent of the game binary (no addresses), same source for Linux and Windows.
+ * Enabled by MPF_VKNULL=1 (any other value or unset: the layer is inert, a real GPU is used as usual).
+ * MPF_VKNULL_MODE: "draw" (default) = draws + dispatches ; "all" = also clears/copies/blits/resolves. */
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+#ifdef _WIN32
+#define EXPORT __declspec(dllexport)
+#else
+#define EXPORT __attribute__((visibility("default")))
+#endif
+
+static PFN_vkGetInstanceProcAddr g_nextGipa;
+static PFN_vkGetDeviceProcAddr g_nextGdpa;
+static int g_on = -1, g_all = 0;
+static unsigned long long g_calls;
+
+static void init_env(void)
+{
+ if (g_on >= 0) return;
+ const char* v = getenv("MPF_VKNULL");
+ g_on = (v && v[0] == '1') ? 1 : 0;
+ const char* m = getenv("MPF_VKNULL_MODE");
+ g_all = (m && !strcmp(m, "all")) ? 1 : 0;
+ if (g_on) fprintf(stderr, "[mpf-vknull] active (mode=%s)\n", g_all ? "all" : "draw");
+}
+
+/* one function serves every void-returning command: the caller cleans the stack/regs (cdecl / SysV / Win64) */
+static void VKAPI_CALL noop_cmd(void) { g_calls++; }
+
+static const char* const k_draw[] = {
+ "vkCmdDraw", "vkCmdDrawIndexed", "vkCmdDrawIndirect", "vkCmdDrawIndexedIndirect",
+ "vkCmdDrawIndirectCount", "vkCmdDrawIndexedIndirectCount", "vkCmdDrawIndirectCountKHR",
+ "vkCmdDrawIndexedIndirectCountKHR", "vkCmdDrawMultiEXT", "vkCmdDrawMultiIndexedEXT",
+ "vkCmdDrawMeshTasksEXT", "vkCmdDrawMeshTasksIndirectEXT",
+ "vkCmdDispatch", "vkCmdDispatchIndirect", "vkCmdDispatchBase", "vkCmdDispatchBaseKHR", 0 };
+static const char* const k_all[] = {
+ "vkCmdClearColorImage", "vkCmdClearDepthStencilImage", "vkCmdClearAttachments",
+ "vkCmdBlitImage", "vkCmdBlitImage2", "vkCmdResolveImage", "vkCmdResolveImage2",
+ "vkCmdCopyImage", "vkCmdCopyImage2",
+ /* mode "memory": the uploads that fill the (software) GPU memory: nobody reads it on a server */
+ "vkCmdCopyBufferToImage", "vkCmdCopyBufferToImage2", "vkCmdCopyBuffer", "vkCmdCopyBuffer2", "vkCmdCopyImageToBuffer",
+ "vkCmdCopyImageToBuffer2", "vkCmdUpdateBuffer", "vkCmdFillBuffer",
+ /* the render passes themselves (their load/clear/resolve work is the remaining software-GPU cost): all of them or none */
+ "vkCmdBeginRenderPass", "vkCmdBeginRenderPass2", "vkCmdBeginRenderPass2KHR", "vkCmdEndRenderPass", "vkCmdEndRenderPass2",
+ "vkCmdEndRenderPass2KHR", "vkCmdNextSubpass", "vkCmdNextSubpass2", "vkCmdNextSubpass2KHR", "vkCmdBeginRendering",
+ "vkCmdBeginRenderingKHR", "vkCmdEndRendering", "vkCmdEndRenderingKHR", "vkCmdExecuteCommands", 0 };
+
+static int in_list(const char* const* l, const char* n)
+{
+ for (; *l; ++l) if (!strcmp(*l, n)) return 1;
+ return 0;
+}
+
+
+/* MPF_VKNULL_TRIM=1 (RAM): nothing is ever drawn, so what the game wrote into mapped GPU memory is never read by anyone. Every TRIM_EVERY
+ * submits the pages of the big mapped ranges are given back to the system (they read as zeros afterwards). Off by default. */
+#define TRIM_EVERY 30
+#define MAXMAP 8192
+static struct { VkDeviceMemory m; char* p; size_t n; } g_map[MAXMAP];
+static pthread_mutex_t g_mu = PTHREAD_MUTEX_INITIALIZER;
+static int g_trim = -1;
+static unsigned long long g_submits, g_trimmed;
+static PFN_vkMapMemory r_map; static PFN_vkUnmapMemory r_unmap; static PFN_vkFreeMemory r_free; static PFN_vkQueueSubmit r_submit;
+
+static VKAPI_ATTR VkResult VKAPI_CALL T_Map(VkDevice d, VkDeviceMemory m, VkDeviceSize off, VkDeviceSize sz, VkMemoryMapFlags f, void** pp)
+{
+ VkResult r = r_map(d, m, off, sz, f, pp);
+ if (r == VK_SUCCESS && sz != VK_WHOLE_SIZE && sz >= (1u << 20)) {
+ pthread_mutex_lock(&g_mu);
+ for (int i = 0; i < MAXMAP; i++) if (!g_map[i].m) { g_map[i].m = m; g_map[i].p = (char*)*pp; g_map[i].n = (size_t)sz; break; }
+ pthread_mutex_unlock(&g_mu);
+ }
+ return r;
+}
+static void forget(VkDeviceMemory m)
+{
+ pthread_mutex_lock(&g_mu);
+ for (int i = 0; i < MAXMAP; i++) if (g_map[i].m == m) g_map[i].m = 0;
+ pthread_mutex_unlock(&g_mu);
+}
+static VKAPI_ATTR void VKAPI_CALL T_Unmap(VkDevice d, VkDeviceMemory m) { forget(m); r_unmap(d, m); }
+static VKAPI_ATTR void VKAPI_CALL T_Free(VkDevice d, VkDeviceMemory m, const VkAllocationCallbacks* al) { forget(m); r_free(d, m, al); }
+static VKAPI_ATTR VkResult VKAPI_CALL T_Submit(VkQueue q, uint32_t n, const VkSubmitInfo* si, VkFence f)
+{
+ VkResult r = r_submit(q, n, si, f);
+ if (++g_submits % TRIM_EVERY == 0) {
+ long pg = sysconf(_SC_PAGESIZE);
+ pthread_mutex_lock(&g_mu);
+ for (int i = 0; i < MAXMAP; i++) if (g_map[i].m) {
+ uintptr_t a = ((uintptr_t)g_map[i].p + pg - 1) & ~(uintptr_t)(pg - 1), b = ((uintptr_t)g_map[i].p + g_map[i].n) & ~(uintptr_t)(pg - 1);
+ if (b > a && madvise((void*)a, b - a, MADV_DONTNEED) == 0) g_trimmed += b - a;
+ }
+ pthread_mutex_unlock(&g_mu);
+ }
+ return r;
+}
+
+static VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL L_GetDeviceProcAddr(VkDevice d, const char* n)
+{
+ init_env();
+ if (g_on && (in_list(k_draw, n) || (g_all && in_list(k_all, n)))) return (PFN_vkVoidFunction)noop_cmd;
+ if (g_trim < 0) { const char* t = getenv("MPF_VKNULL_TRIM"); g_trim = (g_on && t && t[0] == '1') ? 1 : 0; }
+ if (g_trim && g_nextGdpa) {
+ if (!strcmp(n, "vkMapMemory")) { if (!r_map) r_map = (PFN_vkMapMemory)g_nextGdpa(d, n); if (r_map) return (PFN_vkVoidFunction)T_Map; }
+ if (!strcmp(n, "vkUnmapMemory")) { if (!r_unmap) r_unmap = (PFN_vkUnmapMemory)g_nextGdpa(d, n); if (r_unmap) return (PFN_vkVoidFunction)T_Unmap; }
+ if (!strcmp(n, "vkFreeMemory")) { if (!r_free) r_free = (PFN_vkFreeMemory)g_nextGdpa(d, n); if (r_free) return (PFN_vkVoidFunction)T_Free; }
+ if (!strcmp(n, "vkQueueSubmit")) { if (!r_submit) r_submit = (PFN_vkQueueSubmit)g_nextGdpa(d, n); if (r_submit) return (PFN_vkVoidFunction)T_Submit; }
+ }
+ return g_nextGdpa ? g_nextGdpa(d, n) : 0;
+}
+
+static VKAPI_ATTR VkResult VKAPI_CALL L_CreateDevice(VkPhysicalDevice pd, const VkDeviceCreateInfo* ci,
+ const VkAllocationCallbacks* al, VkDevice* out)
+{
+ VkLayerDeviceCreateInfo* lci = (VkLayerDeviceCreateInfo*)ci->pNext;
+ while (lci && !(lci->sType == VK_STRUCTURE_TYPE_LOADER_DEVICE_CREATE_INFO && lci->function == VK_LAYER_LINK_INFO))
+ lci = (VkLayerDeviceCreateInfo*)lci->pNext;
+ if (!lci) return VK_ERROR_INITIALIZATION_FAILED;
+ PFN_vkGetInstanceProcAddr gipa = lci->u.pLayerInfo->pfnNextGetInstanceProcAddr;
+ PFN_vkGetDeviceProcAddr gdpa = lci->u.pLayerInfo->pfnNextGetDeviceProcAddr;
+ lci->u.pLayerInfo = lci->u.pLayerInfo->pNext;
+ PFN_vkCreateDevice next = (PFN_vkCreateDevice)gipa(VK_NULL_HANDLE, "vkCreateDevice");
+ VkResult r = next(pd, ci, al, out);
+ if (r == VK_SUCCESS) g_nextGdpa = gdpa;
+ return r;
+}
+
+static VKAPI_ATTR VkResult VKAPI_CALL L_CreateInstance(const VkInstanceCreateInfo* ci,
+ const VkAllocationCallbacks* al, VkInstance* out)
+{
+ VkLayerInstanceCreateInfo* lci = (VkLayerInstanceCreateInfo*)ci->pNext;
+ while (lci && !(lci->sType == VK_STRUCTURE_TYPE_LOADER_INSTANCE_CREATE_INFO && lci->function == VK_LAYER_LINK_INFO))
+ lci = (VkLayerInstanceCreateInfo*)lci->pNext;
+ if (!lci) return VK_ERROR_INITIALIZATION_FAILED;
+ PFN_vkGetInstanceProcAddr gipa = lci->u.pLayerInfo->pfnNextGetInstanceProcAddr;
+ lci->u.pLayerInfo = lci->u.pLayerInfo->pNext;
+ PFN_vkCreateInstance next = (PFN_vkCreateInstance)gipa(VK_NULL_HANDLE, "vkCreateInstance");
+ VkResult r = next(ci, al, out);
+ if (r == VK_SUCCESS) g_nextGipa = gipa;
+ return r;
+}
+
+static VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL L_GetInstanceProcAddr(VkInstance i, const char* n)
+{
+ if (!strcmp(n, "vkGetInstanceProcAddr")) return (PFN_vkVoidFunction)L_GetInstanceProcAddr;
+ if (!strcmp(n, "vkCreateInstance")) return (PFN_vkVoidFunction)L_CreateInstance;
+ if (!strcmp(n, "vkCreateDevice")) return (PFN_vkVoidFunction)L_CreateDevice;
+ if (!strcmp(n, "vkGetDeviceProcAddr")) return (PFN_vkVoidFunction)L_GetDeviceProcAddr;
+ return g_nextGipa ? g_nextGipa(i, n) : 0;
+}
+
+EXPORT VKAPI_ATTR VkResult VKAPI_CALL vkNegotiateLoaderLayerInterfaceVersion(VkNegotiateLayerInterface* p)
+{
+ if (p->loaderLayerInterfaceVersion >= 2) {
+ p->pfnGetInstanceProcAddr = L_GetInstanceProcAddr;
+ p->pfnGetDeviceProcAddr = L_GetDeviceProcAddr;
+ p->pfnGetPhysicalDeviceProcAddr = 0;
+ }
+ if (p->loaderLayerInterfaceVersion > 2) p->loaderLayerInterfaceVersion = 2;
+ return VK_SUCCESS;
+}
From 0c42c45fe2282392ac21cc9b4bf97ddbfb39e5d5 Mon Sep 17 00:00:00 2001
From: ampynjord <82981605+ampynjord@users.noreply.github.com>
Date: Thu, 19 Nov 2026 13:15:53 +0100
Subject: [PATCH 02/47] server: shellcheck fixes, apt mirror build argument,
configurable container name
---
server/Dockerfile | 7 +++++++
server/compose.yaml | 2 +-
server/scripts/entrypoint.sh | 4 ++--
server/scripts/lib.sh | 2 +-
4 files changed, 11 insertions(+), 4 deletions(-)
diff --git a/server/Dockerfile b/server/Dockerfile
index 118b8347..ec37bac8 100644
--- a/server/Dockerfile
+++ b/server/Dockerfile
@@ -6,11 +6,14 @@
# server/dist/MPFever-server.zip (the release\MPFever--server.zip of a build)
# The image contains no Transport Fever 3 file and no Valve file: the game is imported from the user's own copy (install-game) and Valve's
# client library is fetched from Valve at the first start.
+# --build-arg APT_MIRROR=http:///ubuntu uses another Ubuntu mirror (when archive.ubuntu.com is unreachable).
ARG UBUNTU=ubuntu:24.04
# ---------------------------------------------------------------- Madeira Dock, from source at a pinned commit (GPL-3.0-or-later)
FROM ${UBUNTU} AS dock
+ARG APT_MIRROR=
+RUN if [ -n "$APT_MIRROR" ]; then sed -i "s#http://archive.ubuntu.com/ubuntu#$APT_MIRROR#g; s#http://security.ubuntu.com/ubuntu#$APT_MIRROR#g" /etc/apt/sources.list.d/ubuntu.sources; fi
ARG DOCK_REPO=https://github.com/willfaust/madeira-dock.git
ARG DOCK_REF=67780ba92e60dbfac4fe80eaf2ce34b9ea1a1c60
RUN apt-get update -qq && apt-get install -y -qq --no-install-recommends ca-certificates git gcc-mingw-w64-x86-64 >/dev/null \
@@ -21,12 +24,16 @@ RUN x86_64-w64-mingw32-gcc -std=c11 -O2 -Wall -Wno-cast-function-type -static -s
# ---------------------------------------------------------------- the Vulkan layer that makes drawing a no-op
FROM ${UBUNTU} AS vklayer
+ARG APT_MIRROR=
+RUN if [ -n "$APT_MIRROR" ]; then sed -i "s#http://archive.ubuntu.com/ubuntu#$APT_MIRROR#g; s#http://security.ubuntu.com/ubuntu#$APT_MIRROR#g" /etc/apt/sources.list.d/ubuntu.sources; fi
RUN apt-get update -qq && apt-get install -y -qq --no-install-recommends gcc libc6-dev libvulkan-dev >/dev/null
COPY vklayer/vk_nulldraw.c /src/vk_nulldraw.c
RUN gcc -O2 -shared -fPIC -Wall -Werror -o /libVkLayer_mpf_nulldraw.so /src/vk_nulldraw.c -lpthread
# ---------------------------------------------------------------- runtime
FROM ${UBUNTU} AS runtime
+ARG APT_MIRROR=
+RUN if [ -n "$APT_MIRROR" ]; then sed -i "s#http://archive.ubuntu.com/ubuntu#$APT_MIRROR#g; s#http://security.ubuntu.com/ubuntu#$APT_MIRROR#g" /etc/apt/sources.list.d/ubuntu.sources; fi
ARG WINE_VERSION=11.0.0.0~noble-1
ENV DEBIAN_FRONTEND=noninteractive
RUN dpkg --add-architecture i386 \
diff --git a/server/compose.yaml b/server/compose.yaml
index 058f516d..c1f9a14d 100644
--- a/server/compose.yaml
+++ b/server/compose.yaml
@@ -2,7 +2,7 @@
services:
mpfever-server:
image: ${MPFEVER_IMAGE:-ghcr.io/dkdknight/mpfever-server:experimental}
- container_name: mpfever-server
+ container_name: ${CONTAINER_NAME:-mpfever-server}
restart: unless-stopped
init: true
stop_grace_period: 60s # the world is saved and the game closed on `docker compose stop`
diff --git a/server/scripts/entrypoint.sh b/server/scripts/entrypoint.sh
index 8bba7a56..84ab2144 100644
--- a/server/scripts/entrypoint.sh
+++ b/server/scripts/entrypoint.sh
@@ -15,7 +15,7 @@ MODE=${1:-run}; [ $# -gt 0 ] && shift
ensure_dirs() {
mkdir -p "$DATA" "$SRV" "$RUN" "$STEAM_DIR/steamapps/common" "$STEAM_DIR/config" 2>/dev/null \
- && mkdir -p -m 700 "$SECRETS" 2>/dev/null && [ -w "$DATA" ] \
+ && mkdir -p "$SECRETS" && chmod 700 "$SECRETS" && [ -w "$DATA" ] \
|| die "$DATA is not writable by uid $(id -u): fix the volume ownership (chown -R $(id -u):$(id -g) )" 10
}
@@ -159,7 +159,7 @@ cmd_run() {
on_term() {
STOPPING=1; log "stop requested: saving the world and closing the game"
touch "$STOPFILE"
- local i; for i in $(seq 1 "${STOP_TIMEOUT:-50}"); do kill -0 "$LAUNCHER" 2>/dev/null || break; sleep 1; done
+ local t=0; while kill -0 "$LAUNCHER" 2>/dev/null && [ "$t" -lt "${STOP_TIMEOUT:-50}" ]; do sleep 1; t=$((t + 1)); done
kill "$LAUNCHER" 2>/dev/null; wineserver -k 2>/dev/null
}
trap on_term TERM INT
diff --git a/server/scripts/lib.sh b/server/scripts/lib.sh
index 705c04db..4a66d24a 100644
--- a/server/scripts/lib.sh
+++ b/server/scripts/lib.sh
@@ -1,4 +1,4 @@
-# shellcheck shell=bash
+# shellcheck shell=bash disable=SC2034
# Shared definitions of the MPFever dedicated server scripts (sourced by entrypoint.sh).
export HOME=/data
From 962951c60c1dff88830f3ac467e8ee75cd1e0c29 Mon Sep 17 00:00:00 2001
From: ampynjord <82981605+ampynjord@users.noreply.github.com>
Date: Thu, 19 Nov 2026 13:45:34 +0100
Subject: [PATCH 03/47] server: create the profile folders at start (mod and
saves), longer clean-stop timeouts
---
server/compose.yaml | 2 +-
server/scripts/entrypoint.sh | 5 +++--
2 files changed, 4 insertions(+), 3 deletions(-)
diff --git a/server/compose.yaml b/server/compose.yaml
index c1f9a14d..0ab80c7b 100644
--- a/server/compose.yaml
+++ b/server/compose.yaml
@@ -5,7 +5,7 @@ services:
container_name: ${CONTAINER_NAME:-mpfever-server}
restart: unless-stopped
init: true
- stop_grace_period: 60s # the world is saved and the game closed on `docker compose stop`
+ stop_grace_period: 120s # the world is saved and the game closed on `docker compose stop`
ports:
- "${PORT:-28090}:${PORT:-28090}"
environment:
diff --git a/server/scripts/entrypoint.sh b/server/scripts/entrypoint.sh
index 84ab2144..01a1aca3 100644
--- a/server/scripts/entrypoint.sh
+++ b/server/scripts/entrypoint.sh
@@ -111,7 +111,8 @@ cmd_run() {
init_prefix; ensure_client; link_game
[ -f "$(save_dir)/$WORLD.sav" ] || die "savegame '$WORLD.sav' not found: run import-save (README.md, step 4)" 42
# the game's settings: a minimal profile (lowest graphics) the first time; MPFever activates its mod in it
- [ -f "$(local_dir)/settings.lua" ] || { mkdir -p "$(local_dir)"; cp "$OPT/config/settings.lua" "$(local_dir)/settings.lua"; }
+ mkdir -p "$(local_dir)/mods" "$(save_dir)" # where the game and MPFever look for the mod and the saves (a new profile has none of them)
+ [ -f "$(local_dir)/settings.lua" ] || cp "$OPT/config/settings.lua" "$(local_dir)/settings.lua"
# the launcher package of this image version, and the server settings from the environment (the file is rewritten at every start)
cp -a "$OPT/pkg/." "$SRV/"
@@ -159,7 +160,7 @@ cmd_run() {
on_term() {
STOPPING=1; log "stop requested: saving the world and closing the game"
touch "$STOPFILE"
- local t=0; while kill -0 "$LAUNCHER" 2>/dev/null && [ "$t" -lt "${STOP_TIMEOUT:-50}" ]; do sleep 1; t=$((t + 1)); done
+ local t=0; while kill -0 "$LAUNCHER" 2>/dev/null && [ "$t" -lt "${STOP_TIMEOUT:-90}" ]; do sleep 1; t=$((t + 1)); done
kill "$LAUNCHER" 2>/dev/null; wineserver -k 2>/dev/null
}
trap on_term TERM INT
From 2cbe1cb93c39c010a364a8077bf1e6231e6a21cc Mon Sep 17 00:00:00 2001
From: ampynjord <82981605+ampynjord@users.noreply.github.com>
Date: Thu, 19 Nov 2026 14:16:58 +0100
Subject: [PATCH 04/47] server: smaller image (minimal Mono), measure script,
validated results in the docs, CI runtime checks
---
.github/workflows/dedicated-server.yml | 2 ++
server/Dockerfile | 8 ++++---
server/README.md | 7 ++++---
server/compose.build.yaml | 1 +
server/docs/ARCHITECTURE.md | 29 ++++++++++++++++----------
server/scripts/measure.sh | 21 +++++++++++++++++++
6 files changed, 51 insertions(+), 17 deletions(-)
create mode 100644 server/scripts/measure.sh
diff --git a/.github/workflows/dedicated-server.yml b/.github/workflows/dedicated-server.yml
index 7bcc2c03..cdd65a7c 100644
--- a/.github/workflows/dedicated-server.yml
+++ b/.github/workflows/dedicated-server.yml
@@ -103,6 +103,8 @@ jobs:
# licence texts and Dock are present, a healthcheck is defined
docker run --rm --entrypoint sh "$img" -c 'test -f /opt/mpfever/dockhost.exe && test -f /opt/mpfever/licenses/madeira-dock/COPYING && test -f /opt/mpfever/pkg/MPFever.exe && test -f /opt/mpfever/pkg/winhttp.dll'
docker inspect --format '{{.Config.Healthcheck.Test}}' "$img" | grep -q healthcheck.sh
+ # pinned runtimes
+ docker run --rm --entrypoint sh "$img" -c 'wine --version | grep -q "wine-11.0" && mono --version | head -1 && python3 -c "import qrcode"'
# an empty volume gives explicit messages, not a crash
docker volume create ci-data >/dev/null; docker volume create ci-game >/dev/null
set +e
diff --git a/server/Dockerfile b/server/Dockerfile
index ec37bac8..f977544f 100644
--- a/server/Dockerfile
+++ b/server/Dockerfile
@@ -40,13 +40,15 @@ RUN dpkg --add-architecture i386 \
&& apt-get update -qq \
&& apt-get install -y -qq --no-install-recommends ca-certificates curl wget gnupg2 procps xvfb xauth \
libvulkan1 mesa-vulkan-drivers libgl1 libasound2t64 libgnutls30t64 libfreetype6 fonts-dejavu-core \
- python3-minimal python3-qrcode mono-complete libgdiplus \
+ python3-minimal python3-qrcode mono-runtime libmono-system-windows-forms4.0-cil libmono-system-drawing4.0-cil \
+ libmono-system-core4.0-cil libmono-system-io-compression4.0-cil libmono-system-io-compression-filesystem4.0-cil \
+ libmono-security4.0-cil ca-certificates-mono libgdiplus \
&& mkdir -pm755 /etc/apt/keyrings \
&& wget -qO /etc/apt/keyrings/winehq-archive.key https://dl.winehq.org/wine-builds/winehq.key \
&& wget -qNP /etc/apt/sources.list.d/ https://dl.winehq.org/wine-builds/ubuntu/dists/noble/winehq-noble.sources \
&& apt-get update -qq \
- && apt-get install -y -qq --install-recommends \
- winehq-stable=${WINE_VERSION} wine-stable=${WINE_VERSION} wine-stable-amd64=${WINE_VERSION} wine-stable-i386=${WINE_VERSION} \
+ && apt-get install -y -qq --no-install-recommends wine-stable=${WINE_VERSION} wine-stable-amd64=${WINE_VERSION} wine-stable-i386=${WINE_VERSION} \
+ && for b in wine wineserver wineboot; do ln -s /opt/wine-stable/bin/$b /usr/local/bin/$b; done \
&& rm -rf /var/lib/apt/lists/* \
&& useradd -m -d /data -u 1001 -s /bin/bash tf3 \
&& mkdir -p /data /game /opt/mpfever && chown tf3:tf3 /data /game
diff --git a/server/README.md b/server/README.md
index 9970e50d..373a9398 100644
--- a/server/README.md
+++ b/server/README.md
@@ -4,8 +4,8 @@ A server that runs the **real Transport Fever 3 simulation** in one Docker conta
[Madeira Dock](https://github.com/willfaust/madeira-dock) and Valve's own Steam client library. No GPU, no screen, no Steam desktop.
Players join it with the usual MPFever client (same version) from Windows.
-> **Status: experimental.** It works for short sessions on a small world with a real Windows client (see "Validation" in
-> [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md)). It needs **your own** Transport Fever 3 licence: the image contains no game file and no Valve file.
+> **Status: experimental.** Validated end to end on the built image for short sessions on a small world with a real Windows client (see "Validation" in
+> [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md): long runs, several clients and large worlds are not validated). It needs **your own** Transport Fever 3 licence: the image contains no game file and no Valve file.
## What you need
@@ -43,7 +43,8 @@ Edit `.env` (at least `WORLD`, the savegame's name without `.sav`). Then, once:
```
5. **Start**: `docker compose up -d`. It restarts by itself after a reboot or a crash. `docker compose logs -f` shows the server's log.
-Check at any time what is missing: `docker compose run --rm mpfever-server status`.
+Check at any time what is missing: `docker compose run --rm mpfever-server status`. Memory and CPU: `docker compose exec mpfever-server /opt/mpfever/scripts/measure.sh`.
+The very first start takes a few minutes longer (Wine prefix, Valve client download) and the game restarts once by itself.
Players connect to `:28090` (forward the TCP port on your router for the Internet). Stop with `docker compose stop` (the world is saved first).
## Configuration
diff --git a/server/compose.build.yaml b/server/compose.build.yaml
index 500da85f..612f6655 100644
--- a/server/compose.build.yaml
+++ b/server/compose.build.yaml
@@ -6,3 +6,4 @@ services:
context: .
args:
VERSION: ${VERSION:-local}
+ APT_MIRROR: ${APT_MIRROR:-} # e.g. http://fr.archive.ubuntu.com/ubuntu when archive.ubuntu.com is unreachable
diff --git a/server/docs/ARCHITECTURE.md b/server/docs/ARCHITECTURE.md
index 9cf5096d..6f3b19b1 100644
--- a/server/docs/ARCHITECTURE.md
+++ b/server/docs/ARCHITECTURE.md
@@ -21,23 +21,30 @@
- **Start** (`scripts/entrypoint.sh run`): checks (disk, sparse support, RAM, game, session, save), first-start prefix creation (marker file, so a restart reinstalls nothing), pinned Valve client,
launcher with restart-on-exit (5 quick failures in a minute stop the container with a message), `SIGTERM` writes the stop file: the world is saved, the game closed, then the container exits.
-## Measured (small world, MPFever 0.9.0 package, no GPU, one real Windows client)
+## Measured (small world, MPFever 0.9.2 package, no GPU, built image, fresh volumes)
| | |
|---|---|
-| Game RAM | 10.1 to 10.3 GB (11.0 to 11.2 GB before the GPU-memory trim); heap of about 9 GB is the game's own |
-| Steam side (Dock + Valve service) | about 280 MB (Steam desktop under Wine: 2.7 GB) |
-| CPU | about 0.7 core at x0.98 game speed |
-| Disk | about 0.9 GB game + about 3 GB prefix and client |
-| Sync with a real Windows client | `IDENTICAL on 2 games`, 0 desynchronisations, runs of 3 to 13 minutes |
+| Container (cgroup, game running, no client) | about 10.6 to 11.8 GB: anonymous 9.5 GB, page cache 1 to 2 GB (reclaimable), shared 0.7 GB |
+| Game process | RSS 10.1 GB, PSS 10.0 GB (the heap of about 9 GB is the game's own; the Vulkan layer's trim returns about 0.7 GB of mapped GPU memory) |
+| Dock (`dockhost.exe`) | RSS 256 MB, PSS 193 MB; its CPU is 0.02 core |
+| Other processes | launcher (Mono) 107 MB, Wine desktop 87 MB, Xvfb 23 MB, session feeder 20 MB, wineserver 15 MB |
+| CPU | game 0.6 core at x0.98 game speed |
+| Disk | game 1.3 GB on disk (66 GB apparent), prefix and Valve client about 3 GB |
+| Image | 3.5 GB (Wine 11 with its i386 part 1.5 GB, Mesa/LLVM about 0.3 GB, Mono runtime subset); was 4.3 GB with `mono-complete` |
+| Start | image to "game ready" about 2.5 minutes with a warm cache, plus about 1.5 minutes the very first time (prefix creation, Valve client download, one extra game start) |
+| Sync with a real Windows client (0.9.2) | join, resynchronisation 140 s, then `IDENTICAL on 2 games`, 0 desynchronisations, 6 minutes observed |
+
+`scripts/measure.sh` prints these figures from inside the container (`docker compose exec mpfever-server /opt/mpfever/scripts/measure.sh`).
+Tried and dropped: `MADV_REMOVE` on the mapped GPU memory (no gain), a Wine without its i386 package (the launcher binaries ship in the package that depends on it), fewer or no Lavapipe threads (CPU worse).
## Validation status (honest)
-Validated on the maintainer's machine with the earlier hand-prepared volumes: Dock sign-in with the cached Steam session, licence check, launch, restart after a game crash, cold start of the container, synchronisation
-with a real Windows 0.9.0 client for short runs (join, resynchronisation, identical checks).
-**Not validated yet**: first start on an empty volume with `install-game`, `login` (QR) and the token transfer to Dock; `import-save`; graceful stop through the stop file; runs of 30 minutes or more;
-several clients (a Steam account plays one game at a time: a second account is needed); large worlds; forced CPU/memory minimums; a full image rebuild (the image was last assembled on top of an older Wine layer);
-the GPU variant; the published image (nothing is published until the checklist of the pull request is done).
+Run end to end on the built image, on volumes created empty: `install-game` from a real Steam library (2 min), Steam QR `login` (real account, token kept 0600, valid until the printed date),
+`import-save`, first start (Wine prefix, Valve client download with hash check), **token hand-over to Dock and Steamworks initialisation without any Steam desktop**, launch of Transport Fever 3 under Wine, MPFever server mode,
+world load, a real Windows client joining with resynchronisation and identical checks, `docker compose stop` (9 s, exit 0, world saved at stop), restart restoring the saved world time, healthcheck healthy, read-only root and no capabilities.
+**Not validated yet**: runs of 30 minutes or more; several clients (a Steam account plays one game at a time: a second account is needed); large worlds; forced CPU/memory minimums (limits are set, behaviour under pressure not tested);
+the GPU variant; the published image (nothing is published); stopping while a client is connected and has vanished (the stop waits for it up to about 45 s, the timeouts allow it); the CI image job (see the pull request).
## Decisions not to redo
diff --git a/server/scripts/measure.sh b/server/scripts/measure.sh
new file mode 100644
index 00000000..92a5c584
--- /dev/null
+++ b/server/scripts/measure.sh
@@ -0,0 +1,21 @@
+#!/bin/bash
+# Memory and CPU of the running server, from inside the container: docker compose exec mpfever-server /opt/mpfever/scripts/measure.sh
+# Distinguishes the container's cgroup (anonymous memory, page cache, shared), each process (RSS and PSS = its fair share of shared pages) and CPU over 30 s.
+cg=/sys/fs/cgroup
+echo "== container (cgroup)"
+if [ -f $cg/memory.current ]; then
+ awk -v cur="$(cat $cg/memory.current)" '$1=="anon"{a=$2} $1=="file"{f=$2} $1=="shmem"{s=$2} END{printf "total %.0f MB anonymous %.0f MB page cache %.0f MB shared(shmem) %.0f MB\n", cur/1048576, a/1048576, f/1048576, s/1048576}' $cg/memory.stat
+fi
+echo "== processes (RSS / PSS MB)"
+ps -eo pid=,comm=,args= | while read -r pid comm args; do
+ [ -r /proc/$pid/smaps_rollup ] || continue
+ awk -v p="$pid" -v n="${args:0:46}" '$1=="Rss:"{r=$2} $1=="Pss:"{s=$2} END{printf "%8.0f %8.0f %s\n", r/1024, s/1024, n}' /proc/$pid/smaps_rollup
+done | sort -rn | head -8
+echo "== CPU over 30 s (cores)"
+g=$(pgrep -f 'TransportFever3.exe --script' | tail -1); d=$(pgrep -f 'dockhost.exe' | head -1)
+for p in $g $d; do
+ c0=$(awk '{print $14+$15}' /proc/$p/stat); sleep 30; c1=$(awk '{print $14+$15}' /proc/$p/stat)
+ printf "pid %s %-28s %.2f\n" "$p" "$(tr '\0' ' ' < /proc/$p/cmdline | cut -c1-28)" "$(awk -v a="$c0" -v b="$c1" 'BEGIN{printf "%.2f", (b-a)/100/30}')"
+done
+f=$(ls -t /data/srv/logs/launcher-*.log 2>/dev/null | head -1)
+[ -n "$f" ] && { echo "== sync"; grep "Sync check" "$f" | tail -1 | cut -c1-90; echo "out of sync so far: $(grep -c 'OUT OF SYNC' "$f")"; }
From 46fe24fe4ab992b0391ba3ff30897fc57d5ceb03 Mon Sep 17 00:00:00 2001
From: ampynjord <82981605+ampynjord@users.noreply.github.com>
Date: Thu, 19 Nov 2026 14:20:53 +0100
Subject: [PATCH 05/47] server: fix shellcheck warning in measure.sh
---
server/scripts/measure.sh | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/server/scripts/measure.sh b/server/scripts/measure.sh
index 92a5c584..0a8fb49a 100644
--- a/server/scripts/measure.sh
+++ b/server/scripts/measure.sh
@@ -7,7 +7,7 @@ if [ -f $cg/memory.current ]; then
awk -v cur="$(cat $cg/memory.current)" '$1=="anon"{a=$2} $1=="file"{f=$2} $1=="shmem"{s=$2} END{printf "total %.0f MB anonymous %.0f MB page cache %.0f MB shared(shmem) %.0f MB\n", cur/1048576, a/1048576, f/1048576, s/1048576}' $cg/memory.stat
fi
echo "== processes (RSS / PSS MB)"
-ps -eo pid=,comm=,args= | while read -r pid comm args; do
+ps -eo pid=,args= | while read -r pid args; do
[ -r /proc/$pid/smaps_rollup ] || continue
awk -v p="$pid" -v n="${args:0:46}" '$1=="Rss:"{r=$2} $1=="Pss:"{s=$2} END{printf "%8.0f %8.0f %s\n", r/1024, s/1024, n}' /proc/$pid/smaps_rollup
done | sort -rn | head -8
From b3ebf7a68b2327f920f99c3d172de11e362b61a9 Mon Sep 17 00:00:00 2001
From: ampynjord <82981605+ampynjord@users.noreply.github.com>
Date: Thu, 19 Nov 2026 15:18:18 +0100
Subject: [PATCH 06/47] CI: build the package from the latest official release
plus the launcher changes; publish only on a version tag or a manual run
---
.github/workflows/dedicated-server.yml | 80 +++++++++++++++++++++-----
server/README.md | 10 +++-
server/docs/ARCHITECTURE.md | 2 +-
3 files changed, 75 insertions(+), 17 deletions(-)
diff --git a/.github/workflows/dedicated-server.yml b/.github/workflows/dedicated-server.yml
index cdd65a7c..f65ca597 100644
--- a/.github/workflows/dedicated-server.yml
+++ b/.github/workflows/dedicated-server.yml
@@ -1,6 +1,12 @@
-# The Linux dedicated server (server/): static checks, the package built from this repository, the Docker image built and smoke-tested.
-# NOTHING IS PUBLISHED by a push or a pull request. The image is pushed to GHCR only by a manual run (workflow_dispatch) with
-# "publish" ticked, on the upstream repository, after the checks and the smoke tests below pass.
+# The Linux dedicated server (server/): static checks, the package, the Docker image built and smoke-tested.
+#
+# The image always carries the LATEST OFFICIAL MPFever release: the package is built from that release's tag (build.bat) with the launcher
+# changes of this branch applied on top (they disappear from the patch once a release contains them). So players on the official release can join.
+#
+# Publication to GHCR (ghcr.io//mpfever-server) happens ONLY on purpose, after every job above has passed:
+# - pushing a tag dedicated-server-v- (for example dedicated-server-v0.9.1-1): tags "-server." and "experimental"
+# - or a manual run (workflow_dispatch, workflow file on the default branch) with "publish" ticked.
+# A push or a pull request never publishes.
name: Dedicated server
on:
@@ -8,15 +14,20 @@ on:
paths: ["server/**", "launcher/**", ".github/workflows/dedicated-server.yml"]
push:
branches: [main, "feature/dedicated-server"]
+ tags: ["dedicated-server-v*"]
paths: ["server/**", "launcher/**", ".github/workflows/dedicated-server.yml"]
workflow_dispatch:
inputs:
publish:
- description: "Push the image to GHCR (only the upstream repository, only after the tests pass)"
+ description: "Push the image to GHCR (only after the tests pass)"
type: boolean
default: false
- version:
- description: "Version tag to publish besides 'experimental' (for example 0.9.1-server.1); empty: only 'experimental'"
+ version_tag:
+ description: "Image tag besides 'experimental' (for example 0.9.1-server.1); empty: only 'experimental'"
+ type: string
+ default: ""
+ mpfever_ref:
+ description: "MPFever release tag to build the package from; empty: the latest official release"
type: string
default: ""
@@ -27,6 +38,9 @@ concurrency:
permissions:
contents: read
+env:
+ UPSTREAM: https://github.com/dkdknight/MPFever.git
+
jobs:
static:
runs-on: ubuntu-24.04
@@ -39,24 +53,49 @@ jobs:
run: bash server/tests/check.sh
package:
- # The same build as ci.yml (native module, launcher with warnings as errors, tests, archives); the server archive is the input of the image.
+ # The same build as ci.yml (native module, launcher with warnings as errors, tests, archives), of the latest official release + this branch's launcher changes.
runs-on: windows-2022
timeout-minutes: 40
+ outputs:
+ mpfever_version: ${{ steps.ref.outputs.version }}
steps:
- uses: actions/checkout@v4
+ with:
+ fetch-depth: 0
- uses: actions/setup-python@v5
with:
python-version: "3.12"
- run: python -m pip install lupa==2.8
+ - name: Release to build, and the launcher changes of this branch
+ id: ref
+ shell: bash
+ env:
+ GH_TOKEN: ${{ github.token }}
+ WANTED: ${{ inputs.mpfever_ref }}
+ run: |
+ set -eu
+ tag="${WANTED:-}"
+ [ -n "$tag" ] || tag=$(gh release view --repo dkdknight/MPFever --json tagName --jq .tagName)
+ echo "official release: $tag"
+ git remote add upstream "$UPSTREAM" 2>/dev/null || true
+ git fetch -q upstream main "refs/tags/$tag:refs/tags/upstream-$tag"
+ git diff "upstream/main...HEAD" -- launcher > "$RUNNER_TEMP/launcher.patch"
+ git worktree add -q --detach release-src "upstream-$tag"
+ cd release-src
+ if [ ! -s "$RUNNER_TEMP/launcher.patch" ]; then echo "no launcher changes to apply"
+ elif git apply --reverse --check --ignore-whitespace "$RUNNER_TEMP/launcher.patch" 2>/dev/null; then echo "the release already contains the launcher changes"
+ else git apply --ignore-whitespace "$RUNNER_TEMP/launcher.patch" && echo "launcher changes applied"; fi
+ echo "version=$tag" >> "$GITHUB_OUTPUT"
- name: Build, test, pack
shell: pwsh
+ working-directory: release-src
run: |
cmd /c build.bat 2>&1 | Tee-Object -FilePath build.log
if ($LASTEXITCODE -ne 0) { exit 1 }
- uses: actions/upload-artifact@v4
with:
name: server-package
- path: release/*-server.zip
+ path: release-src/release/*-server.zip
retention-days: 14
if-no-files-found: error
@@ -78,7 +117,7 @@ jobs:
run: |
ls -l
cp ./*-server.zip MPFever-server.zip
- echo "PKG_VERSION=$(ls ./*-server.zip | head -1 | sed -E 's#.*MPFever-(.*)-server\.zip#\1#')" >> "$GITHUB_ENV"
+ echo "PKG_VERSION=${{ needs.package.outputs.mpfever_version }}" >> "$GITHUB_ENV"
- uses: docker/setup-buildx-action@v3
- name: Build the image (not pushed)
uses: docker/build-push-action@v6
@@ -114,17 +153,30 @@ jobs:
test $rc -eq 40 && echo "$out" | grep -q "run login"
# the Dock build is the pinned one, the Vulkan layer loads
docker run --rm --entrypoint sh "$img" -c 'ls -l /opt/mpfever/libVkLayer_mpf_nulldraw.so /etc/vulkan/implicit_layer.d/'
+ - name: Decide the tags to publish
+ id: tags
+ run: |
+ set -eu
+ owner=$(echo "${{ github.repository_owner }}" | tr 'A-Z' 'a-z')
+ pub=false; vtag=""
+ if [ "${{ github.event_name }}" = workflow_dispatch ] && [ "${{ inputs.publish }}" = true ]; then pub=true; vtag="${{ inputs.version_tag }}"; fi
+ if [ "${{ github.ref_type }}" = tag ]; then
+ pub=true; t="${{ github.ref_name }}"; t="${t#dedicated-server-v}" # 0.9.1-1
+ vtag="${t%-*}-server.${t##*-}" # 0.9.1-server.1
+ fi
+ echo "publish=$pub" >> "$GITHUB_OUTPUT"; echo "repo=ghcr.io/$owner/mpfever-server" >> "$GITHUB_OUTPUT"; echo "vtag=$vtag" >> "$GITHUB_OUTPUT"
- name: Log in to GHCR
- if: github.event_name == 'workflow_dispatch' && inputs.publish && github.repository == 'dkdknight/MPFever'
+ if: steps.tags.outputs.publish == 'true'
uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- - name: Publish (manual run only)
- if: github.event_name == 'workflow_dispatch' && inputs.publish && github.repository == 'dkdknight/MPFever'
+ - name: Publish (tag push or manual run only)
+ if: steps.tags.outputs.publish == 'true'
run: |
set -eu
- repo=ghcr.io/dkdknight/mpfever-server
+ repo=${{ steps.tags.outputs.repo }}; vtag=${{ steps.tags.outputs.vtag }}
docker tag mpfever-server:ci "$repo:experimental"; docker push "$repo:experimental"
- if [ -n "${{ inputs.version }}" ]; then docker tag mpfever-server:ci "$repo:${{ inputs.version }}"; docker push "$repo:${{ inputs.version }}"; fi
+ if [ -n "$vtag" ]; then docker tag mpfever-server:ci "$repo:$vtag"; docker push "$repo:$vtag"; fi
+ echo "published $repo:experimental ${vtag:+and $repo:$vtag}" >> "$GITHUB_STEP_SUMMARY"
diff --git a/server/README.md b/server/README.md
index 373a9398..e05af3ff 100644
--- a/server/README.md
+++ b/server/README.md
@@ -59,10 +59,16 @@ Images are tagged by version (`ghcr.io/dkdknight/mpfever-server:`) and
`MPFEVER_IMAGE=ghcr.io/dkdknight/mpfever-server:` in `.env` and `docker compose up -d`; the data volume is untouched. Players need the MPFever client of the server's version.
See [docs/OPERATIONS.md](docs/OPERATIONS.md) for backups, Valve updates, security and troubleshooting.
+## Versions and tags
+
+The image always carries the **latest official MPFever release** (the package is built from that release's tag, with the launcher changes of this branch applied until a release contains them), so players on the official client can join.
+Tags: `-server.` (for example `0.9.1-server.1`, `n` counts rebuilds of the same release) and `experimental` (the latest build). Pin a version tag in production.
+Publishing is deliberate: pushing the git tag `dedicated-server-v-` (or a manual workflow run) publishes after the checks pass; a push or a pull request never does.
+
## Build it yourself
-`build.bat` at the repository root builds the launcher and package (`release/MPFever--server.zip`); copy it to `server/dist/MPFever-server.zip` and run
-`docker compose -f compose.yaml -f compose.build.yaml build`. The same steps run in CI (`.github/workflows/dedicated-server.yml`).
+`.github/workflows/dedicated-server.yml` does it all (static checks, package of the latest release with the launcher changes, image, smoke tests). To build locally, put a package built by `build.bat`
+(`release/MPFever--server.zip`) in `server/dist/MPFever-server.zip` and run `docker compose -f compose.yaml -f compose.build.yaml build`.
## Licence
diff --git a/server/docs/ARCHITECTURE.md b/server/docs/ARCHITECTURE.md
index 6f3b19b1..35342c10 100644
--- a/server/docs/ARCHITECTURE.md
+++ b/server/docs/ARCHITECTURE.md
@@ -5,7 +5,7 @@
| Part | What | Why |
|---|---|---|
| Game | `TransportFever3.exe` (Windows) under **Wine 11** (pinned package) on Ubuntu 24.04 | A native Linux build of the game drifts from Windows clients (different C++ library, `std::` distributions inlined in the game): same executable = same simulation. Not Proton: no DXVK, rendering is a no-op. |
-| Launcher | `MPFever.exe --server --server-start headless` under **Mono**, with a Linux/Wine mode (`launcher/Core.cs`: `GameInstall.WineMode`, `MPFEVER_WINE=1`; `Server.cs`: `MPFEVER_STOPFILE`) | Provides all the host logic and the same `winhttp.dll` native module and mod as the players'. Built from this repository by `build.bat`. |
+| Launcher | `MPFever.exe --server --server-start headless` under **Mono**, with a Linux/Wine mode (`launcher/Core.cs`: `GameInstall.WineMode`, `MPFEVER_WINE=1`; `Server.cs`: `MPFEVER_STOPFILE`) | Provides all the host logic and the same `winhttp.dll` native module and mod as the players'. Built by `build.bat` from the latest official release tag with this branch's launcher changes applied (CI). |
| Steam | **Madeira Dock** (`dockhost.exe`, built from source at a pinned commit) driving **Valve's own `steamclient64.dll`** | The game requires a running Valve client. Dock signs in with the account owner's refresh token, asks Valve's client for the licence and has it start the game: no `steam.exe`, no `steamwebhelper` (about 280 MB instead of 2.7 GB). No emulation of Steamworks, no DRM bypass: every decision is Valve's. |
| Rendering | Lavapipe (software Vulkan) + the layer `vklayer/` (`MPF_VKNULL=1`, `MPF_VKNULL_MODE=all`, `MPF_VKNULL_TRIM=1`) and `MPFEVER_HEADLESS_NORENDER=1;MPFEVER_HEADLESS_FPS=10` | Draws, copies and render passes become no-ops; mapped GPU memory nobody reads is given back. A real GPU is used if the layer is off (`compose.gpu.yaml`, not validated). |
| Disk | "Lite" game install (`scripts/mklite.py`) | The engine reads archives at fixed offsets, so archives keep their layout: textures, audio and blobs become file holes (sparse), images stay valid but empty. 66 GB become about 1 GB on disk. Generated from the host's own copy; never distributed. |
From 9402953a9f363006b5c2692fbe7ec817462f33b1 Mon Sep 17 00:00:00 2001
From: ampynjord <82981605+ampynjord@users.noreply.github.com>
Date: Thu, 19 Nov 2026 15:22:47 +0100
Subject: [PATCH 07/47] image: source label points to the repository that
builds it
---
.github/workflows/dedicated-server.yml | 1 +
server/Dockerfile | 3 ++-
2 files changed, 3 insertions(+), 1 deletion(-)
diff --git a/.github/workflows/dedicated-server.yml b/.github/workflows/dedicated-server.yml
index f65ca597..638d7eba 100644
--- a/.github/workflows/dedicated-server.yml
+++ b/.github/workflows/dedicated-server.yml
@@ -128,6 +128,7 @@ jobs:
build-args: |
VERSION=${{ env.PKG_VERSION }}
VCS_REF=${{ github.sha }}
+ SOURCE_REPO=${{ github.server_url }}/${{ github.repository }}
cache-from: type=gha
cache-to: type=gha,mode=max
- name: Smoke tests
diff --git a/server/Dockerfile b/server/Dockerfile
index f977544f..b171fa9b 100644
--- a/server/Dockerfile
+++ b/server/Dockerfile
@@ -68,10 +68,11 @@ COPY config/ /opt/mpfever/config/
RUN sed -i 's/\r$//' /opt/mpfever/scripts/*.sh && chmod 755 /opt/mpfever/scripts/*.sh
ARG VCS_REF=unknown
+ARG SOURCE_REPO=https://github.com/dkdknight/MPFever
ARG VERSION=experimental
LABEL org.opencontainers.image.title="MPFever dedicated server (experimental)" \
org.opencontainers.image.description="Transport Fever 3 under Wine with Madeira Dock; contains no game or Valve files" \
- org.opencontainers.image.source="https://github.com/dkdknight/MPFever" \
+ org.opencontainers.image.source="${SOURCE_REPO}" \
org.opencontainers.image.licenses="GPL-3.0-or-later" \
org.opencontainers.image.revision="${VCS_REF}" org.opencontainers.image.version="${VERSION}"
From 79d16d44b931d85953a591f20e78521867911d86 Mon Sep 17 00:00:00 2001
From: ampynjord <82981605+ampynjord@users.noreply.github.com>
Date: Thu, 19 Nov 2026 15:25:38 +0100
Subject: [PATCH 08/47] Naming like the rest of the project: image
mpfever-server-docker tagged with the MPFever version, MPFever-server-package
artifact, compose project name
---
.github/workflows/dedicated-server.yml | 17 ++++++++---------
server/.env.example | 2 +-
server/README.md | 8 ++++----
server/compose.yaml | 4 +++-
server/docs/OPERATIONS.md | 2 +-
5 files changed, 17 insertions(+), 16 deletions(-)
diff --git a/.github/workflows/dedicated-server.yml b/.github/workflows/dedicated-server.yml
index 638d7eba..763061db 100644
--- a/.github/workflows/dedicated-server.yml
+++ b/.github/workflows/dedicated-server.yml
@@ -3,8 +3,8 @@
# The image always carries the LATEST OFFICIAL MPFever release: the package is built from that release's tag (build.bat) with the launcher
# changes of this branch applied on top (they disappear from the patch once a release contains them). So players on the official release can join.
#
-# Publication to GHCR (ghcr.io//mpfever-server) happens ONLY on purpose, after every job above has passed:
-# - pushing a tag dedicated-server-v- (for example dedicated-server-v0.9.1-1): tags "-server." and "experimental"
+# Publication to GHCR (ghcr.io//mpfever-server-docker, named like the relay's mpfever-relay-docker) happens ONLY on purpose, after every job above has passed:
+# - pushing a tag dedicated-server-v[-] (for example dedicated-server-v0.9.1): image tags "[-]" and "experimental"
# - or a manual run (workflow_dispatch, workflow file on the default branch) with "publish" ticked.
# A push or a pull request never publishes.
name: Dedicated server
@@ -23,7 +23,7 @@ on:
type: boolean
default: false
version_tag:
- description: "Image tag besides 'experimental' (for example 0.9.1-server.1); empty: only 'experimental'"
+ description: "Image tag besides 'experimental' (the MPFever version, for example 0.9.1); empty: only 'experimental'"
type: string
default: ""
mpfever_ref:
@@ -94,8 +94,8 @@ jobs:
if ($LASTEXITCODE -ne 0) { exit 1 }
- uses: actions/upload-artifact@v4
with:
- name: server-package
- path: release-src/release/*-server.zip
+ name: MPFever-server-package-${{ github.sha }}
+ path: release-src/release/MPFever-*-server.zip
retention-days: 14
if-no-files-found: error
@@ -110,7 +110,7 @@ jobs:
- uses: actions/checkout@v4
- uses: actions/download-artifact@v4
with:
- name: server-package
+ name: MPFever-server-package-${{ github.sha }}
path: server/dist
- name: Package for the image
working-directory: server/dist
@@ -162,10 +162,9 @@ jobs:
pub=false; vtag=""
if [ "${{ github.event_name }}" = workflow_dispatch ] && [ "${{ inputs.publish }}" = true ]; then pub=true; vtag="${{ inputs.version_tag }}"; fi
if [ "${{ github.ref_type }}" = tag ]; then
- pub=true; t="${{ github.ref_name }}"; t="${t#dedicated-server-v}" # 0.9.1-1
- vtag="${t%-*}-server.${t##*-}" # 0.9.1-server.1
+ pub=true; vtag="${{ github.ref_name }}"; vtag="${vtag#dedicated-server-v}" # 0.9.1 or 0.9.1-2
fi
- echo "publish=$pub" >> "$GITHUB_OUTPUT"; echo "repo=ghcr.io/$owner/mpfever-server" >> "$GITHUB_OUTPUT"; echo "vtag=$vtag" >> "$GITHUB_OUTPUT"
+ echo "publish=$pub" >> "$GITHUB_OUTPUT"; echo "repo=ghcr.io/$owner/mpfever-server-docker" >> "$GITHUB_OUTPUT"; echo "vtag=$vtag" >> "$GITHUB_OUTPUT"
- name: Log in to GHCR
if: steps.tags.outputs.publish == 'true'
uses: docker/login-action@v3
diff --git a/server/.env.example b/server/.env.example
index 66b2eb00..f794c9ed 100644
--- a/server/.env.example
+++ b/server/.env.example
@@ -18,5 +18,5 @@ MOTD=
# Resource limits. Measured for a small world: about 11 GB of RAM and 0.7 core.
MEM_LIMIT=14g
CPUS=2
-# Another image or version (rollback): MPFEVER_IMAGE=ghcr.io/dkdknight/mpfever-server:
+# Another image or version (rollback): MPFEVER_IMAGE=ghcr.io/dkdknight/mpfever-server-docker:
#MPFEVER_IMAGE=
diff --git a/server/README.md b/server/README.md
index e05af3ff..b548f8d9 100644
--- a/server/README.md
+++ b/server/README.md
@@ -55,15 +55,15 @@ with `install-game` at any time. Server console commands (`save`, `kick`, ...) a
## Update and roll back
-Images are tagged by version (`ghcr.io/dkdknight/mpfever-server:`) and `experimental`. Update: `docker compose pull && docker compose up -d`. Roll back: set
-`MPFEVER_IMAGE=ghcr.io/dkdknight/mpfever-server:` in `.env` and `docker compose up -d`; the data volume is untouched. Players need the MPFever client of the server's version.
+Images are tagged by version (`ghcr.io/dkdknight/mpfever-server-docker:`) and `experimental`. Update: `docker compose pull && docker compose up -d`. Roll back: set
+`MPFEVER_IMAGE=ghcr.io/dkdknight/mpfever-server-docker:` in `.env` and `docker compose up -d`; the data volume is untouched. Players need the MPFever client of the server's version.
See [docs/OPERATIONS.md](docs/OPERATIONS.md) for backups, Valve updates, security and troubleshooting.
## Versions and tags
The image always carries the **latest official MPFever release** (the package is built from that release's tag, with the launcher changes of this branch applied until a release contains them), so players on the official client can join.
-Tags: `-server.` (for example `0.9.1-server.1`, `n` counts rebuilds of the same release) and `experimental` (the latest build). Pin a version tag in production.
-Publishing is deliberate: pushing the git tag `dedicated-server-v-` (or a manual workflow run) publishes after the checks pass; a push or a pull request never does.
+The image is named like the relay's (`mpfever-relay-docker`): `ghcr.io//mpfever-server-docker`. Tags: the MPFever version (for example `0.9.1`; `0.9.1-2` for a rebuild of the same release) and `experimental` (the latest build). Pin a version tag in production.
+Publishing is deliberate: pushing the git tag `dedicated-server-v[-]` (or a manual workflow run) publishes after the checks pass; a push or a pull request never does.
## Build it yourself
diff --git a/server/compose.yaml b/server/compose.yaml
index 0ab80c7b..cd27c373 100644
--- a/server/compose.yaml
+++ b/server/compose.yaml
@@ -1,7 +1,9 @@
# MPFever dedicated server (experimental). Setup and first start: README.md. docker compose up -d
+name: mpfever-server
+
services:
mpfever-server:
- image: ${MPFEVER_IMAGE:-ghcr.io/dkdknight/mpfever-server:experimental}
+ image: ${MPFEVER_IMAGE:-ghcr.io/dkdknight/mpfever-server-docker:experimental}
container_name: ${CONTAINER_NAME:-mpfever-server}
restart: unless-stopped
init: true
diff --git a/server/docs/OPERATIONS.md b/server/docs/OPERATIONS.md
index 7d67f2ca..fc1ee95b 100644
--- a/server/docs/OPERATIONS.md
+++ b/server/docs/OPERATIONS.md
@@ -20,7 +20,7 @@ Dock never starts `steam.exe`, so the pinned client is **never updated by Steam
## Update, roll back, back up
-- Update: `docker compose pull && docker compose up -d`. Roll back: `MPFEVER_IMAGE=ghcr.io/dkdknight/mpfever-server:` in `.env`. The launcher package is replaced at each start; `.env` and the volumes stay.
+- Update: `docker compose pull && docker compose up -d`. Roll back: `MPFEVER_IMAGE=ghcr.io/dkdknight/mpfever-server-docker:` in `.env`. The launcher package is replaced at each start; `.env` and the volumes stay.
- Players must run the MPFever client of the server's version (the launcher says "other version than the host's" otherwise).
- Back up the `mpfever-data` volume (saves, `srv/backups`, session). Never copy `secrets/steam.json` anywhere else; revoke it from your Steam account (Settings, Security, devices) if it leaks.
- Resetting: remove the volumes (`docker compose down -v`) to start from nothing; the game volume is rebuilt by `install-game`.
From 665272af78d23622aae62b4f9d028433008d0170 Mon Sep 17 00:00:00 2001
From: ampynjord <82981605+ampynjord@users.noreply.github.com>
Date: Thu, 19 Nov 2026 15:37:05 +0100
Subject: [PATCH 09/47] Image named mpfever-server (conventional, no -docker
suffix)
---
.github/workflows/dedicated-server.yml | 4 ++--
server/.env.example | 2 +-
server/README.md | 6 +++---
server/compose.yaml | 2 +-
server/docs/OPERATIONS.md | 2 +-
5 files changed, 8 insertions(+), 8 deletions(-)
diff --git a/.github/workflows/dedicated-server.yml b/.github/workflows/dedicated-server.yml
index 763061db..a7896988 100644
--- a/.github/workflows/dedicated-server.yml
+++ b/.github/workflows/dedicated-server.yml
@@ -3,7 +3,7 @@
# The image always carries the LATEST OFFICIAL MPFever release: the package is built from that release's tag (build.bat) with the launcher
# changes of this branch applied on top (they disappear from the patch once a release contains them). So players on the official release can join.
#
-# Publication to GHCR (ghcr.io//mpfever-server-docker, named like the relay's mpfever-relay-docker) happens ONLY on purpose, after every job above has passed:
+# Publication to GHCR (ghcr.io//mpfever-server, named like the relay's mpfever-relay) happens ONLY on purpose, after every job above has passed:
# - pushing a tag dedicated-server-v[-] (for example dedicated-server-v0.9.1): image tags "[-]" and "experimental"
# - or a manual run (workflow_dispatch, workflow file on the default branch) with "publish" ticked.
# A push or a pull request never publishes.
@@ -164,7 +164,7 @@ jobs:
if [ "${{ github.ref_type }}" = tag ]; then
pub=true; vtag="${{ github.ref_name }}"; vtag="${vtag#dedicated-server-v}" # 0.9.1 or 0.9.1-2
fi
- echo "publish=$pub" >> "$GITHUB_OUTPUT"; echo "repo=ghcr.io/$owner/mpfever-server-docker" >> "$GITHUB_OUTPUT"; echo "vtag=$vtag" >> "$GITHUB_OUTPUT"
+ echo "publish=$pub" >> "$GITHUB_OUTPUT"; echo "repo=ghcr.io/$owner/mpfever-server" >> "$GITHUB_OUTPUT"; echo "vtag=$vtag" >> "$GITHUB_OUTPUT"
- name: Log in to GHCR
if: steps.tags.outputs.publish == 'true'
uses: docker/login-action@v3
diff --git a/server/.env.example b/server/.env.example
index f794c9ed..66b2eb00 100644
--- a/server/.env.example
+++ b/server/.env.example
@@ -18,5 +18,5 @@ MOTD=
# Resource limits. Measured for a small world: about 11 GB of RAM and 0.7 core.
MEM_LIMIT=14g
CPUS=2
-# Another image or version (rollback): MPFEVER_IMAGE=ghcr.io/dkdknight/mpfever-server-docker:
+# Another image or version (rollback): MPFEVER_IMAGE=ghcr.io/dkdknight/mpfever-server:
#MPFEVER_IMAGE=
diff --git a/server/README.md b/server/README.md
index b548f8d9..c3ae8a04 100644
--- a/server/README.md
+++ b/server/README.md
@@ -55,14 +55,14 @@ with `install-game` at any time. Server console commands (`save`, `kick`, ...) a
## Update and roll back
-Images are tagged by version (`ghcr.io/dkdknight/mpfever-server-docker:`) and `experimental`. Update: `docker compose pull && docker compose up -d`. Roll back: set
-`MPFEVER_IMAGE=ghcr.io/dkdknight/mpfever-server-docker:` in `.env` and `docker compose up -d`; the data volume is untouched. Players need the MPFever client of the server's version.
+Images are tagged by version (`ghcr.io/dkdknight/mpfever-server:`) and `experimental`. Update: `docker compose pull && docker compose up -d`. Roll back: set
+`MPFEVER_IMAGE=ghcr.io/dkdknight/mpfever-server:` in `.env` and `docker compose up -d`; the data volume is untouched. Players need the MPFever client of the server's version.
See [docs/OPERATIONS.md](docs/OPERATIONS.md) for backups, Valve updates, security and troubleshooting.
## Versions and tags
The image always carries the **latest official MPFever release** (the package is built from that release's tag, with the launcher changes of this branch applied until a release contains them), so players on the official client can join.
-The image is named like the relay's (`mpfever-relay-docker`): `ghcr.io//mpfever-server-docker`. Tags: the MPFever version (for example `0.9.1`; `0.9.1-2` for a rebuild of the same release) and `experimental` (the latest build). Pin a version tag in production.
+The image is named like the relay's (`mpfever-relay`): `ghcr.io//mpfever-server`. Tags: the MPFever version (for example `0.9.1`; `0.9.1-2` for a rebuild of the same release) and `experimental` (the latest build). Pin a version tag in production.
Publishing is deliberate: pushing the git tag `dedicated-server-v[-]` (or a manual workflow run) publishes after the checks pass; a push or a pull request never does.
## Build it yourself
diff --git a/server/compose.yaml b/server/compose.yaml
index cd27c373..52378c6f 100644
--- a/server/compose.yaml
+++ b/server/compose.yaml
@@ -3,7 +3,7 @@ name: mpfever-server
services:
mpfever-server:
- image: ${MPFEVER_IMAGE:-ghcr.io/dkdknight/mpfever-server-docker:experimental}
+ image: ${MPFEVER_IMAGE:-ghcr.io/dkdknight/mpfever-server:experimental}
container_name: ${CONTAINER_NAME:-mpfever-server}
restart: unless-stopped
init: true
diff --git a/server/docs/OPERATIONS.md b/server/docs/OPERATIONS.md
index fc1ee95b..7d67f2ca 100644
--- a/server/docs/OPERATIONS.md
+++ b/server/docs/OPERATIONS.md
@@ -20,7 +20,7 @@ Dock never starts `steam.exe`, so the pinned client is **never updated by Steam
## Update, roll back, back up
-- Update: `docker compose pull && docker compose up -d`. Roll back: `MPFEVER_IMAGE=ghcr.io/dkdknight/mpfever-server-docker:` in `.env`. The launcher package is replaced at each start; `.env` and the volumes stay.
+- Update: `docker compose pull && docker compose up -d`. Roll back: `MPFEVER_IMAGE=ghcr.io/dkdknight/mpfever-server:` in `.env`. The launcher package is replaced at each start; `.env` and the volumes stay.
- Players must run the MPFever client of the server's version (the launcher says "other version than the host's" otherwise).
- Back up the `mpfever-data` volume (saves, `srv/backups`, session). Never copy `secrets/steam.json` anywhere else; revoke it from your Steam account (Settings, Security, devices) if it leaks.
- Resetting: remove the volumes (`docker compose down -v`) to start from nothing; the game volume is rebuilt by `install-game`.
From e852e93ff2ffdfd5770be83b529dfa6c77eb5d64 Mon Sep 17 00:00:00 2001
From: ampynjord <82981605+ampynjord@users.noreply.github.com>
Date: Thu, 19 Nov 2026 15:55:11 +0100
Subject: [PATCH 10/47] docs: the published image lives on
ghcr.io/ampynjord/mpfever-server
---
server/.env.example | 2 +-
server/README.md | 10 +++++-----
server/compose.yaml | 2 +-
server/docs/OPERATIONS.md | 2 +-
4 files changed, 8 insertions(+), 8 deletions(-)
diff --git a/server/.env.example b/server/.env.example
index 66b2eb00..108c1eb6 100644
--- a/server/.env.example
+++ b/server/.env.example
@@ -18,5 +18,5 @@ MOTD=
# Resource limits. Measured for a small world: about 11 GB of RAM and 0.7 core.
MEM_LIMIT=14g
CPUS=2
-# Another image or version (rollback): MPFEVER_IMAGE=ghcr.io/dkdknight/mpfever-server:
+# Another image or version (rollback): MPFEVER_IMAGE=ghcr.io/ampynjord/mpfever-server:
#MPFEVER_IMAGE=
diff --git a/server/README.md b/server/README.md
index c3ae8a04..1b5ac2a5 100644
--- a/server/README.md
+++ b/server/README.md
@@ -19,8 +19,8 @@ Players join it with the usual MPFever client (same version) from Windows.
```
mkdir mpfever-server && cd mpfever-server
-curl -fsSLO https://raw.githubusercontent.com/dkdknight/MPFever/main/server/compose.yaml
-curl -fsSL https://raw.githubusercontent.com/dkdknight/MPFever/main/server/.env.example -o .env
+curl -fsSLO https://raw.githubusercontent.com/ampynjord/MPFever/feature/dedicated-server/server/compose.yaml
+curl -fsSL https://raw.githubusercontent.com/ampynjord/MPFever/feature/dedicated-server/server/.env.example -o .env
```
Edit `.env` (at least `WORLD`, the savegame's name without `.sav`). Then, once:
@@ -55,14 +55,14 @@ with `install-game` at any time. Server console commands (`save`, `kick`, ...) a
## Update and roll back
-Images are tagged by version (`ghcr.io/dkdknight/mpfever-server:`) and `experimental`. Update: `docker compose pull && docker compose up -d`. Roll back: set
-`MPFEVER_IMAGE=ghcr.io/dkdknight/mpfever-server:` in `.env` and `docker compose up -d`; the data volume is untouched. Players need the MPFever client of the server's version.
+Images are tagged by version (`ghcr.io/ampynjord/mpfever-server:`) and `experimental`. Update: `docker compose pull && docker compose up -d`. Roll back: set
+`MPFEVER_IMAGE=ghcr.io/ampynjord/mpfever-server:` in `.env` and `docker compose up -d`; the data volume is untouched. Players need the MPFever client of the server's version.
See [docs/OPERATIONS.md](docs/OPERATIONS.md) for backups, Valve updates, security and troubleshooting.
## Versions and tags
The image always carries the **latest official MPFever release** (the package is built from that release's tag, with the launcher changes of this branch applied until a release contains them), so players on the official client can join.
-The image is named like the relay's (`mpfever-relay`): `ghcr.io//mpfever-server`. Tags: the MPFever version (for example `0.9.1`; `0.9.1-2` for a rebuild of the same release) and `experimental` (the latest build). Pin a version tag in production.
+The image is `ghcr.io/ampynjord/mpfever-server` (named like the relay's `mpfever-relay`; published from the maintainer's fork, a project that builds it elsewhere publishes `ghcr.io//mpfever-server`). Tags: the MPFever version (for example `0.9.1`; `0.9.1-2` for a rebuild of the same release) and `experimental` (the latest build). Pin a version tag in production.
Publishing is deliberate: pushing the git tag `dedicated-server-v[-]` (or a manual workflow run) publishes after the checks pass; a push or a pull request never does.
## Build it yourself
diff --git a/server/compose.yaml b/server/compose.yaml
index 52378c6f..d85a64f3 100644
--- a/server/compose.yaml
+++ b/server/compose.yaml
@@ -3,7 +3,7 @@ name: mpfever-server
services:
mpfever-server:
- image: ${MPFEVER_IMAGE:-ghcr.io/dkdknight/mpfever-server:experimental}
+ image: ${MPFEVER_IMAGE:-ghcr.io/ampynjord/mpfever-server:experimental}
container_name: ${CONTAINER_NAME:-mpfever-server}
restart: unless-stopped
init: true
diff --git a/server/docs/OPERATIONS.md b/server/docs/OPERATIONS.md
index 7d67f2ca..3120aacf 100644
--- a/server/docs/OPERATIONS.md
+++ b/server/docs/OPERATIONS.md
@@ -20,7 +20,7 @@ Dock never starts `steam.exe`, so the pinned client is **never updated by Steam
## Update, roll back, back up
-- Update: `docker compose pull && docker compose up -d`. Roll back: `MPFEVER_IMAGE=ghcr.io/dkdknight/mpfever-server:` in `.env`. The launcher package is replaced at each start; `.env` and the volumes stay.
+- Update: `docker compose pull && docker compose up -d`. Roll back: `MPFEVER_IMAGE=ghcr.io/ampynjord/mpfever-server:` in `.env`. The launcher package is replaced at each start; `.env` and the volumes stay.
- Players must run the MPFever client of the server's version (the launcher says "other version than the host's" otherwise).
- Back up the `mpfever-data` volume (saves, `srv/backups`, session). Never copy `secrets/steam.json` anywhere else; revoke it from your Steam account (Settings, Security, devices) if it leaks.
- Resetting: remove the volumes (`docker compose down -v`) to start from nothing; the game volume is rebuilt by `install-game`.
From 74a28b0812faaf740d7649116d4a458621d566ba Mon Sep 17 00:00:00 2001
From: ampynjord <82981605+ampynjord@users.noreply.github.com>
Date: Thu, 19 Nov 2026 15:58:18 +0100
Subject: [PATCH 11/47] docs: a dedicated guide docs/LINUX-SERVER.md (like
RELAY.md), changelog entry, server/README.md as an index
---
README.md | 1 +
docs/CHANGELOG.txt | 7 ++
docs/LINUX-SERVER.md | 147 +++++++++++++++++++++++++++++++++++
docs/RELAY.md | 4 +-
server/.env.example | 2 +-
server/Dockerfile | 2 +-
server/README.md | 86 +++-----------------
server/compose.yaml | 2 +-
server/docs/ARCHITECTURE.md | 52 -------------
server/docs/OPERATIONS.md | 36 ---------
server/scripts/entrypoint.sh | 8 +-
server/scripts/lib.sh | 2 +-
12 files changed, 177 insertions(+), 172 deletions(-)
create mode 100644 docs/LINUX-SERVER.md
delete mode 100644 server/docs/ARCHITECTURE.md
delete mode 100644 server/docs/OPERATIONS.md
diff --git a/README.md b/README.md
index e3d2a95d..bc09dd76 100644
--- a/README.md
+++ b/README.md
@@ -209,6 +209,7 @@ The savegames are in `Steam\userdata\\3493540\local\save\` (Steam) or `%
| Game mod | `mod/mpfever_1/` (Lua) | Captures player actions and replays them in every game at the same game time (barrier lockstep). It computes the state checksums and manages the companies. It also draws the multiplayer page and the in-game windows. It does nothing unless the game was started by the launcher. |
| Native module | `native/` (C++, no CRT) | `winhttp.dll` in the game folder, a pass-through proxy. In a session, it holds construction commands until the shared step, copies terrain edits, separates each player's company, and fixes the game's sources of randomness and its pacing. |
| Relay (`mpfever-relay`) | `relay/` (C#, .NET 9) | Not the dedicated server: an optional meeting point that runs on any small Linux or Windows machine, with no game on it: the first player in hosts through it (no port to open, one address for everybody) and, with experimental `--migration`, an eligible player can take over when the host leaves. See [RELAY](docs/RELAY.md). |
+| Linux dedicated server (`mpfever-server`, experimental) | `server/` | The Windows game under Wine in a Docker container, with Valve's own client library through Madeira Dock: a dedicated server that runs on Linux, no GPU. See [docs/LINUX-SERVER.md](docs/LINUX-SERVER.md). |
| Tests | `tests/` (Python + lupa) | Language files and a simulated lockstep. |
The launcher and the game talk through files in `%TEMP%\mpfever\\`. No process injection is used.
diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index f1c26a49..f1b36af2 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -2,6 +2,13 @@ MPFever - Changelog
===================
0.9.2 - (in progress)
+ - NEW (experimental, server/, docs/LINUX-SERVER.md): a dedicated server on Linux, in one Docker container: the Windows game under Wine, started through
+ Madeira Dock (Valve's own client library: real sign-in and licence check, no Steam desktop, about 280 MB), software Vulkan with a layer that makes drawing a
+ no-op, a "lite" game install (66 GB become about 1 GB), no GPU. Players join it like any dedicated server. The launcher gets a Linux/Wine start mode
+ (MPFEVER_WINE=1, MPFEVER_DOCK) and a stop file (MPFEVER_STOPFILE: the world is saved, then the server stops, as the console's "stop"); nothing changes on
+ Windows. The image (ghcr.io/ampynjord/mpfever-server, tagged with the MPFever version and "experimental") holds no game or Valve file; install-game,
+ login (QR code, no password), import-save and status are its administration commands. Validated end to end for short sessions with a real Windows
+ client; long runs, several clients and large worlds are not yet (see the guide). CI: .github/workflows/dedicated-server.yml.
- BUILD (code signing, 2026-11-19: SignPath Foundation accepted MPFever; their first step is a signature with their
self-signed test certificate, then they review the setup and import the Foundation's certificate): the Release build
workflow asks for the signing policy, test-signing by default, release-signing once the certificate is in. Archives signed
diff --git a/docs/LINUX-SERVER.md b/docs/LINUX-SERVER.md
new file mode 100644
index 00000000..caff12af
--- /dev/null
+++ b/docs/LINUX-SERVER.md
@@ -0,0 +1,147 @@
+# MPFever dedicated server for Linux (`mpfever-server`, experimental)
+
+The dedicated server on Linux: the **real Transport Fever 3 simulation** (the Windows game, under Wine) in one Docker container. No GPU, no screen, no
+Steam desktop. Players join it with the usual MPFever client, from Windows, exactly as they join the Windows dedicated server.
+
+> **Status: experimental.** Validated end to end on the built image for short sessions on a small world with a real Windows client (see
+> [What is validated](#what-is-validated)). Long runs, several clients and large worlds are not validated yet. It needs **your own** Transport Fever 3
+> licence: the image contains no game file and no Valve file.
+
+## Dedicated server on Windows, on Linux, or relay
+
+| | Dedicated server (Windows) | Dedicated server (Linux, this page) | Relay ([RELAY.md](RELAY.md)) |
+|---|---|---|---|
+| Download | `MPFever--server.zip` | Docker image `mpfever-server` | `Relay-MPFever--...` or its Docker image |
+| Runs the game and the world | yes | yes (Windows game under Wine) | no: the hosting player's PC does |
+| Needs | Windows, the game installed | Linux x86-64 with Docker, about 12 GB of RAM, your game files once | nothing but the program |
+| Steam | the desktop client | Valve's client library only (about 280 MB) | none |
+
+## Quick start
+
+You need a Linux x86-64 host or VPS with Docker (Compose v2), 12 GB of RAM or more for the container, about 1 core, a file system with sparse-file support
+(ext4, xfs, btrfs), about 6 GB of disk, a Steam account that owns Transport Fever 3 with the Steam mobile app (to approve the sign-in once), a copy of the game
+on a PC where it is installed, and a savegame (`.sav`) of the world to host. Use an account that is not played on at the same time as the server.
+
+```
+mkdir mpfever-server && cd mpfever-server
+curl -fsSLO https://raw.githubusercontent.com/ampynjord/MPFever/feature/dedicated-server/server/compose.yaml
+curl -fsSL https://raw.githubusercontent.com/ampynjord/MPFever/feature/dedicated-server/server/.env.example -o .env
+```
+
+Edit `.env` (at least `WORLD`, the savegame's name without `.sav`). Then, once:
+
+1. **Pull the image**: `docker compose pull`
+2. **Import the game** from your own Steam library (read-only mount; the 3D data is left out, 66 GB become about 1 GB on disk):
+ `docker compose run --rm -v "/path/to/Steam/steamapps:/src:ro" mpfever-server install-game /src`
+ (`/path/to/Steam/steamapps` holds `common/Transport Fever 3` and `appmanifest_3493540.acf`.)
+3. **Sign in to Steam**: `docker compose run --rm mpfever-server login`. A QR code appears in the terminal; approve it in the Steam mobile app. No password is typed or stored.
+4. **Import your savegame** (the `.sav` and the files next to it): `docker compose run --rm -v "/path/to/saves:/in:ro" mpfever-server import-save /in/myworld.sav`
+5. **Start**: `docker compose up -d`. It restarts by itself after a reboot or a crash. `docker compose logs -f` shows the server's log.
+
+Players connect to `:28090` (forward the TCP port on your router for the Internet). `docker compose stop` saves the world first. The very first start takes a few
+minutes longer (Wine prefix, Valve client download) and the game restarts once by itself.
+
+Commands for the administrator (the service is `mpfever-server`):
+
+| | |
+|---|---|
+| `docker compose ps` / `logs -f` | state, health, log |
+| `docker compose run --rm mpfever-server status` | what is missing (game, Steam session, savegame, sparse files, disk) |
+| `docker compose exec mpfever-server /opt/mpfever/scripts/measure.sh` | memory (container, processes), CPU over 30 s, synchronisation |
+| `docker compose run --rm mpfever-server login` | sign in again when the Steam session expires (about 7 months) |
+| `docker compose run --rm -v "...:/in:ro" mpfever-server import-save /in/.sav` | add or replace a savegame |
+
+## Settings
+
+Everything is in `.env` and takes effect with `docker compose up -d`, no rebuild. Only `WORLD` is required.
+
+| Variable | Default | |
+|---|---|---|
+| `WORLD` | | the savegame to host (name without `.sav`) |
+| `SERVER_NAME`, `MOTD` | `MPFever Server`, empty | name and welcome message |
+| `PORT` | `28090` | TCP port |
+| `PASSWORD`, `MAX_PLAYERS` | empty, `8` | |
+| `COMPANY_MODE` | `shared` | `shared` or `separate` (one company per player) |
+| `START_SPEED`, `PAUSE_WHEN_EMPTY`, `PLAYER_SPEED_CONTROL` | `1`, `false`, `true` | |
+| `AUTOSAVE_MINUTES`, `BACKUPS` | `10`, `10` | autosave and copies kept in `srv/backups` |
+| `PUBLIC`, `PUBLIC_ADDRESS` | `false`, empty | list the server in MPFever's public list |
+| `MEM_LIMIT`, `CPUS` | `14g`, `2` | container limits (measured need: about 11 GB and 0.7 core for a small world) |
+| `MPFEVER_IMAGE` | the published image | another image or a version tag (rollback) |
+
+They are written to the server's `mpfever_server.properties` at every start (the game's other server options of SERVER.txt are the launcher's own).
+Data live in two named volumes: `mpfever-data` (Wine prefix, Valve client, Steam session, saves, launcher logs and backups) and `mpfever-game` (the lite game install,
+rebuilt at any time with `install-game`). Back up `mpfever-data`.
+
+## How it works
+
+| Part | What | Why |
+|---|---|---|
+| Game | `TransportFever3.exe` under Wine 11 (pinned package) on Ubuntu 24.04 | A native Linux game drifts from Windows clients (different C++ library, `std::` distributions inlined in the game): the same executable keeps the same simulation. No Proton, no DXVK: rendering is a no-op. |
+| Launcher | `MPFever.exe --server --server-start headless` under Mono, with a Linux/Wine mode (`GameInstall.WineMode`, `MPFEVER_WINE=1`; `MPFEVER_STOPFILE` for a clean stop) | The same host logic, `winhttp.dll` module and mod as the players'. |
+| Steam | [Madeira Dock](https://github.com/willfaust/madeira-dock) (`dockhost.exe`, built from source at a pinned commit) driving **Valve's own `steamclient64.dll`** | The game requires a running Valve client. Dock signs in with the owner's refresh token, asks Valve's client for the licence and has it start the game: no `steam.exe`, no web helper (about 280 MB instead of 2.7 GB). No Steamworks emulation, no DRM bypass: every decision is Valve's. |
+| Rendering | Lavapipe (software Vulkan) and the layer `server/vklayer/` (`MPF_VKNULL=1`, `MPF_VKNULL_MODE=all`, `MPF_VKNULL_TRIM=1`), `MPFEVER_HEADLESS_NORENDER=1;MPFEVER_HEADLESS_FPS=10` | Draws, copies and render passes become no-ops; mapped GPU memory nobody reads is given back. A real GPU is used if the layer is off (`compose.gpu.yaml`, not validated). |
+| Disk | the "lite" install (`server/scripts/mklite.py`) | The engine reads archives at fixed offsets, so archives keep their layout: textures, audio and blobs become file holes (sparse), images stay valid but empty. Generated from the host's own copy, never distributed. |
+| Display | `Xvfb` only | The game closes without an X server. Nothing is exposed: no VNC, no remote desktop. |
+
+The image is **versioned by the MPFever release** it carries (`0.9.1`, `0.9.1-2` for a rebuild) plus `experimental`: it is built from the latest official release's sources with the launcher
+changes of the Linux server applied, so the players' official client can join. The image holds no secret, no Transport Fever 3 file and no Valve file; the Valve client library is
+fetched from Valve at the first start (pinned build, hash-checked). Start (`server/scripts/entrypoint.sh run`): checks (disk, sparse support, RAM, game, session, savegame), first-start
+Wine prefix, the launcher restarted when it exits (five failures within a minute stop the container with a message), `SIGTERM` writes the stop file: the world is saved, the game closed, then the container exits.
+
+## Steam sign-in
+
+`login` uses Steam's own authentication service (the QR flow of the Steam mobile app) and keeps a **refresh token** in `secrets/steam.json` of the data volume (mode 0600). At every game
+start the token is handed to Dock as its one-use transfer file; it never appears on a command line, in the environment or in the image. When it expires the server stops with
+a message (`login` again). Revoke it from your Steam account (Settings, Security) if it leaks.
+
+## Madeira Dock and Valve's client: compatibility and risks
+
+Dock calls internal interfaces of Valve's client library by position in its method tables, so it only drives builds it has verified (by the SHA-256 of `steamclient64.dll`) and refuses any
+other (result 30, before any sign-in). The image pins the January 2026 build:
+
+| | |
+|---|---|
+| `steamclient64.dll` | 25 546 904 bytes, SHA-256 `71b391fe9f3e2006cbc81a5c75eef3eb4186012deabfdb2c8b7e8d4850ecf640` |
+| Package fetched from Valve | `https://client-update.akamai.steamstatic.com/bins_win32.zip.23e34a6d4b10596a44561a5100dac5585d2517da`, SHA-256 `8b712b2a3412a9066b7725f4e1c5cef9a7ca5b187b6585a5b92d25d09df0ba62` (checked before use) |
+| Madeira Dock | github.com/willfaust/madeira-dock, commit `67780ba92e60dbfac4fe80eaf2ce34b9ea1a1c60` (GPL-3.0-or-later) |
+
+Dock never starts `steam.exe`, so the pinned client is never updated by Steam. Valve could remove that archive or change its authentication protocol: the server then stops with an explicit message
+(hash mismatch, download failure, or Dock's refusal in `srv/dock.log`). There is no second Steam implementation: the remedy is a new Dock revision with a verified layout and a new pinned hash
+(`server/scripts/lib.sh`, `server/Dockerfile`). Dock is a young third-party project, not endorsed by Valve; overlay, cloud saves and achievements are not supported (the server does not use them).
+One Steam account plays one game at a time: playing on it elsewhere while the server runs can interrupt it (a few minutes of both was tolerated, no guarantee): use a dedicated account.
+
+## Update, roll back, security
+
+- Update: `docker compose pull && docker compose up -d`. Roll back: `MPFEVER_IMAGE=ghcr.io/ampynjord/mpfever-server:` in `.env`. The launcher package is replaced at each start; `.env` and the volumes stay.
+ Players must run the MPFever client of the server's version.
+- The container runs as uid 1001 with a read-only root file system, all capabilities dropped, `no-new-privileges`, only the game port published. `.env` holds the server password: keep it out of version control.
+- Exit codes: 20/21 Valve client download or hash, 30 game missing, 40/41 Steam session missing or expired, 42 savegame missing, 50 launcher failing repeatedly. Reports: `docker compose logs`, `srv/launcher.out`,
+ `srv/logs/`, and Dock's `srv/dock.log` (stage names and numbers only; result codes in madeira-dock's README).
+
+## Measured
+
+Small world, no GPU, one real Windows client:
+
+| | |
+|---|---|
+| Container | about 10.6 to 11.8 GB: anonymous 9.5 GB, reclaimable page cache 1 to 2 GB, shared 0.7 GB |
+| Game process | 10.0 GB (PSS); about 9 GB of it is the game's own heap; the Vulkan layer's trim returns about 0.7 GB |
+| Dock | 256 MB (193 MB PSS), about 0 CPU; the rest: launcher 107 MB, Wine desktop 87 MB, Xvfb 23 MB |
+| CPU | about 0.6 core at x0.98 game speed |
+| Disk | 1.3 GB game (66 GB apparent), about 3 GB prefix and Valve client; image 3.5 GB |
+| Sync with a real Windows client | join, resynchronisation 140 s, `IDENTICAL on 2 games`, 0 desynchronisations over about 6 minutes |
+
+## What is validated
+
+Run end to end on the built image with volumes created empty, a real account and a real Windows client: `install-game`, the QR `login`, the token hand-over to Dock (Steamworks without a Steam
+desktop), first start, `import-save`, world load, a client joining and staying identical, `docker compose stop` (about 10 s, world saved), restart restoring the saved world, the healthcheck, the
+read-only container.
+**Not validated yet:** runs of 30 minutes or more, memory growth over time, several clients (a second Steam account is needed, or local test clients), large worlds, enforced CPU/memory limits,
+stopping while a client has vanished, the GPU variant.
+
+## Build and tests
+
+`.github/workflows/dedicated-server.yml` runs the static checks (`server/tests/check.sh`: shell, Python tests, Compose, no secrets or binaries), builds the package from the latest official release with the
+Linux server's launcher changes, builds the image, smoke-tests it (unprivileged, no game or Valve file inside, explicit errors on empty volumes) and publishes only when a tag
+`dedicated-server-v` is pushed or the workflow is run by hand with "publish" ticked. Locally: put a package built by `build.bat` in `server/dist/MPFever-server.zip` and
+`docker compose -f compose.yaml -f compose.build.yaml build` (`APT_MIRROR` can name another Ubuntu mirror).
diff --git a/docs/RELAY.md b/docs/RELAY.md
index 0ac0cf1f..3093a6d9 100644
--- a/docs/RELAY.md
+++ b/docs/RELAY.md
@@ -42,8 +42,8 @@ They are two different things:
| Public server list, autosaves, restarts | Yes | No |
Use the dedicated server when a Windows PC can run the game all the time. Use the relay when the host has no port to open, when you want a
-stable address, or when you want a cheap always-on meeting point on a small machine. A Linux dedicated server (the game itself on Linux) does not
-exist: the relay is not that, and the game's native module (`winhttp.dll`) has no Linux version.
+stable address, or when you want a cheap always-on meeting point on a small machine. The relay is not a Linux dedicated server; that one now exists
+(experimental): the Windows game under Wine in a Docker container, see [LINUX-SERVER.md](LINUX-SERVER.md).
## Quick start
diff --git a/server/.env.example b/server/.env.example
index 108c1eb6..e763cdca 100644
--- a/server/.env.example
+++ b/server/.env.example
@@ -1,5 +1,5 @@
# Copy to .env. Everything but WORLD has a default. Changing a value never needs a rebuild: docker compose up -d
-# The savegame to host: its name without .sav, imported with `import-save` (README.md).
+# The savegame to host: its name without .sav, imported with `import-save` (docs/LINUX-SERVER.md).
WORLD=myworld
SERVER_NAME=MPFever Server
# TCP port players connect to (forward it on your router for the Internet).
diff --git a/server/Dockerfile b/server/Dockerfile
index b171fa9b..1b03ad5c 100644
--- a/server/Dockerfile
+++ b/server/Dockerfile
@@ -1,6 +1,6 @@
# syntax=docker/dockerfile:1
# MPFever dedicated server (experimental): the Windows game under Wine 11 on Linux, Steam through Madeira Dock (Valve's own client library),
-# no GPU needed. See README.md and docs/ARCHITECTURE.md.
+# no GPU needed. See docs/LINUX-SERVER.md.
#
# Build context: this folder. The MPFever package (launcher, native module, mod, built from this repository by build.bat / CI) is an input:
# server/dist/MPFever-server.zip (the release\MPFever--server.zip of a build)
diff --git a/server/README.md b/server/README.md
index 1b5ac2a5..32f36442 100644
--- a/server/README.md
+++ b/server/README.md
@@ -1,76 +1,14 @@
# MPFever dedicated server for Linux (experimental)
-A server that runs the **real Transport Fever 3 simulation** in one Docker container: the Windows game under Wine, started through
-[Madeira Dock](https://github.com/willfaust/madeira-dock) and Valve's own Steam client library. No GPU, no screen, no Steam desktop.
-Players join it with the usual MPFever client (same version) from Windows.
-
-> **Status: experimental.** Validated end to end on the built image for short sessions on a small world with a real Windows client (see "Validation" in
-> [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md): long runs, several clients and large worlds are not validated). It needs **your own** Transport Fever 3 licence: the image contains no game file and no Valve file.
-
-## What you need
-
-- A Linux x86-64 host or VPS (Docker with Compose v2), **12 GB of RAM or more** free for the container, about 1 core, **a file system with sparse-file
- support** (ext4, xfs, btrfs) and about 6 GB of disk. No GPU.
-- A Steam account that **owns Transport Fever 3**, with the Steam mobile app (to approve the sign-in once). Use an account that is not played on
- at the same time as the server (one Steam account plays one game at a time).
-- A copy of the game on a PC where it is installed (to build the small "lite" install), and a savegame (`.sav`) of the world to host.
-
-## Install
-
-```
-mkdir mpfever-server && cd mpfever-server
-curl -fsSLO https://raw.githubusercontent.com/ampynjord/MPFever/feature/dedicated-server/server/compose.yaml
-curl -fsSL https://raw.githubusercontent.com/ampynjord/MPFever/feature/dedicated-server/server/.env.example -o .env
-```
-
-Edit `.env` (at least `WORLD`, the savegame's name without `.sav`). Then, once:
-
-1. **Pull the image**: `docker compose pull`
-2. **Import the game** from your own Steam library (read-only mount; the 3D data is left out, 66 GB become about 1 GB on disk):
- ```
- docker compose run --rm -v "/path/to/Steam/steamapps:/src:ro" mpfever-server install-game /src
- ```
- (`/path/to/Steam/steamapps` is the library folder that holds `common/Transport Fever 3` and `appmanifest_3493540.acf`.)
-3. **Sign in to Steam** (QR code in the terminal, approve it in the Steam mobile app; no password is typed or stored):
- ```
- docker compose run --rm mpfever-server login
- ```
- Only a Steam refresh token is kept, in the `mpfever-data` volume (`secrets/steam.json`, mode 0600). It is valid for several months; when it expires the
- server says so and you run `login` again.
-4. **Import your savegame** (the `.sav` and the files next to it with the same name):
- ```
- docker compose run --rm -v "/path/to/saves:/in:ro" mpfever-server import-save /in/myworld.sav
- ```
-5. **Start**: `docker compose up -d`. It restarts by itself after a reboot or a crash. `docker compose logs -f` shows the server's log.
-
-Check at any time what is missing: `docker compose run --rm mpfever-server status`. Memory and CPU: `docker compose exec mpfever-server /opt/mpfever/scripts/measure.sh`.
-The very first start takes a few minutes longer (Wine prefix, Valve client download) and the game restarts once by itself.
-Players connect to `:28090` (forward the TCP port on your router for the Internet). Stop with `docker compose stop` (the world is saved first).
-
-## Configuration
-
-All settings are in `.env` and take effect with `docker compose up -d`, no rebuild. The game's save files and the launcher's backups (`srv/backups`, `backups=` in `.env`)
-live in the `mpfever-data` volume: back it up (`docker run --rm -v mpfever-data:/d -v "$PWD":/b ubuntu tar czf /b/mpfever-data.tgz -C /d .`). The game volume `mpfever-game` can be rebuilt
-with `install-game` at any time. Server console commands (`save`, `kick`, ...) are those of `MPFever.exe --server` (see the server's `SERVER.txt`).
-
-## Update and roll back
-
-Images are tagged by version (`ghcr.io/ampynjord/mpfever-server:`) and `experimental`. Update: `docker compose pull && docker compose up -d`. Roll back: set
-`MPFEVER_IMAGE=ghcr.io/ampynjord/mpfever-server:` in `.env` and `docker compose up -d`; the data volume is untouched. Players need the MPFever client of the server's version.
-See [docs/OPERATIONS.md](docs/OPERATIONS.md) for backups, Valve updates, security and troubleshooting.
-
-## Versions and tags
-
-The image always carries the **latest official MPFever release** (the package is built from that release's tag, with the launcher changes of this branch applied until a release contains them), so players on the official client can join.
-The image is `ghcr.io/ampynjord/mpfever-server` (named like the relay's `mpfever-relay`; published from the maintainer's fork, a project that builds it elsewhere publishes `ghcr.io//mpfever-server`). Tags: the MPFever version (for example `0.9.1`; `0.9.1-2` for a rebuild of the same release) and `experimental` (the latest build). Pin a version tag in production.
-Publishing is deliberate: pushing the git tag `dedicated-server-v[-]` (or a manual workflow run) publishes after the checks pass; a push or a pull request never does.
-
-## Build it yourself
-
-`.github/workflows/dedicated-server.yml` does it all (static checks, package of the latest release with the launcher changes, image, smoke tests). To build locally, put a package built by `build.bat`
-(`release/MPFever--server.zip`) in `server/dist/MPFever-server.zip` and run `docker compose -f compose.yaml -f compose.build.yaml build`.
-
-## Licence
-
-GPL-3.0-or-later like MPFever. The image contains Madeira Dock (GPL-3.0-or-later, built from source at a pinned commit, licence texts in `/opt/mpfever/licenses`), Wine (LGPL), Mono, Mesa.
-Transport Fever 3 and Steam belong to their owners and are never redistributed here.
+Docker packaging of the Linux dedicated server: Dockerfile, Compose files, entrypoint and administration commands, Vulkan layer, tests.
+**The guide (install, settings, how it works, risks, validation status) is [docs/LINUX-SERVER.md](../docs/LINUX-SERVER.md).**
+
+| Path | |
+|---|---|
+| `compose.yaml`, `.env.example` | what a user needs: `docker compose up -d` |
+| `compose.build.yaml`, `compose.gpu.yaml` | local build; optional GPU (not validated) |
+| `Dockerfile` | multi-stage image (Madeira Dock and the Vulkan layer built from source, Wine and Mono pinned) |
+| `scripts/` | `entrypoint.sh` (run, login, install-game, import-save, status), `steam_session.py` (QR sign-in, token hand-over to Dock), `mklite.py` (lite game install), `healthcheck.sh`, `measure.sh` |
+| `vklayer/` | the Vulkan layer that makes drawing a no-op |
+| `config/settings.lua` | the game's minimal profile (lowest graphics) |
+| `tests/` | `check.sh` (static checks run by CI), unit tests |
diff --git a/server/compose.yaml b/server/compose.yaml
index d85a64f3..9e0142cc 100644
--- a/server/compose.yaml
+++ b/server/compose.yaml
@@ -1,4 +1,4 @@
-# MPFever dedicated server (experimental). Setup and first start: README.md. docker compose up -d
+# MPFever dedicated server (experimental). Setup and first start: docs/LINUX-SERVER.md. docker compose up -d
name: mpfever-server
services:
diff --git a/server/docs/ARCHITECTURE.md b/server/docs/ARCHITECTURE.md
deleted file mode 100644
index 35342c10..00000000
--- a/server/docs/ARCHITECTURE.md
+++ /dev/null
@@ -1,52 +0,0 @@
-# Architecture, decisions, measures
-
-## The pieces
-
-| Part | What | Why |
-|---|---|---|
-| Game | `TransportFever3.exe` (Windows) under **Wine 11** (pinned package) on Ubuntu 24.04 | A native Linux build of the game drifts from Windows clients (different C++ library, `std::` distributions inlined in the game): same executable = same simulation. Not Proton: no DXVK, rendering is a no-op. |
-| Launcher | `MPFever.exe --server --server-start headless` under **Mono**, with a Linux/Wine mode (`launcher/Core.cs`: `GameInstall.WineMode`, `MPFEVER_WINE=1`; `Server.cs`: `MPFEVER_STOPFILE`) | Provides all the host logic and the same `winhttp.dll` native module and mod as the players'. Built by `build.bat` from the latest official release tag with this branch's launcher changes applied (CI). |
-| Steam | **Madeira Dock** (`dockhost.exe`, built from source at a pinned commit) driving **Valve's own `steamclient64.dll`** | The game requires a running Valve client. Dock signs in with the account owner's refresh token, asks Valve's client for the licence and has it start the game: no `steam.exe`, no `steamwebhelper` (about 280 MB instead of 2.7 GB). No emulation of Steamworks, no DRM bypass: every decision is Valve's. |
-| Rendering | Lavapipe (software Vulkan) + the layer `vklayer/` (`MPF_VKNULL=1`, `MPF_VKNULL_MODE=all`, `MPF_VKNULL_TRIM=1`) and `MPFEVER_HEADLESS_NORENDER=1;MPFEVER_HEADLESS_FPS=10` | Draws, copies and render passes become no-ops; mapped GPU memory nobody reads is given back. A real GPU is used if the layer is off (`compose.gpu.yaml`, not validated). |
-| Disk | "Lite" game install (`scripts/mklite.py`) | The engine reads archives at fixed offsets, so archives keep their layout: textures, audio and blobs become file holes (sparse), images stay valid but empty. 66 GB become about 1 GB on disk. Generated from the host's own copy; never distributed. |
-| Display | `Xvfb` only | The game closes without an X server. Nothing is exposed (no VNC, no noVNC). |
-
-## Layers and data
-
-- **Image** (versioned, immutable): Wine, Mono, launcher package, Dock, Vulkan layer, scripts. No secret, no TF3 file, no Valve file.
-- **`/data` volume**: Wine prefix, Valve client (fetched from Valve, pinned hash), `secrets/steam.json`, saves (inside the Steam `userdata` of the prefix), `srv/` (launcher logs, backups).
-- **`/game` volume**: the lite game install. **Configuration**: `.env` (environment), written to `mpfever_server.properties` at each start.
-- **Sign-in**: `scripts/steam_session.py login` (Steam's `IAuthenticationService` QR flow, the same as the Steam mobile app's "sign in with QR") stores a refresh token;
- at each game start `feed` writes Dock's one-use transfer file (`MDOCK001`) with it. The token never appears on a command line, in the environment or in the image.
-- **Start** (`scripts/entrypoint.sh run`): checks (disk, sparse support, RAM, game, session, save), first-start prefix creation (marker file, so a restart reinstalls nothing), pinned Valve client,
- launcher with restart-on-exit (5 quick failures in a minute stop the container with a message), `SIGTERM` writes the stop file: the world is saved, the game closed, then the container exits.
-
-## Measured (small world, MPFever 0.9.2 package, no GPU, built image, fresh volumes)
-
-| | |
-|---|---|
-| Container (cgroup, game running, no client) | about 10.6 to 11.8 GB: anonymous 9.5 GB, page cache 1 to 2 GB (reclaimable), shared 0.7 GB |
-| Game process | RSS 10.1 GB, PSS 10.0 GB (the heap of about 9 GB is the game's own; the Vulkan layer's trim returns about 0.7 GB of mapped GPU memory) |
-| Dock (`dockhost.exe`) | RSS 256 MB, PSS 193 MB; its CPU is 0.02 core |
-| Other processes | launcher (Mono) 107 MB, Wine desktop 87 MB, Xvfb 23 MB, session feeder 20 MB, wineserver 15 MB |
-| CPU | game 0.6 core at x0.98 game speed |
-| Disk | game 1.3 GB on disk (66 GB apparent), prefix and Valve client about 3 GB |
-| Image | 3.5 GB (Wine 11 with its i386 part 1.5 GB, Mesa/LLVM about 0.3 GB, Mono runtime subset); was 4.3 GB with `mono-complete` |
-| Start | image to "game ready" about 2.5 minutes with a warm cache, plus about 1.5 minutes the very first time (prefix creation, Valve client download, one extra game start) |
-| Sync with a real Windows client (0.9.2) | join, resynchronisation 140 s, then `IDENTICAL on 2 games`, 0 desynchronisations, 6 minutes observed |
-
-`scripts/measure.sh` prints these figures from inside the container (`docker compose exec mpfever-server /opt/mpfever/scripts/measure.sh`).
-Tried and dropped: `MADV_REMOVE` on the mapped GPU memory (no gain), a Wine without its i386 package (the launcher binaries ship in the package that depends on it), fewer or no Lavapipe threads (CPU worse).
-
-## Validation status (honest)
-
-Run end to end on the built image, on volumes created empty: `install-game` from a real Steam library (2 min), Steam QR `login` (real account, token kept 0600, valid until the printed date),
-`import-save`, first start (Wine prefix, Valve client download with hash check), **token hand-over to Dock and Steamworks initialisation without any Steam desktop**, launch of Transport Fever 3 under Wine, MPFever server mode,
-world load, a real Windows client joining with resynchronisation and identical checks, `docker compose stop` (9 s, exit 0, world saved at stop), restart restoring the saved world time, healthcheck healthy, read-only root and no capabilities.
-**Not validated yet**: runs of 30 minutes or more; several clients (a Steam account plays one game at a time: a second account is needed); large worlds; forced CPU/memory minimums (limits are set, behaviour under pressure not tested);
-the GPU variant; the published image (nothing is published); stopping while a client is connected and has vanished (the stop waits for it up to about 45 s, the timeouts allow it); the CI image job (see the pull request).
-
-## Decisions not to redo
-
-Native Linux game: abandoned (drift). Steam desktop under Wine: replaced by Dock (2.7 GB web helper floor; stubbing it crashes Steam). Aurelia (headless Steam CLI) downloads the game but cannot run TF3 without a Steam client.
-A server without the game installed is impossible with the Steam build without circumventing the DRM (refused): the game comes from the host's own licence. `autoupdate=0` is mandatory (the official updater replaces the launcher and module).
diff --git a/server/docs/OPERATIONS.md b/server/docs/OPERATIONS.md
deleted file mode 100644
index 3120aacf..00000000
--- a/server/docs/OPERATIONS.md
+++ /dev/null
@@ -1,36 +0,0 @@
-# Operations: Valve client, updates, security, troubleshooting
-
-## Valve's Steam client and Madeira Dock (compatibility and risk)
-
-Dock calls **internal interfaces of Valve's client library** by position in its method tables, so it only drives builds it has verified (identified by the SHA-256 of `steamclient64.dll`)
-and refuses any other one (result 30, before any sign-in). This image pins:
-
-| | |
-|---|---|
-| `steamclient64.dll` | January 2026 build, 25 546 904 bytes, SHA-256 `71b391fe9f3e2006cbc81a5c75eef3eb4186012deabfdb2c8b7e8d4850ecf640` (PE timestamp 1769726215) |
-| Package fetched from Valve | `https://client-update.akamai.steamstatic.com/bins_win32.zip.23e34a6d4b10596a44561a5100dac5585d2517da`, SHA-256 `8b712b2a3412a9066b7725f4e1c5cef9a7ca5b187b6585a5b92d25d09df0ba62` (checked before use) |
-| Madeira Dock | github.com/willfaust/madeira-dock, commit `67780ba92e60dbfac4fe80eaf2ce34b9ea1a1c60` (GPL-3.0-or-later), built in the image |
-
-Dock never starts `steam.exe`, so the pinned client is **never updated by Steam itself**. Risks, stated plainly:
-1. Valve could remove that archive from its server or change its authentication protocol. The server then stops with an explicit message (hash mismatch, download failure, or Dock's refusal in `srv/dock.log`). There is no second Steam implementation to fall back on:
- the remedy is a new Dock revision with a verified layout, and a new pinned hash here (`scripts/lib.sh`, `Dockerfile`).
-2. Dock is a young third-party project, not endorsed by Valve. Overlay, cloud saves and achievements are not supported by it; the server does not use them.
-3. The sign-in is the account owner's own, through Steam's authentication service; tokens are stored only in `secrets/steam.json`. Using unofficial tooling on a Steam account carries the usual risk of Valve's rules: use an account you accept that for.
-4. One Steam account plays one game at a time: playing on that account elsewhere while the server runs can interrupt it (observed: a few minutes of both running was tolerated, no guarantee). A dedicated account (Family Sharing) is recommended.
-
-## Update, roll back, back up
-
-- Update: `docker compose pull && docker compose up -d`. Roll back: `MPFEVER_IMAGE=ghcr.io/ampynjord/mpfever-server:` in `.env`. The launcher package is replaced at each start; `.env` and the volumes stay.
-- Players must run the MPFever client of the server's version (the launcher says "other version than the host's" otherwise).
-- Back up the `mpfever-data` volume (saves, `srv/backups`, session). Never copy `secrets/steam.json` anywhere else; revoke it from your Steam account (Settings, Security, devices) if it leaks.
-- Resetting: remove the volumes (`docker compose down -v`) to start from nothing; the game volume is rebuilt by `install-game`.
-
-## Security
-
-Runs as uid 1001, read-only root file system, all capabilities dropped, `no-new-privileges`, only the game port published, no graphical or remote-desktop interface.
-The image holds no secret; `.env` holds the server password if you set one: keep it out of version control.
-
-## Troubleshooting
-
-`docker compose run --rm mpfever-server status` lists what is missing. Launcher log: `docker compose logs`, files `srv/launcher.out`, `srv/logs/`, Dock report `srv/dock.log` (stage names and numbers only; result codes in madeira-dock's README).
-Exit code 20/21 Valve client download or hash, 30 game missing, 40/41 Steam session missing or expired, 42 savegame missing, 50 launcher failing repeatedly.
diff --git a/server/scripts/entrypoint.sh b/server/scripts/entrypoint.sh
index 01a1aca3..b37b7fa8 100644
--- a/server/scripts/entrypoint.sh
+++ b/server/scripts/entrypoint.sh
@@ -44,7 +44,7 @@ ensure_client() { # Valve's pinned client library, fetched from Valve's own ser
}
link_game() {
- [ -f "$GAME/TransportFever3.exe" ] || die "no game install in $GAME: run install-game (README.md, step 2)" 30
+ [ -f "$GAME/TransportFever3.exe" ] || die "no game install in $GAME: run install-game (docs/LINUX-SERVER.md, quick start step 2)" 30
[ -f "$STEAM_DIR/steamapps/appmanifest_$APPID.acf" ] || die "the Steam app manifest is missing: run install-game again" 30
[ -L "$GAME_LINK" ] || { rmdir "$GAME_LINK" 2>/dev/null; ln -sfn "$GAME" "$GAME_LINK"; }
if [ ! -f "$STEAM_DIR/steamapps/libraryfolders.vdf" ]; then # the single library the Valve client needs to find the game
@@ -101,15 +101,15 @@ cmd_import_save() {
cmd_run() {
ensure_dirs
: "${WORLD:?set WORLD to the name of a savegame (without .sav)}"
- [ -f "$SESSION_FILE" ] || die "no Steam session: run login first (README.md, step 3)" 40
+ [ -f "$SESSION_FILE" ] || die "no Steam session: run login first (docs/LINUX-SERVER.md, quick start step 3)" 40
python3 "$OPT/scripts/steam_session.py" status --file "$SESSION_FILE" >/dev/null \
|| die "the Steam session has expired: run login again" 41
- [ -f "$GAME/TransportFever3.exe" ] || die "no game install in $GAME: run install-game (README.md, step 2)" 30
+ [ -f "$GAME/TransportFever3.exe" ] || die "no game install in $GAME: run install-game (docs/LINUX-SERVER.md, quick start step 2)" 30
supports_sparse "$GAME" || warn "$GAME has no sparse-file support: only a full copy of the game works there"
local ram; ram=$(awk '/MemTotal/ {printf "%d", $2/1048576}' /proc/meminfo)
[ "$ram" -ge 12 ] || warn "only $ram GB of RAM visible: the game needs about 11 GB"
init_prefix; ensure_client; link_game
- [ -f "$(save_dir)/$WORLD.sav" ] || die "savegame '$WORLD.sav' not found: run import-save (README.md, step 4)" 42
+ [ -f "$(save_dir)/$WORLD.sav" ] || die "savegame '$WORLD.sav' not found: run import-save (docs/LINUX-SERVER.md, quick start step 4)" 42
# the game's settings: a minimal profile (lowest graphics) the first time; MPFever activates its mod in it
mkdir -p "$(local_dir)/mods" "$(save_dir)" # where the game and MPFever look for the mod and the saves (a new profile has none of them)
[ -f "$(local_dir)/settings.lua" ] || cp "$OPT/config/settings.lua" "$(local_dir)/settings.lua"
diff --git a/server/scripts/lib.sh b/server/scripts/lib.sh
index 4a66d24a..080c8f32 100644
--- a/server/scripts/lib.sh
+++ b/server/scripts/lib.sh
@@ -11,7 +11,7 @@ export APPID=3493540
GAME_LINK="$STEAM_DIR/steamapps/common/Transport Fever 3"
OPT=/opt/mpfever
-# Valve's Steam client build driven by Madeira Dock, pinned (docs/COMPATIBILITY.md). Never updated by itself.
+# Valve's Steam client build driven by Madeira Dock, pinned (docs/LINUX-SERVER.md). Never updated by itself.
CLIENT_URL=https://client-update.akamai.steamstatic.com/bins_win32.zip.23e34a6d4b10596a44561a5100dac5585d2517da
CLIENT_ZIP_SHA256=8b712b2a3412a9066b7725f4e1c5cef9a7ca5b187b6585a5b92d25d09df0ba62
CLIENT_DLL_SHA256=71b391fe9f3e2006cbc81a5c75eef3eb4186012deabfdb2c8b7e8d4850ecf640
From b5b12ab3ba412902fab9d2297497ca6c0d476ae1 Mon Sep 17 00:00:00 2001
From: ampynjord <82981605+ampynjord@users.noreply.github.com>
Date: Thu, 19 Nov 2026 16:00:51 +0100
Subject: [PATCH 12/47] docs: DOCKER-SERVER.md (the host can be any x86-64
Docker host, not only Linux), table of supported hosts
---
README.md | 2 +-
docs/CHANGELOG.txt | 2 +-
docs/{LINUX-SERVER.md => DOCKER-SERVER.md} | 23 ++++++++++++++++------
docs/RELAY.md | 4 ++--
server/.env.example | 2 +-
server/Dockerfile | 2 +-
server/README.md | 6 +++---
server/compose.yaml | 2 +-
server/scripts/entrypoint.sh | 8 ++++----
server/scripts/lib.sh | 2 +-
10 files changed, 32 insertions(+), 21 deletions(-)
rename docs/{LINUX-SERVER.md => DOCKER-SERVER.md} (91%)
diff --git a/README.md b/README.md
index bc09dd76..ed1dc12e 100644
--- a/README.md
+++ b/README.md
@@ -209,7 +209,7 @@ The savegames are in `Steam\userdata\\3493540\local\save\` (Steam) or `%
| Game mod | `mod/mpfever_1/` (Lua) | Captures player actions and replays them in every game at the same game time (barrier lockstep). It computes the state checksums and manages the companies. It also draws the multiplayer page and the in-game windows. It does nothing unless the game was started by the launcher. |
| Native module | `native/` (C++, no CRT) | `winhttp.dll` in the game folder, a pass-through proxy. In a session, it holds construction commands until the shared step, copies terrain edits, separates each player's company, and fixes the game's sources of randomness and its pacing. |
| Relay (`mpfever-relay`) | `relay/` (C#, .NET 9) | Not the dedicated server: an optional meeting point that runs on any small Linux or Windows machine, with no game on it: the first player in hosts through it (no port to open, one address for everybody) and, with experimental `--migration`, an eligible player can take over when the host leaves. See [RELAY](docs/RELAY.md). |
-| Linux dedicated server (`mpfever-server`, experimental) | `server/` | The Windows game under Wine in a Docker container, with Valve's own client library through Madeira Dock: a dedicated server that runs on Linux, no GPU. See [docs/LINUX-SERVER.md](docs/LINUX-SERVER.md). |
+| Dedicated server in Docker (`mpfever-server`, experimental) | `server/` | The Windows game under Wine in a Linux container, with Valve's own client library through Madeira Dock: a dedicated server for any x86-64 Docker host, no GPU. See [docs/DOCKER-SERVER.md](docs/DOCKER-SERVER.md). |
| Tests | `tests/` (Python + lupa) | Language files and a simulated lockstep. |
The launcher and the game talk through files in `%TEMP%\mpfever\\`. No process injection is used.
diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index f1b36af2..36b1a9b5 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -2,7 +2,7 @@ MPFever - Changelog
===================
0.9.2 - (in progress)
- - NEW (experimental, server/, docs/LINUX-SERVER.md): a dedicated server on Linux, in one Docker container: the Windows game under Wine, started through
+ - NEW (experimental, server/, docs/DOCKER-SERVER.md): a dedicated server in one Linux Docker container (any x86-64 Docker host): the Windows game under Wine, started through
Madeira Dock (Valve's own client library: real sign-in and licence check, no Steam desktop, about 280 MB), software Vulkan with a layer that makes drawing a
no-op, a "lite" game install (66 GB become about 1 GB), no GPU. Players join it like any dedicated server. The launcher gets a Linux/Wine start mode
(MPFEVER_WINE=1, MPFEVER_DOCK) and a stop file (MPFEVER_STOPFILE: the world is saved, then the server stops, as the console's "stop"); nothing changes on
diff --git a/docs/LINUX-SERVER.md b/docs/DOCKER-SERVER.md
similarity index 91%
rename from docs/LINUX-SERVER.md
rename to docs/DOCKER-SERVER.md
index caff12af..f87f30a4 100644
--- a/docs/LINUX-SERVER.md
+++ b/docs/DOCKER-SERVER.md
@@ -1,24 +1,35 @@
-# MPFever dedicated server for Linux (`mpfever-server`, experimental)
+# MPFever dedicated server in Docker (`mpfever-server`, experimental)
-The dedicated server on Linux: the **real Transport Fever 3 simulation** (the Windows game, under Wine) in one Docker container. No GPU, no screen, no
+A dedicated server in a Linux container: the **real Transport Fever 3 simulation** (the Windows game, under Wine) in one Docker container. No GPU, no screen, no
Steam desktop. Players join it with the usual MPFever client, from Windows, exactly as they join the Windows dedicated server.
> **Status: experimental.** Validated end to end on the built image for short sessions on a small world with a real Windows client (see
> [What is validated](#what-is-validated)). Long runs, several clients and large worlds are not validated yet. It needs **your own** Transport Fever 3
> licence: the image contains no game file and no Valve file.
-## Dedicated server on Windows, on Linux, or relay
+## Where it runs
-| | Dedicated server (Windows) | Dedicated server (Linux, this page) | Relay ([RELAY.md](RELAY.md)) |
+"Linux" is the system inside the container. The host is any machine that runs Linux containers for x86-64:
+
+| Host | |
+|---|---|
+| Linux x86-64 (server, VPS) | yes, the target |
+| Windows with Docker Desktop (WSL2) | yes (give WSL2 at least 12 GB of RAM for the container: a Docker Desktop setting) |
+| macOS Intel | probably, not tried |
+| macOS Apple Silicon, other ARM hosts | no: the image is x86-64 and emulated Wine is far too slow |
+
+## Dedicated server on Windows, in Docker, or relay
+
+| | Dedicated server (Windows) | Dedicated server (Docker, this page) | Relay ([RELAY.md](RELAY.md)) |
|---|---|---|---|
| Download | `MPFever--server.zip` | Docker image `mpfever-server` | `Relay-MPFever--...` or its Docker image |
| Runs the game and the world | yes | yes (Windows game under Wine) | no: the hosting player's PC does |
-| Needs | Windows, the game installed | Linux x86-64 with Docker, about 12 GB of RAM, your game files once | nothing but the program |
+| Needs | Windows, the game installed | an x86-64 host with Docker, about 12 GB of RAM, your game files once | nothing but the program |
| Steam | the desktop client | Valve's client library only (about 280 MB) | none |
## Quick start
-You need a Linux x86-64 host or VPS with Docker (Compose v2), 12 GB of RAM or more for the container, about 1 core, a file system with sparse-file support
+You need an x86-64 host with Docker (Compose v2; a Linux server or VPS, or Windows with Docker Desktop), 12 GB of RAM or more for the container, about 1 core, a file system with sparse-file support
(ext4, xfs, btrfs), about 6 GB of disk, a Steam account that owns Transport Fever 3 with the Steam mobile app (to approve the sign-in once), a copy of the game
on a PC where it is installed, and a savegame (`.sav`) of the world to host. Use an account that is not played on at the same time as the server.
diff --git a/docs/RELAY.md b/docs/RELAY.md
index 3093a6d9..bc9702c3 100644
--- a/docs/RELAY.md
+++ b/docs/RELAY.md
@@ -42,8 +42,8 @@ They are two different things:
| Public server list, autosaves, restarts | Yes | No |
Use the dedicated server when a Windows PC can run the game all the time. Use the relay when the host has no port to open, when you want a
-stable address, or when you want a cheap always-on meeting point on a small machine. The relay is not a Linux dedicated server; that one now exists
-(experimental): the Windows game under Wine in a Docker container, see [LINUX-SERVER.md](LINUX-SERVER.md).
+stable address, or when you want a cheap always-on meeting point on a small machine. The relay is not a dedicated server in Docker; that one now exists
+(experimental): the Windows game under Wine in a Docker container, see [DOCKER-SERVER.md](DOCKER-SERVER.md).
## Quick start
diff --git a/server/.env.example b/server/.env.example
index e763cdca..ced7ca21 100644
--- a/server/.env.example
+++ b/server/.env.example
@@ -1,5 +1,5 @@
# Copy to .env. Everything but WORLD has a default. Changing a value never needs a rebuild: docker compose up -d
-# The savegame to host: its name without .sav, imported with `import-save` (docs/LINUX-SERVER.md).
+# The savegame to host: its name without .sav, imported with `import-save` (docs/DOCKER-SERVER.md).
WORLD=myworld
SERVER_NAME=MPFever Server
# TCP port players connect to (forward it on your router for the Internet).
diff --git a/server/Dockerfile b/server/Dockerfile
index 1b03ad5c..269fae56 100644
--- a/server/Dockerfile
+++ b/server/Dockerfile
@@ -1,6 +1,6 @@
# syntax=docker/dockerfile:1
# MPFever dedicated server (experimental): the Windows game under Wine 11 on Linux, Steam through Madeira Dock (Valve's own client library),
-# no GPU needed. See docs/LINUX-SERVER.md.
+# no GPU needed. See docs/DOCKER-SERVER.md.
#
# Build context: this folder. The MPFever package (launcher, native module, mod, built from this repository by build.bat / CI) is an input:
# server/dist/MPFever-server.zip (the release\MPFever--server.zip of a build)
diff --git a/server/README.md b/server/README.md
index 32f36442..2659711d 100644
--- a/server/README.md
+++ b/server/README.md
@@ -1,7 +1,7 @@
-# MPFever dedicated server for Linux (experimental)
+# MPFever dedicated server in Docker (experimental)
-Docker packaging of the Linux dedicated server: Dockerfile, Compose files, entrypoint and administration commands, Vulkan layer, tests.
-**The guide (install, settings, how it works, risks, validation status) is [docs/LINUX-SERVER.md](../docs/LINUX-SERVER.md).**
+Docker packaging of the dedicated server (a Linux container): Dockerfile, Compose files, entrypoint and administration commands, Vulkan layer, tests.
+**The guide (install, settings, how it works, risks, validation status) is [docs/DOCKER-SERVER.md](../docs/DOCKER-SERVER.md).**
| Path | |
|---|---|
diff --git a/server/compose.yaml b/server/compose.yaml
index 9e0142cc..f2621591 100644
--- a/server/compose.yaml
+++ b/server/compose.yaml
@@ -1,4 +1,4 @@
-# MPFever dedicated server (experimental). Setup and first start: docs/LINUX-SERVER.md. docker compose up -d
+# MPFever dedicated server (experimental). Setup and first start: docs/DOCKER-SERVER.md. docker compose up -d
name: mpfever-server
services:
diff --git a/server/scripts/entrypoint.sh b/server/scripts/entrypoint.sh
index b37b7fa8..7cec59fc 100644
--- a/server/scripts/entrypoint.sh
+++ b/server/scripts/entrypoint.sh
@@ -44,7 +44,7 @@ ensure_client() { # Valve's pinned client library, fetched from Valve's own ser
}
link_game() {
- [ -f "$GAME/TransportFever3.exe" ] || die "no game install in $GAME: run install-game (docs/LINUX-SERVER.md, quick start step 2)" 30
+ [ -f "$GAME/TransportFever3.exe" ] || die "no game install in $GAME: run install-game (docs/DOCKER-SERVER.md, quick start step 2)" 30
[ -f "$STEAM_DIR/steamapps/appmanifest_$APPID.acf" ] || die "the Steam app manifest is missing: run install-game again" 30
[ -L "$GAME_LINK" ] || { rmdir "$GAME_LINK" 2>/dev/null; ln -sfn "$GAME" "$GAME_LINK"; }
if [ ! -f "$STEAM_DIR/steamapps/libraryfolders.vdf" ]; then # the single library the Valve client needs to find the game
@@ -101,15 +101,15 @@ cmd_import_save() {
cmd_run() {
ensure_dirs
: "${WORLD:?set WORLD to the name of a savegame (without .sav)}"
- [ -f "$SESSION_FILE" ] || die "no Steam session: run login first (docs/LINUX-SERVER.md, quick start step 3)" 40
+ [ -f "$SESSION_FILE" ] || die "no Steam session: run login first (docs/DOCKER-SERVER.md, quick start step 3)" 40
python3 "$OPT/scripts/steam_session.py" status --file "$SESSION_FILE" >/dev/null \
|| die "the Steam session has expired: run login again" 41
- [ -f "$GAME/TransportFever3.exe" ] || die "no game install in $GAME: run install-game (docs/LINUX-SERVER.md, quick start step 2)" 30
+ [ -f "$GAME/TransportFever3.exe" ] || die "no game install in $GAME: run install-game (docs/DOCKER-SERVER.md, quick start step 2)" 30
supports_sparse "$GAME" || warn "$GAME has no sparse-file support: only a full copy of the game works there"
local ram; ram=$(awk '/MemTotal/ {printf "%d", $2/1048576}' /proc/meminfo)
[ "$ram" -ge 12 ] || warn "only $ram GB of RAM visible: the game needs about 11 GB"
init_prefix; ensure_client; link_game
- [ -f "$(save_dir)/$WORLD.sav" ] || die "savegame '$WORLD.sav' not found: run import-save (docs/LINUX-SERVER.md, quick start step 4)" 42
+ [ -f "$(save_dir)/$WORLD.sav" ] || die "savegame '$WORLD.sav' not found: run import-save (docs/DOCKER-SERVER.md, quick start step 4)" 42
# the game's settings: a minimal profile (lowest graphics) the first time; MPFever activates its mod in it
mkdir -p "$(local_dir)/mods" "$(save_dir)" # where the game and MPFever look for the mod and the saves (a new profile has none of them)
[ -f "$(local_dir)/settings.lua" ] || cp "$OPT/config/settings.lua" "$(local_dir)/settings.lua"
diff --git a/server/scripts/lib.sh b/server/scripts/lib.sh
index 080c8f32..53d5bc46 100644
--- a/server/scripts/lib.sh
+++ b/server/scripts/lib.sh
@@ -11,7 +11,7 @@ export APPID=3493540
GAME_LINK="$STEAM_DIR/steamapps/common/Transport Fever 3"
OPT=/opt/mpfever
-# Valve's Steam client build driven by Madeira Dock, pinned (docs/LINUX-SERVER.md). Never updated by itself.
+# Valve's Steam client build driven by Madeira Dock, pinned (docs/DOCKER-SERVER.md). Never updated by itself.
CLIENT_URL=https://client-update.akamai.steamstatic.com/bins_win32.zip.23e34a6d4b10596a44561a5100dac5585d2517da
CLIENT_ZIP_SHA256=8b712b2a3412a9066b7725f4e1c5cef9a7ca5b187b6585a5b92d25d09df0ba62
CLIENT_DLL_SHA256=71b391fe9f3e2006cbc81a5c75eef3eb4186012deabfdb2c8b7e8d4850ecf640
From 60129bce49495b213277ecc1715c24f7cc21819e Mon Sep 17 00:00:00 2001
From: ampynjord <82981605+ampynjord@users.noreply.github.com>
Date: Thu, 19 Nov 2026 16:06:52 +0100
Subject: [PATCH 13/47] Madeira Dock integrated: sources in server/dock
(unit-tested, built in the image from them), maintenance guide, docs and CI
wording
---
.github/workflows/dedicated-server.yml | 2 +-
docs/CHANGELOG.txt | 3 +-
docs/DOCKER-SERVER.md | 14 +-
server/.dockerignore | 1 +
server/Dockerfile | 13 +-
server/dock/COPYING | 674 ++++++++++++++++++++++
server/dock/LICENSE | 27 +
server/dock/LICENSE-EXCEPTION.md | 71 +++
server/dock/MAINTAINING.md | 46 ++
server/dock/README.upstream.md | 350 +++++++++++
server/dock/THIRD-PARTY-NOTICES.md | 35 ++
server/dock/build.sh | 8 +
server/dock/check.sh | 14 +
server/dock/docs/CLIENT_LAYOUTS.md | 127 ++++
server/dock/docs/OFFLINE.md | 74 +++
server/dock/notices/LLVM.txt | 279 +++++++++
server/dock/notices/MinGW-w64-runtime.txt | 265 +++++++++
server/dock/src/auth.c | 97 ++++
server/dock/src/auth.h | 29 +
server/dock/src/client_layout.c | 38 ++
server/dock/src/client_layout.h | 24 +
server/dock/src/hold.c | 137 +++++
server/dock/src/hold.h | 39 ++
server/dock/src/launch.c | 492 ++++++++++++++++
server/dock/src/launch.h | 11 +
server/dock/src/main.c | 340 +++++++++++
server/dock/src/probe.c | 68 +++
server/dock/src/probe.h | 58 ++
server/dock/src/scm.c | 380 ++++++++++++
server/dock/src/scm.h | 41 ++
server/dock/src/session.c | 410 +++++++++++++
server/dock/src/session.h | 11 +
server/dock/src/validation.c | 354 ++++++++++++
server/dock/src/validation.h | 134 +++++
server/dock/tests/test-auth.c | 90 +++
server/dock/tests/test-client_layout.c | 39 ++
server/dock/tests/test-probe.c | 108 ++++
server/dock/tests/test-validation.c | 224 +++++++
server/dock/tools/check-client-layout.py | 84 +++
server/tests/check.sh | 4 +
40 files changed, 5198 insertions(+), 17 deletions(-)
create mode 100644 server/dock/COPYING
create mode 100644 server/dock/LICENSE
create mode 100644 server/dock/LICENSE-EXCEPTION.md
create mode 100644 server/dock/MAINTAINING.md
create mode 100644 server/dock/README.upstream.md
create mode 100644 server/dock/THIRD-PARTY-NOTICES.md
create mode 100644 server/dock/build.sh
create mode 100644 server/dock/check.sh
create mode 100644 server/dock/docs/CLIENT_LAYOUTS.md
create mode 100644 server/dock/docs/OFFLINE.md
create mode 100644 server/dock/notices/LLVM.txt
create mode 100644 server/dock/notices/MinGW-w64-runtime.txt
create mode 100644 server/dock/src/auth.c
create mode 100644 server/dock/src/auth.h
create mode 100644 server/dock/src/client_layout.c
create mode 100644 server/dock/src/client_layout.h
create mode 100644 server/dock/src/hold.c
create mode 100644 server/dock/src/hold.h
create mode 100644 server/dock/src/launch.c
create mode 100644 server/dock/src/launch.h
create mode 100644 server/dock/src/main.c
create mode 100644 server/dock/src/probe.c
create mode 100644 server/dock/src/probe.h
create mode 100644 server/dock/src/scm.c
create mode 100644 server/dock/src/scm.h
create mode 100644 server/dock/src/session.c
create mode 100644 server/dock/src/session.h
create mode 100644 server/dock/src/validation.c
create mode 100644 server/dock/src/validation.h
create mode 100644 server/dock/tests/test-auth.c
create mode 100644 server/dock/tests/test-client_layout.c
create mode 100644 server/dock/tests/test-probe.c
create mode 100644 server/dock/tests/test-validation.c
create mode 100644 server/dock/tools/check-client-layout.py
diff --git a/.github/workflows/dedicated-server.yml b/.github/workflows/dedicated-server.yml
index a7896988..f1d03bfc 100644
--- a/.github/workflows/dedicated-server.yml
+++ b/.github/workflows/dedicated-server.yml
@@ -1,4 +1,4 @@
-# The Linux dedicated server (server/): static checks, the package, the Docker image built and smoke-tested.
+# The dedicated server in Docker (server/, docs/DOCKER-SERVER.md): static checks (shell, Python, Dock's unit tests, Compose, no secrets), the package, the image built (Dock built from server/dock/, with its tests) and smoke-tested.
#
# The image always carries the LATEST OFFICIAL MPFever release: the package is built from that release's tag (build.bat) with the launcher
# changes of this branch applied on top (they disappear from the patch once a release contains them). So players on the official release can join.
diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index 36b1a9b5..faf6ec94 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -3,7 +3,8 @@ MPFever - Changelog
0.9.2 - (in progress)
- NEW (experimental, server/, docs/DOCKER-SERVER.md): a dedicated server in one Linux Docker container (any x86-64 Docker host): the Windows game under Wine, started through
- Madeira Dock (Valve's own client library: real sign-in and licence check, no Steam desktop, about 280 MB), software Vulkan with a layer that makes drawing a
+ Madeira Dock (Valve's own client library: real sign-in and licence check, no Steam desktop, about 280 MB; its sources are in server/dock/,
+ unmodified at the import and maintained by this project: server/dock/MAINTAINING.md), software Vulkan with a layer that makes drawing a
no-op, a "lite" game install (66 GB become about 1 GB), no GPU. Players join it like any dedicated server. The launcher gets a Linux/Wine start mode
(MPFEVER_WINE=1, MPFEVER_DOCK) and a stop file (MPFEVER_STOPFILE: the world is saved, then the server stops, as the console's "stop"); nothing changes on
Windows. The image (ghcr.io/ampynjord/mpfever-server, tagged with the MPFever version and "experimental") holds no game or Valve file; install-game,
diff --git a/docs/DOCKER-SERVER.md b/docs/DOCKER-SERVER.md
index f87f30a4..be4493bc 100644
--- a/docs/DOCKER-SERVER.md
+++ b/docs/DOCKER-SERVER.md
@@ -89,7 +89,7 @@ rebuilt at any time with `install-game`). Back up `mpfever-data`.
|---|---|---|
| Game | `TransportFever3.exe` under Wine 11 (pinned package) on Ubuntu 24.04 | A native Linux game drifts from Windows clients (different C++ library, `std::` distributions inlined in the game): the same executable keeps the same simulation. No Proton, no DXVK: rendering is a no-op. |
| Launcher | `MPFever.exe --server --server-start headless` under Mono, with a Linux/Wine mode (`GameInstall.WineMode`, `MPFEVER_WINE=1`; `MPFEVER_STOPFILE` for a clean stop) | The same host logic, `winhttp.dll` module and mod as the players'. |
-| Steam | [Madeira Dock](https://github.com/willfaust/madeira-dock) (`dockhost.exe`, built from source at a pinned commit) driving **Valve's own `steamclient64.dll`** | The game requires a running Valve client. Dock signs in with the owner's refresh token, asks Valve's client for the licence and has it start the game: no `steam.exe`, no web helper (about 280 MB instead of 2.7 GB). No Steamworks emulation, no DRM bypass: every decision is Valve's. |
+| Steam | Madeira Dock (`dockhost.exe`, built in the image from our copy in `server/dock/`, which we maintain; origin [willfaust/madeira-dock](https://github.com/willfaust/madeira-dock)) driving **Valve's own `steamclient64.dll`** | The game requires a running Valve client. Dock signs in with the owner's refresh token, asks Valve's client for the licence and has it start the game: no `steam.exe`, no web helper (about 280 MB instead of 2.7 GB). No Steamworks emulation, no DRM bypass: every decision is Valve's. |
| Rendering | Lavapipe (software Vulkan) and the layer `server/vklayer/` (`MPF_VKNULL=1`, `MPF_VKNULL_MODE=all`, `MPF_VKNULL_TRIM=1`), `MPFEVER_HEADLESS_NORENDER=1;MPFEVER_HEADLESS_FPS=10` | Draws, copies and render passes become no-ops; mapped GPU memory nobody reads is given back. A real GPU is used if the layer is off (`compose.gpu.yaml`, not validated). |
| Disk | the "lite" install (`server/scripts/mklite.py`) | The engine reads archives at fixed offsets, so archives keep their layout: textures, audio and blobs become file holes (sparse), images stay valid but empty. Generated from the host's own copy, never distributed. |
| Display | `Xvfb` only | The game closes without an X server. Nothing is exposed: no VNC, no remote desktop. |
@@ -114,11 +114,11 @@ other (result 30, before any sign-in). The image pins the January 2026 build:
|---|---|
| `steamclient64.dll` | 25 546 904 bytes, SHA-256 `71b391fe9f3e2006cbc81a5c75eef3eb4186012deabfdb2c8b7e8d4850ecf640` |
| Package fetched from Valve | `https://client-update.akamai.steamstatic.com/bins_win32.zip.23e34a6d4b10596a44561a5100dac5585d2517da`, SHA-256 `8b712b2a3412a9066b7725f4e1c5cef9a7ca5b187b6585a5b92d25d09df0ba62` (checked before use) |
-| Madeira Dock | github.com/willfaust/madeira-dock, commit `67780ba92e60dbfac4fe80eaf2ce34b9ea1a1c60` (GPL-3.0-or-later) |
+| Madeira Dock | `server/dock/`, imported unmodified from github.com/willfaust/madeira-dock commit `67780ba92e60dbfac4fe80eaf2ce34b9ea1a1c60` (GPL-3.0-or-later), maintained here; unit-tested and built in the image build |
Dock never starts `steam.exe`, so the pinned client is never updated by Steam. Valve could remove that archive or change its authentication protocol: the server then stops with an explicit message
-(hash mismatch, download failure, or Dock's refusal in `srv/dock.log`). There is no second Steam implementation: the remedy is a new Dock revision with a verified layout and a new pinned hash
-(`server/scripts/lib.sh`, `server/Dockerfile`). Dock is a young third-party project, not endorsed by Valve; overlay, cloud saves and achievements are not supported (the server does not use them).
+(hash mismatch, download failure, or Dock's refusal in `srv/dock.log`). There is no second Steam implementation: the remedy is to add the new client build to our copy of Dock's layout table and to change the pin
+(`server/dock/MAINTAINING.md` lists the steps; the pin is in `server/scripts/lib.sh`). Dock is not endorsed by Valve; overlay, cloud saves and achievements are not supported (the server does not use them).
One Steam account plays one game at a time: playing on it elsewhere while the server runs can interrupt it (a few minutes of both was tolerated, no guarantee): use a dedicated account.
## Update, roll back, security
@@ -127,7 +127,7 @@ One Steam account plays one game at a time: playing on it elsewhere while the se
Players must run the MPFever client of the server's version.
- The container runs as uid 1001 with a read-only root file system, all capabilities dropped, `no-new-privileges`, only the game port published. `.env` holds the server password: keep it out of version control.
- Exit codes: 20/21 Valve client download or hash, 30 game missing, 40/41 Steam session missing or expired, 42 savegame missing, 50 launcher failing repeatedly. Reports: `docker compose logs`, `srv/launcher.out`,
- `srv/logs/`, and Dock's `srv/dock.log` (stage names and numbers only; result codes in madeira-dock's README).
+ `srv/logs/`, and Dock's `srv/dock.log` (stage names and numbers only; result codes in `server/dock/README.upstream.md`).
## Measured
@@ -152,7 +152,7 @@ stopping while a client has vanished, the GPU variant.
## Build and tests
-`.github/workflows/dedicated-server.yml` runs the static checks (`server/tests/check.sh`: shell, Python tests, Compose, no secrets or binaries), builds the package from the latest official release with the
-Linux server's launcher changes, builds the image, smoke-tests it (unprivileged, no game or Valve file inside, explicit errors on empty volumes) and publishes only when a tag
+`.github/workflows/dedicated-server.yml` runs the static checks (`server/tests/check.sh`: shell, Python tests, Compose, no secrets or binaries), runs Dock's unit tests, builds the package from the latest official release with the
+Docker server's launcher changes, builds the image, smoke-tests it (unprivileged, no game or Valve file inside, explicit errors on empty volumes) and publishes only when a tag
`dedicated-server-v` is pushed or the workflow is run by hand with "publish" ticked. Locally: put a package built by `build.bat` in `server/dist/MPFever-server.zip` and
`docker compose -f compose.yaml -f compose.build.yaml build` (`APT_MIRROR` can name another Ubuntu mirror).
diff --git a/server/.dockerignore b/server/.dockerignore
index b596f0ac..1d6e451c 100644
--- a/server/.dockerignore
+++ b/server/.dockerignore
@@ -3,4 +3,5 @@
!scripts/
!config/
!vklayer/
+!dock/
!dist/
diff --git a/server/Dockerfile b/server/Dockerfile
index 269fae56..bdc63358 100644
--- a/server/Dockerfile
+++ b/server/Dockerfile
@@ -10,17 +10,14 @@
ARG UBUNTU=ubuntu:24.04
-# ---------------------------------------------------------------- Madeira Dock, from source at a pinned commit (GPL-3.0-or-later)
+# ---------------------------------------------------------------- Madeira Dock, from this repository's copy (dock/, GPL-3.0-or-later): unit tests, then the build
FROM ${UBUNTU} AS dock
ARG APT_MIRROR=
RUN if [ -n "$APT_MIRROR" ]; then sed -i "s#http://archive.ubuntu.com/ubuntu#$APT_MIRROR#g; s#http://security.ubuntu.com/ubuntu#$APT_MIRROR#g" /etc/apt/sources.list.d/ubuntu.sources; fi
-ARG DOCK_REPO=https://github.com/willfaust/madeira-dock.git
-ARG DOCK_REF=67780ba92e60dbfac4fe80eaf2ce34b9ea1a1c60
-RUN apt-get update -qq && apt-get install -y -qq --no-install-recommends ca-certificates git gcc-mingw-w64-x86-64 >/dev/null \
- && git clone -q "$DOCK_REPO" /src && git -C /src checkout -q "$DOCK_REF" && test "$(git -C /src rev-parse HEAD)" = "$DOCK_REF"
+RUN apt-get update -qq && apt-get install -y -qq --no-install-recommends gcc libc6-dev gcc-mingw-w64-x86-64 >/dev/null
+COPY dock/ /src/
WORKDIR /src
-RUN x86_64-w64-mingw32-gcc -std=c11 -O2 -Wall -Wno-cast-function-type -static -s -o /dockhost.exe \
- src/main.c src/probe.c src/session.c src/launch.c src/validation.c src/auth.c src/client_layout.c src/scm.c src/hold.c -ladvapi32 -luser32
+RUN bash check.sh && bash build.sh /dockhost.exe
# ---------------------------------------------------------------- the Vulkan layer that makes drawing a no-op
FROM ${UBUNTU} AS vklayer
@@ -60,7 +57,7 @@ RUN python3 -m zipfile -e /tmp/mpfever-server.zip /tmp/pkg && mkdir -p /opt/mpfe
&& rm -rf /tmp/pkg /tmp/mpfever-server.zip
COPY --from=dock /dockhost.exe /opt/mpfever/dockhost.exe
-COPY --from=dock /src/LICENSE /src/COPYING /src/LICENSE-EXCEPTION.md /opt/mpfever/licenses/madeira-dock/
+COPY --from=dock /src/LICENSE /src/COPYING /src/LICENSE-EXCEPTION.md /src/THIRD-PARTY-NOTICES.md /src/notices /opt/mpfever/licenses/madeira-dock/
COPY --from=vklayer /libVkLayer_mpf_nulldraw.so /opt/mpfever/libVkLayer_mpf_nulldraw.so
COPY vklayer/VkLayer_mpf_nulldraw.json /etc/vulkan/implicit_layer.d/VkLayer_mpf_nulldraw.json
COPY scripts/ /opt/mpfever/scripts/
diff --git a/server/dock/COPYING b/server/dock/COPYING
new file mode 100644
index 00000000..2a000655
--- /dev/null
+++ b/server/dock/COPYING
@@ -0,0 +1,674 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc.
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+ Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+ For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+ Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+ Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Use with the GNU Affero General Public License.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+
+ Copyright (C)
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+ Copyright (C)
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+.
+
+ The GNU General Public License does not permit incorporating your program
+into proprietary programs. If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License. But first, please read
+.
diff --git a/server/dock/LICENSE b/server/dock/LICENSE
new file mode 100644
index 00000000..0be5f48f
--- /dev/null
+++ b/server/dock/LICENSE
@@ -0,0 +1,27 @@
+Madeira Dock
+Copyright 2026 125hz
+
+SPDX-License-Identifier: GPL-3.0-or-later
+Licensed GPL-3.0-or-later with the Madeira Converter Exception.
+
+Madeira Dock is free software: you can redistribute it and/or modify it under
+the terms of the GNU General Public License as published by the Free Software
+Foundation, either version 3 of the License, or (at your option) any later
+version. See COPYING for the full licence text.
+
+Additional permission under GNU GPL version 3 section 7: 125hz, the copyright
+holder of Madeira Dock, grants for Madeira Dock the additional permission in
+the section "Madeira Converter Exception, version 1" of LICENSE-EXCEPTION.md.
+That file is reproduced unmodified from the Madeira application; its adoption
+line and "Scope and authority" section describe the Madeira repository and are
+kept for reference. This grant, by the Dock copyright holder, is what attaches
+the same permission to Madeira Dock's code, effective 2026-09-27.
+
+Madeira Dock is distributed in the hope that it will be useful, but WITHOUT ANY
+WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
+PARTICULAR PURPOSE. See the GNU General Public License for more details.
+
+No rights to Valve software, Steam, game content or trademarks are granted.
+Valve's client components and games are obtained separately under Valve's and
+their publishers' terms and are not part of this repository or its releases.
+Third-party notices: THIRD-PARTY-NOTICES.md and notices/.
diff --git a/server/dock/LICENSE-EXCEPTION.md b/server/dock/LICENSE-EXCEPTION.md
new file mode 100644
index 00000000..5eac352c
--- /dev/null
+++ b/server/dock/LICENSE-EXCEPTION.md
@@ -0,0 +1,71 @@
+# Additional permission for the Apple Metal Shader Converter (GPL-3.0 section 7)
+
+Prepared 2026-09-16 for review. NOT IN EFFECT until the copyright
+holder completes the adoption line below. Distribution begins with the first
+push to a public remote, not with a release tag, so the line must be
+completed BEFORE any public push (the repository's `.githooks/pre-push`
+refuses a remote push while this file is a draft; enable it with
+`git config core.hooksPath .githooks`). Every copy of this text in the
+forks and the runtime follows this adoption. See "Scope and authority" for
+what it can and cannot cover.
+
+Adopted on: 2026-09-24
+By: Will Faust
+
+Madeira is licensed under the GNU General Public License, version 3 or (at
+your option) any later version (see `COPYING`). The following additional
+permission applies to the parts of Madeira whose copyright is held by the
+Madeira authors (see "Scope and authority"):
+
+### Madeira Converter Exception, version 1 (of 2026-09-16; in effect from the adoption date above)
+
+Additional permission under GNU GPL version 3 section 7.
+
+If you modify this Program, or any covered work, by linking or combining it
+with the Apple Metal Shader Converter dynamic library
+(libmetalirconverter.dylib, in any version) or with Apple's Metal,
+Foundation, CoreGraphics, QuartzCore, UIKit, AppKit and related system
+frameworks, or with modified versions of those libraries, the licensors of
+this Program grant you additional permission to convey the resulting work.
+Corresponding Source for a non-source form of such a combination shall
+include the source code for the parts of the Program used in the
+combination, but need not include the source code of those Apple libraries.
+This permission does not extend to those libraries, which remain subject to
+Apple's own licence terms. You may remove this additional permission from
+copies you convey, as GPL-3.0 section 7 allows.
+
+## Scope and authority
+
+An additional permission can be attached only by the copyright holder of
+the code it covers. It therefore covers, and only covers:
+
+- the Madeira application and tooling in this repository (all commits are
+ by the Madeira author; contributions are accepted under `CONTRIBUTING.md`,
+ which from this date includes this permission);
+- the native Direct3D 12 runtime in `research/madeira-d3d12` (same author;
+ its own `LICENSE` file carries the same text);
+- the Madeira-authored modifications in the FEX and DXMT forks and in the
+ rpmalloc fork under FEX/External (commits by Will Faust), whose
+ `LICENSE-MADEIRA.md` files reproduce this permission in full. Upstream
+ FEX and DXMT code is MIT and upstream rpmalloc is 0BSD; Ryan Houdek's
+ rpmalloc commits are 0BSD; none needs an exception.
+
+It does NOT cover, and nothing here changes:
+
+- upstream Wine code. The Wine fork was relicensed from LGPL-2.1-or-later
+ to GPL-3.0-or-later under LGPL section 3, which is irreversible for that
+ copy and makes the Wine authors' code GPL-only in that tree; no exception
+ can be attached to it by anyone but them. The path being prepared is an
+ LGPL branch built from the upstream wine-11.4 baseline with the
+ Madeira-authored patches reapplied under LGPL-2.1-or-later, documented in
+ `docs/wine-lgpl-provenance.md`;
+- the Apple libraries themselves. The converter library is tracked in this
+ repository (whether that co-location, or the built app, forms a combined
+ work with the GPL code is a question for the legal review, not settled by
+ this file) and it is distributed only under Apple's agreement
+ (`app/Madeira/d3d12/METAL-SHADER-CONVERTER-AGREEMENT.txt`, section 2.B:
+ distribution "for the sole purpose of shader conversion").
+
+This file is a licensing statement by the copyright holder, not legal
+advice; the assembled application must be reviewed before public release
+(see `docs/LICENSING.md`).
diff --git a/server/dock/MAINTAINING.md b/server/dock/MAINTAINING.md
new file mode 100644
index 00000000..d729ba32
--- /dev/null
+++ b/server/dock/MAINTAINING.md
@@ -0,0 +1,46 @@
+# Madeira Dock in MPFever: our copy and how we maintain it
+
+`dockhost.exe` is a small Windows program (about 2,000 lines of C) that loads **Valve's own, unmodified `steamclient64.dll`**, signs in with the account owner's refresh
+token, asks Valve's client whether the account owns the game and has Valve's client start it. It is what lets the dedicated server run without Steam's desktop client.
+It contains no Steamworks implementation, no ticket or licence logic of its own, and no DRM bypass: every decision (valid sign-in, ownership, permission to start) is Valve's;
+Dock has no path that starts the game when Valve says no (see `README.upstream.md`, "What it does not do").
+
+## Origin and licence
+
+Imported unmodified from [willfaust/madeira-dock](https://github.com/willfaust/madeira-dock), commit `67780ba92e60dbfac4fe80eaf2ce34b9ea1a1c60` (2026-10-28),
+Copyright 2026 125hz, GPL-3.0-or-later with the Madeira Converter Exception (`LICENSE`, `COPYING`, `LICENSE-EXCEPTION.md`). MPFever is GPL-3.0, so the code can live here;
+the licence files, `THIRD-PARTY-NOTICES.md` and `notices/` stay with it, and the image carries them in `/opt/mpfever/licenses/madeira-dock/`.
+Not included: the author's Madeira app, its Swift/iOS parts, his agent notes and development history (`docs/HISTORY.md`, `docs/HANDOFF.md`). This copy is maintained here from now on;
+changes made after the import are listed at the end of this file (none yet).
+
+## What is here
+
+| | |
+|---|---|
+| `src/` | the program (`main.c`, `session.c` sign-in and licence, `launch.c`, `auth.c` the transfer file, `client_layout.c` the supported client builds, `scm.c`, `hold.c`, ...) |
+| `tests/`, `check.sh` | unit tests of the pure logic (synthetic data, no Steam): `bash server/dock/check.sh` |
+| `build.sh` | the build the image uses (MinGW-w64, static, `-Wall -Wextra -Werror`): `bash server/dock/build.sh` |
+| `tools/check-client-layout.py` | checks a `steamclient64.dll` against the layout table without running it |
+| `docs/CLIENT_LAYOUTS.md`, `docs/OFFLINE.md` | where each supported client build came from and how its methods were identified; offline logon |
+| `README.upstream.md` | the author's README (variables, result codes, credentials) |
+
+The server drives Dock through environment variables set by `server/scripts/entrypoint.sh` and by the launcher (`MPFEVER_DOCK`, see `launcher/Core.cs`).
+
+## The one thing to maintain: the supported Valve client builds
+
+Dock calls **private interfaces** of Valve's client by position in its method tables, so `src/client_layout.c` lists the exact `steamclient64.dll` builds it may drive (by SHA-256) with the address of every
+method it calls; any other build is refused (result 30) before any sign-in. The image pins one build (`CLIENT_*` in `server/scripts/lib.sh`: January 2026, SHA-256 `71b391fe...`). When
+Valve ships a client that breaks it, or removes the pinned archive:
+
+1. Get the new client package from Valve's update server (`https://client-update.akamai.steamstatic.com/steam_client_win32` names the current package; the archive is `bins_win32.zip.` on the same host)
+ and extract `steamclient64.dll`. Check Valve's signature (Windows Authenticode: signer Valve Corp).
+2. `python tools/check-client-layout.py ` identifies the vtables (RTTI) and the 14 called methods; compare with the table (`docs/CLIENT_LAYOUTS.md` explains the method).
+3. Add the build to `src/client_layout.c` (its SHA-256, PE timestamp and method addresses) and a case to `tests/test-client_layout.c` (the known build is accepted, a changed byte is rejected).
+4. `bash server/dock/check.sh`, then a real test: `docker compose run ... login`, a start, `launch-game-running=1` in `srv/dock.log`, a client joining.
+5. Update the pin (`CLIENT_URL`, `CLIENT_ZIP_SHA256`, `CLIENT_DLL_SHA256` in `server/scripts/lib.sh`) and the table in `docs/DOCKER-SERVER.md`, add the entry below, publish a new image.
+
+Never loosen Dock's checks (the launch callback must stay strictly checked: id, size, game id, success). Never add a path that starts the game without Valve's answer.
+
+## Changes since the import
+
+None.
diff --git a/server/dock/README.upstream.md b/server/dock/README.upstream.md
new file mode 100644
index 00000000..b85df65c
--- /dev/null
+++ b/server/dock/README.upstream.md
@@ -0,0 +1,350 @@
+# Madeira Dock
+
+Madeira Dock is a small headless host for **Valve's own Steam client**. It lets
+[Madeira](https://github.com/willfaust/Madeira) (Windows games on iPhone and iPad, through Wine)
+start a game the signed-in user owns, with Steam's real sign-in, Steam's real licence check and the
+game's original DRM, without running Steam's desktop interface.
+
+It is one Windows program, `dockhost.exe`, about 2,000 lines of C.
+
+**Licence:** GPL-3.0-or-later with the Madeira Converter Exception, Copyright 2026 125hz
+(`LICENSE`, `COPYING`, `LICENSE-EXCEPTION.md`). Not affiliated with or endorsed by Valve.
+
+## In one paragraph
+
+On a PC, `steam.exe` loads Valve's client library (`steamclient64.dll`), signs in, checks the
+account's licences and starts games; a second set of processes draws the window and the store.
+Dock does the first half only. It loads the same unmodified Valve library, hands it the user's
+own Steam sign-in, asks it whether the account owns the game, and asks it to start the game with
+Valve's own launch function. Every decision (is this sign-in valid, does this account own this
+game, may it start now) is made by Valve's library talking to Valve's servers. Dock has no code
+that answers any of those questions itself, and no path that starts a game when Valve's answer is
+no.
+
+## Why it exists
+
+Steam's desktop interface (the client window and its Chromium web helper) needs more memory than
+a phone can spare next to a running game. The part of Steam a game actually needs while it runs is
+the client library: it confirms the licence, serves the Steamworks API the game calls, and
+handles the DRM wrapper or per-user executable the game ships with. Dock hosts that part and
+nothing else.
+
+## What it does, in order
+
+1. **Refuses to run beside another Steam.** If `steam.exe`, `steamwebhelper.exe` or another host
+ is running, or another Dock holds its mutex, it stops (`main.c`, `no_other_client`).
+2. **Identifies Valve's client file.** It opens `steamclient64.dll` in the Steam folder with
+ writes and deletes denied, checks it is a 64-bit DLL and computes its SHA-256. Only builds
+ whose hash is in `src/client_layout.c` are driven; any other build stops here with result 30
+ (see "Supported client builds").
+3. **Loads it as Windows would for Steam.** `LoadLibraryExW` from the Steam folder with the
+ search path limited to that folder and `system32`. Nothing is patched, hooked or replaced.
+4. **Creates a Steam user and pipe** with the library's exported functions
+ (`Steam_CreateGlobalUser`, `Steam_BGetCallback`, ...), and obtains the client engine with
+ `CreateInterface`.
+5. **Signs in with the user's own sign-in.** Madeira's sign-in screen (QR code, or password with
+ Steam Guard) is answered by Steam's own authentication service; the resulting token is kept in
+ the iOS Keychain. For a launch, Madeira passes it to Dock once (see "Credentials"), and Dock
+ gives it to the client's own `SetLoginToken` and calls the client's own `LogOn`. Valve's
+ servers accept or reject it.
+6. **Waits until Valve's client says it is signed in and online** (`Steam_BLoggedOn`,
+ `BLoggedOn` and `BConnected` must all hold). With no network (`MADEIRA_DOCK_OFFLINE=1`), or
+ when the connection fails and the client allows it, Dock instead asks the client for its own
+ offline logon (`CanLogonOffline`, `LogOnOffline`; `docs/OFFLINE.md`); the steps below are the
+ same, answered by the client from its own cache.
+7. **Asks Valve's client whether the account owns the game.** The requested App ID must be in
+ the client's own list of the account's subscribed apps (`GetSubscribedApps`). If it is not
+ there within 90 seconds, Dock stops with result 34 or 35 and nothing is started.
+8. **Checks it is the game the user asked for.** The install folder Valve's client resolves for
+ the App ID must equal the folder Madeira expects.
+9. **If the game ships per-user executables (CEG),** asks the client to prepare them
+ (`RequestCustomBinaries`), as desktop Steam does before a launch. Valve's client requests
+ them from Valve with this account's licence. A failure stops the launch (result 49).
+10. **Announces itself as the running Steam client**, the way `steam.exe` does: its process id
+ and the signed-in account id in Steam's `ActiveProcess` registry values. Games find the
+ client through these. The previous values are restored on exit.
+11. **Asks Valve's client to start the game**: `IClientAppManager::LaunchApp` with the original
+ launch entry key selected by Madeira, including nonzero and sparse keys. Valve's client
+ applies its own launch checks and returns its own result; a
+ refusal (for example "no licence", "another session is playing", "update required") is
+ reported as Valve gave it, and the game is not started.
+12. **Stays up while the game runs**, pumping the client's callbacks, so the game's
+ `steam_api64.dll` talks to a live, signed-in client exactly as it would on a PC. The game,
+ its Steamworks calls and its DRM (SteamStub wrapper, CEG, the game's own checks) run
+ unmodified.
+13. **Holds the session while the game's own programs are still starting or showing something.**
+ Valve's client stops reporting the game as running when the program it started exits, which
+ some games' launchers do while they restart themselves or before they start the game. Dock
+ follows the game's process tree while it runs (`src/hold.c`: the host's descendants, Windows'
+ own images and their children excepted, plus any image named in `MADEIRA_DOCK_KEEP_ALIVE`),
+ only looking: process snapshots, image paths, start times and visible windows. After the
+ report ends, the session is held while a member still shows a window or is younger than 60 s
+ (`launch-keep-alive`, then `launch-keep-alive-held=` at the end); a launcher left in
+ the background after the game ends holds nothing. `MADEIRA_DOCK_KEEP_ALIVE=0` ends the
+ session 3 s after the report as before.
+14. **Shuts the client down** when the game has ended, with the public `SteamClient021` shutdown
+ call, releases the user and pipe, and exits with a numeric result.
+
+## What it does not do
+
+- **No emulation.** There is no replacement `steam_api`, `steamclient` or Steamworks
+ implementation here. The game loads Valve's files.
+- **No DRM removal or bypass.** Dock does not unwrap, patch or modify any executable, does not
+ create or alter CEG binaries, and does not forge tickets, licences or ownership.
+- **No start without Valve's yes.** Dock keeps no cached "owned" flag and has no fallback of its
+ own: a failed sign-in, a missing licence or a refused launch ends the run. An offline start is
+ Valve's client's own offline logon (`docs/OFFLINE.md`), which the client allows only with the
+ offline logon ticket Steam issued to it during an earlier online logon; it then answers the
+ licence question from its own cache, as desktop Steam's Offline Mode does.
+- **No game installs.** Dock starts games that are already installed in the user's prefix with
+ their Steam app manifest. Dock itself downloads nothing; Valve's client may update a game's
+ content before starting it, as it does on a PC.
+- **No Valve files in this repository or in Madeira's app bundle.** Madeira downloads Valve's
+ client packages from Valve's own update servers on the user's device and verifies them against
+ pinned sizes and SHA-256 sums.
+- **No game-specific code.** There are no game names, App IDs or per-game fixes in the source.
+- **No account data in logs.** The report contains stage names and numbers only: no token,
+ account name, SteamID, path, App ID list or callback payload.
+- **No interaction with anti-cheat.** Dock has no code that touches VAC or any third-party
+ anti-cheat.
+
+## What decides whether a game starts
+
+| Question | Who answers | How Dock asks |
+|---|---|---|
+| Is this sign-in valid? | Valve's servers, through Valve's client | `SetLoginToken`, `LogOn`, then `BLoggedOn` and `BConnected` |
+| Offline: may this account sign in without a connection? | Valve's client, from the offline logon ticket Steam issued to it | `CanLogonOffline`, then `LogOnOffline` (`docs/OFFLINE.md`) |
+| Does this account own the game? | Valve's client, from the account's licences | `GetSubscribedApps` (and `BIsSubscribedApp`, reported but never sufficient alone) |
+| May it start now? | Valve's client | `LaunchApp` and its asynchronous result |
+| Is the copy genuine and licensed to this user? | The game's own DRM, against the running client | not asked by Dock: it happens between the game and Valve's client |
+
+Dock's own checks are all additional refusals (wrong client build, wrong install folder,
+malformed sign-in transfer, another Steam already running). None of them can turn a "no" from
+Valve into a start.
+
+## Credentials
+
+- Dock never sees a password. Madeira's sign-in produces a Steam refresh token for the user's
+ own account; Madeira keeps it in the iOS Keychain.
+- For one launch, Madeira writes a **one-use transfer file** in its protected app storage and
+ passes only the file's path to Dock (`MADEIRA_DOCK_AUTH_FILE`). The token is never put on a
+ command line or in an environment variable.
+- Dock opens the file exclusively with delete-on-close, so it is gone before sign-in starts;
+ refuses directories, links and anything outside the size bounds; parses it; hands the token to
+ the client's `SetLoginToken`; and overwrites its own copies. Madeira also deletes any
+ unconsumed file after a failed launch, at sign-out and at the next app start.
+- The transfer names one App ID. A transfer for another App ID is rejected (result 37).
+- A missing, locked or malformed transfer fails the run. It never falls back to another login.
+- Format `MDOCK001`: 8 magic bytes; little-endian u64 SteamID, u32 App ID, u16 account length,
+ u16 token length; then the account name (1 to 64 bytes) and the token (1 to 8192 bytes); no
+ trailing data. It carries a credential, never a claim of ownership.
+- Valve's client may keep its own session cache inside the user's Wine prefix, as it does on a
+ PC. Dock does not read or write it.
+
+There is also a developer mode for testing on a Windows PC that asks an installed client to sign
+in with **its own** cached account (`MADEIRA_STEAM_HOST_ACCOUNT`, `_STEAMID`, `_APPID`). Dock
+passes the account name to the client and never reads the client's credential files. Madeira
+always clears these variables; the app only uses the transfer file.
+
+## Supported client builds
+
+The functions Dock calls for sign-in, licence and launch are **not a public Valve SDK**. They are
+internal interfaces of the client library (`IClientEngine`, `IClientUser`, `IClientAppManager`),
+called by their position in the library's own method tables. That is fragile, so Dock is strict:
+
+- It drives only client builds listed in `src/client_layout.c`, identified by the SHA-256 of
+ `steamclient64.dll`. Two builds are listed (revisions 202601 and 202609).
+- Before each internal call it checks that the method table entry is exactly the address
+ recorded for that build. A mismatch stops the run.
+- An unknown build **fails closed** with result 30 before any sign-in. Dock never guesses a
+ layout.
+
+`docs/CLIENT_LAYOUTS.md` records where each build came from (Valve's update servers, with the
+manifest and archive hashes), that its Authenticode signature is Valve's, and how each method
+was identified. `tools/check-client-layout.py` re-checks a client file against the table.
+
+Only the shutdown call uses a public interface (`SteamClient021`, slot 23), checked against
+Valve's public Steamworks header.
+
+## Services
+
+Valve's client prepares CEG executables through its own Windows service. A Dock session starts
+only this host, so Wine's service manager may not be running yet. `src/scm.c`:
+
+- starts Wine's standard `services.exe` if no service manager answers, and ends it again at exit
+ if Dock started it;
+- checks, read-only, that Valve's client service is registered; if it is not, runs Valve's own
+ `bin\SteamService.exe /install`, which is what Valve's client does when it finds the service
+ missing.
+
+Dock itself never creates, registers, configures or starts a service. At exit it stops Valve's
+client service through the service manager, so that nothing outlives the session.
+
+`dockhost.exe --start-services` is a separate mode used before a game's one-time installers
+(runtime setups from the game's Steam install script). It loads no Steam client: it only makes
+Wine's service manager reachable, prints one line and exits.
+
+A game session gets the same bounded start before the launch when the game needs it
+(`src/launch.c`, `src/scm.c`): some launchers install an automatic-start Windows service of their
+own, and without a service manager every start of it fails (RPC error 1722). With
+`MADEIRA_DOCK_GAME_SCM` unset, Dock counts, read-only, the Win32 services registered in the prefix
+with automatic or on-demand start whose image lies outside the Windows folder (`game-scm-services`;
+Wine's own services never count) and starts the manager only when there is at least one; `1`
+always starts it and `0`
+never does. The step waits at most 20 s (`game-scm=<2 started, 1 already running, 0 off, -1
+failed>` or `game-scm-timeout=1`) and never decides whether the game launches. The manager it
+starts stays for the session, as after `--start-services`.
+
+## Limits
+
+- **Windows program, 64-bit session.** The 32-bit build supports only the bootstrap test.
+- **Launch entries from Steam's configuration.** Bounded user arguments are passed to the selected entry.
+- **One Steam session.** While Dock runs it is the account's Steam client; Madeira closes its own
+ Steam connection first, because a second sign-in of the same account would replace this one.
+- **Not crash-safe.** If the host is killed, the `ActiveProcess` values it wrote are not
+ restored until the next run or the next real Steam start.
+- **Not everything is validated.** Sign-in, the licence check and game starts have been run on
+ Windows and on devices; CEG preparation has had less testing. Overlay, cloud saves,
+ achievements, multiplayer, family sharing, revoked or refunded licences and connection loss
+ during play have not been tested systematically. Setting up Steam's overlay is known to fail
+ under Dock; nothing is patched to hide that.
+- **A client update needs a new verified layout.** Until then Dock refuses the new build.
+
+## Extra launch arguments
+
+`MADEIRA_STEAM_HOST_ARGUMENTS` adds bounded UTF-8 arguments to Valve's own
+`LaunchApp` user-arguments parameter. It is supplied on the first request and
+on retries alongside the selected original Steam launch entry key. It never
+enters the installer command and only its byte count is logged. Unbalanced
+quotes, control characters, more than 64 tokens or 4095 bytes fail closed;
+missing input preserves Valve's normal arguments. The app exports the value
+from the selected library profile before starting this host. The client still
+checks authentication, subscription and the original game DRM.
+
+## Running it
+
+Dock is started by Madeira, not by hand. Everything is passed in the environment, and every stage
+is opt-in: with no variables set, `dockhost.exe` does nothing and exits with 2.
+
+| Variable | Meaning |
+|---|---|
+| `MADEIRA_STEAM_HOST_PROBE=1` | Master switch. Without it nothing is loaded. |
+| `MADEIRA_STEAM_HOST_SESSION=1` | Use the verified internal interfaces (needs a supported build). |
+| `MADEIRA_STEAM_HOST_LOGIN=1` | Sign in. |
+| `MADEIRA_STEAM_HOST_LAUNCH=1` | Start the game after sign-in and the licence check. |
+| `MADEIRA_STEAM_HOST_BOOTSTRAP=1` | Without `SESSION`: load the client, create and release a user, for five seconds. No sign-in. |
+| `MADEIRA_DOCK_AUTH_FILE` | Path of the one-use sign-in transfer. |
+| `MADEIRA_STEAM_HOST_APPID` | The game to start. |
+| `MADEIRA_STEAM_HOST_LAUNCH_OPTION` | Original numeric `config.launch` key, from 0 to 2147483647. Absent means 0 for older launchers; malformed input fails closed. |
+| `MADEIRA_STEAM_HOST_EXPECTED_INSTALL` | The install folder the client must resolve for it. |
+| `MADEIRA_STEAM_HOST_CLIENT_DIR` | Steam folder (default: the registry's `SteamPath`). Must be an absolute local path. |
+| `MADEIRA_STEAM_HOST_LOG` | Report file. |
+| `MADEIRA_STEAM_HOST_CEG=1` | The game ships CEG executables: prepare them first. |
+| `MADEIRA_DOCK_OFFLINE=1` | The launcher found no network: ask Valve's client for an offline logon straight away (`docs/OFFLINE.md`). |
+
+Switches that turn a behaviour off (all default on): `MADEIRA_DOCK_CEG=0`,
+`MADEIRA_DOCK_CEG_SCM=0`, `MADEIRA_DOCK_CEG_SERVICE_INSTALL=0`, `MADEIRA_DOCK_CONTENT_WAIT=0`,
+`MADEIRA_DOCK_CONFIG_WAIT=0`, `MADEIRA_DOCK_SESSION_WAIT=0`, `MADEIRA_DOCK_LIST_ENTITLEMENT=0`,
+`MADEIRA_DOCK_CLIENT_202601=0`, `MADEIRA_DOCK_HANDOFF_DIAGNOSTICS=0`,
+`MADEIRA_DOCK_INSTALL_SCM=0`, `MADEIRA_DOCK_OFFLINE_LOGON=0` (no offline start, and no
+`session-offline-*` question), `MADEIRA_DOCK_KEEP_ALIVE=0` (no hold after the running report
+ends; a `;`-separated list of image names instead adds those programs to the game's tree). The
+three waits only ask Valve's client again for a bounded time when it answers "content is still
+installing", "the game's configuration has not arrived yet" or "another session is playing"; they
+never turn a refusal into a launch. `MADEIRA_DOCK_GAME_SCM` is three-way: `0` never starts a
+service manager for the game session, `1` always does, unset starts one only when the prefix
+registers a startable (automatic or on-demand) service outside Windows (see "Services"). Madeira
+also sets `1` for a game whose own Steam install script recorded a non-Microsoft program, since a
+launcher registers its service only on its first run, through the manager.
+
+The selected launch key is reused on every retry and reported as numeric
+`launch-option-index`. Invalid input reports `launch-option-invalid=1`. An error 22 whose
+bounded detail explicitly identifies the requested launch entry as missing reports
+`launch-option-missing` and stops instead of waiting for configuration. The detail is never
+logged; other configuration waits and the sign-in and licence checks are unchanged.
+
+### Result codes
+
+| Code | Meaning |
+|---|---|
+| 0 | The stage that was asked for completed (after a launch: the game ran and ended). |
+| 2 | Not enabled. |
+| 10 to 13 | Bootstrap test: bad exports, user creation failed; any mode: malformed callback, release failed. |
+| 20 | Stopped before a session: another Steam or Dock is running, bad Steam folder, client file unreadable, not loadable or missing its exports. |
+| 30 | Unsupported client build, or a method address did not match. |
+| 31, 32 | Developer mode: the client has no cached sign-in for the account, or could not select it. |
+| 33 | The client did not start a sign-in. |
+| 34 | Not signed in, or licence not confirmed, within 90 seconds. |
+| 35, 36 | The game is not in the account's licence list; the list could not be read. |
+| 37 | The sign-in transfer was missing, malformed or for another App ID. |
+| 40 | Launch interfaces did not match the supported build. |
+| 41 | The client's install folder for the game is not the expected one. |
+| 42, 47 | Steam's discovery registry values could not be written, or could not be restored. |
+| 43 | The client did not accept the launch request. |
+| 44, 45 | No launch result in time; Valve's client refused the launch (its reason is reported as `launch-client-error`). |
+| 46 | The game ran, but the launch result was missing or rejected. |
+| 48 | The client was still installing content the game needs when the wait ended. |
+| 49 | CEG preparation failed. |
+| 50 | Offline: Valve's client cannot log this account on offline (no valid offline logon ticket), or this client build has no verified offline logon. |
+| 51 | Offline: Valve's client refused the offline logon. |
+| 54 | Extra launch arguments are malformed or too long. |
+| 52 | Offline: signed in offline, but the client's cached licences did not list the game within 60 seconds. |
+
+The report (`[steam-host] =` lines) is documented field by field in
+Madeira's `docs/MADEIRA_DOCK.md`.
+
+## Build and test
+
+```sh
+bash tools/check.sh # unit tests with ASan and UBSan (host clang)
+bash tools/build.sh # x86-64 and i686 dockhost with llvm-mingw, static, stripped
+bash tools/build.sh --stage # also copy the x64 EXE and dock-notices.txt into ../Madeira
+python3 tools/check-privacy.py [--history|--self-test]
+```
+
+- The tests cover the transfer parser and its bounds, the client-layout table, callback
+ handling, licence-list bounds, launch-result decoding and the service-manager decisions. They
+ use synthetic data and do not contact Steam.
+- `tools/test-invalid-handoff.ps1` runs the real host on Windows with a malformed transfer and
+ checks that it fails before sign-in and that the file is gone.
+- `tools/check-privacy.py` fails on personal paths, email addresses, token-like strings, private
+ keys, real-looking SteamIDs and Steam login-cache files, in the tree or in history.
+
+Never commit tokens, passwords, Steam login caches, account names, real SteamIDs, personal paths,
+logs, Valve binaries, games or build output.
+
+## Repository layout
+
+| Path | Contents |
+|---|---|
+| `src/main.c` | Entry point: gates, client identification and loading, shutdown, `--start-services`. |
+| `src/session.c` | Sign-in, the wait for online state, the offline logon, the licence check. |
+| `src/launch.c` | Install-folder check, CEG request, discovery values, `LaunchApp`, the game-running loop. |
+| `src/auth.c` | The one-use sign-in transfer: parse, consume, clear. |
+| `src/client_layout.c` | The supported client builds and their method addresses. |
+| `src/scm.c` | Wine's service manager and Valve's service installer. |
+| `src/probe.c`, `src/validation.c` | The bootstrap test and the pure decision functions the tests cover. |
+| `tests/`, `tools/` | Unit tests; build, check, privacy and layout scripts. |
+| `docs/CLIENT_LAYOUTS.md` | Provenance and verification of each supported client build. |
+| `docs/HANDOFF.md`, `docs/HISTORY.md` | Development notes and the round-by-round history. |
+| `notices/`, `THIRD-PARTY-NOTICES.md` | Toolchain runtime notices and research references. |
+
+## Provenance
+
+The implementation is independent. No code from a Steam emulator, from another project's host or
+from Valve is included. Interface layouts were researched with
+[OpenSteamworks](https://github.com/OpenSteamClient/OpenSteamworks) (MIT, used as a reference
+only) and confirmed by inspecting the exact client files Dock supports; the public shutdown slot
+was checked against Valve's Steamworks header as distributed with Proton. Details are in
+`THIRD-PARTY-NOTICES.md`.
+
+## Relationship to Valve
+
+Steam and the Steam client are Valve's. This project is not affiliated with, authorised by or
+endorsed by Valve, and it uses interfaces Valve has not published and may change at any time.
+Its purpose is narrow: to let the owner of a game play their own licensed copy on their own
+device, with Valve's client performing the sign-in, the licence check and the launch, and with
+the game's protection left exactly as shipped.
+
+Questions or concerns, including from Valve or from a game's rights holder, are welcome in the
+[issue tracker](https://github.com/125hz/madeira-dock/issues).
diff --git a/server/dock/THIRD-PARTY-NOTICES.md b/server/dock/THIRD-PARTY-NOTICES.md
new file mode 100644
index 00000000..9f0f7029
--- /dev/null
+++ b/server/dock/THIRD-PARTY-NOTICES.md
@@ -0,0 +1,35 @@
+# Third-party references and components
+
+Madeira Dock is licensed GPL-3.0-or-later with the Madeira Converter
+Exception (see `LICENSE`, `COPYING` and `LICENSE-EXCEPTION.md`).
+
+Dock's implementation is independently written. No Steamworks emulator,
+GameNative host binary, Valve client binary, game binary or reference-project
+implementation is included in this repository.
+
+API declarations and architecture were researched using OpenSteamworks
+(commit d0abbe85f4b8314607836e1c588bb48813f642a4), Valve's public Steamworks
+documentation and independently inspected, unmodified installed client files.
+OpenSteamworks was used as a research reference only: no declaration, header,
+generated interface or implementation from it was copied into Dock. Dock's
+call types are its own C function-pointer typedefs addressed by vtable slot
+number and checked against exact method addresses in the supported client
+builds (see `docs/CLIENT_LAYOUTS.md`). For reference, the OpenSteamworks
+components consulted are MIT-licensed (Copyright (c) 2024 Onni Kukkonen) at
+that commit. Reference interface layouts were checked against the exact
+supported client.
+
+The public SteamClient021 shutdown slot was checked against Valve's public
+Steamworks SDK header as distributed in Proton (`isteamclient.h`); nothing
+from that header was copied.
+
+Builds use LLVM/MinGW-w64, and release executables statically link their
+runtime. Those licences and runtime notices continue to apply alongside
+Dock's own licence; their texts are retained in
+`notices/MinGW-w64-runtime.txt` and `notices/LLVM.txt`. `tools/build.sh
+--stage` writes `dock-notices.txt` with Dock's licence statement, the Madeira
+Converter Exception, the GPL-3.0 text and these runtime notices.
+
+Windows system DLLs are provided by Windows or the Wine environment. Valve's
+client components are obtained separately under Valve's terms and are not
+covered by Dock's licence. GameNative's steamhost binaries were not used.
diff --git a/server/dock/build.sh b/server/dock/build.sh
new file mode 100644
index 00000000..12a27566
--- /dev/null
+++ b/server/dock/build.sh
@@ -0,0 +1,8 @@
+#!/usr/bin/env bash
+# Builds dockhost.exe (x86-64 Windows, static, stripped) with MinGW-w64: the build the server image uses. Usage: build.sh [output.exe]
+set -euo pipefail
+cd "$(dirname "$0")"
+out=${1:-dockhost.exe}
+x86_64-w64-mingw32-gcc -std=c11 -O2 -Wall -Wextra -Werror -Wno-cast-function-type -static -s -o "$out" \
+ src/main.c src/probe.c src/session.c src/launch.c src/validation.c src/auth.c src/client_layout.c src/scm.c src/hold.c -ladvapi32 -luser32
+echo "built $out"
diff --git a/server/dock/check.sh b/server/dock/check.sh
new file mode 100644
index 00000000..b9d55306
--- /dev/null
+++ b/server/dock/check.sh
@@ -0,0 +1,14 @@
+#!/usr/bin/env bash
+# Unit tests of Dock's pure logic (transfer parser, client-layout table, callbacks, licence list, launch result, service decisions): synthetic data,
+# no Steam, no Wine. Sanitizers (ASan, UBSan) are used when the compiler has them. Usage: check.sh (CC=... to choose the compiler)
+set -euo pipefail
+cd "$(dirname "$0")"
+cc=${CC:-$(command -v gcc || command -v clang)}
+san=""
+if echo 'int main(void){return 0;}' | "$cc" -x c - -fsanitize=address,undefined -o /dev/null 2>/dev/null; then san="-fsanitize=address,undefined"; fi
+out=$(mktemp -d); trap 'rm -rf "$out"' EXIT
+for t in probe validation auth client_layout; do
+ "$cc" -std=c11 -g -O1 -Wall -Wextra -Werror $san -Isrc "src/$t.c" "tests/test-$t.c" -o "$out/test-$t"
+ "$out/test-$t"
+done
+echo "dock unit tests passed${san:+ (with sanitizers)}"
diff --git a/server/dock/docs/CLIENT_LAYOUTS.md b/server/dock/docs/CLIENT_LAYOUTS.md
new file mode 100644
index 00000000..64f991c1
--- /dev/null
+++ b/server/dock/docs/CLIENT_LAYOUTS.md
@@ -0,0 +1,127 @@
+# Exact client adapters — ml1860
+
+"Private" below means Valve's undocumented client interfaces. These are
+compatibility adapters for genuine Valve libraries, not replacements for the
+libraries or their authentication/DRM.
+An unrecognized SHA-256 or mismatched method address fails closed. Interface
+names and PE timestamps alone never authorize private calls.
+
+The previously supported September build has SHA-256
+`caba4826aa3501039d095aee1843a6bfb270fb43a3ab4455b2d6733223579fee`.
+ml1860 also supports the owner's device's exact January build:
+`71b391fe9f3e2006cbc81a5c75eef3eb4186012deabfdb2c8b7e8d4850ecf640`,
+PE timestamp 1769726215. `MADEIRA_DOCK_CLIENT_202601=0` disables this adapter.
+`[steam-host] ml1860 session-client-adapter=202601` identifies selection;
+it is not authentication or entitlement evidence.
+
+## Provenance and independent inspection
+
+Fetched from Valve on 2026-09-24 via HTTPS:
+`https://client-update.akamai.steamstatic.com/steam_client_win32`.
+The returned manifest reports version 1769731672 and names
+`bins_win32.zip.23e34a6d4b10596a44561a5100dac5585d2517da`, downloaded
+from the same host. Archive SHA-256 matches its manifest:
+`8b712b2a3412a9066b7725f4e1c5cef9a7ca5b187b6585a5b92d25d09df0ba62`.
+Its steamclient64.dll matches the device report byte fingerprint exactly.
+Windows Authenticode verification reports Valid, signer Valve Corp.
+Downloaded files and analysis output stay ignored in `.build/client-jan2026`.
+No Valve DLLs or archives are included in the app/repository distribution.
+
+RTTI gives offset-zero vtables CSteamClient at RVA 0x12ec718,
+IClientUserMap at 0x12b8938, IClientAppManagerMap at 0x12c0278.
+All 14 called private methods are pinned in `src/client_layout.c`. User and
+manager method names were independently checked via their RIP-relative IPC
+strings, including LogOn, SetLoginToken, BIsSubscribedApp, GetSubscribedApps,
+LaunchApp and GetAppInstallDir. Slots are unchanged between these two builds.
+
+Disassembly comparison of the called wrappers (through their first return)
+retains identical argument registers/stack widths and return widths. Engine
+user/manager wrappers have identical normalized instructions. Differences in
+the others are equivalent signed-negative cleanup tests and reordered loads
+before the same underlying call; manager IPC type constants vary by build.
+Those constants are implemented by Valve's own matching library, not Dock.
+GetAPICallResult still forwards the same buffer/size/callback/failure args.
+This inspection is bounded ABI evidence, not full behavioral compatibility.
+The launch callback remains strictly checked for ID 1270027, 524 bytes, the
+requested GameID and success. Do not loosen it if a future device test fails.
+
+Reproduce the independent RTTI/table checks with Python (no DLL execution):
+
+```
+python tools/check-client-layout.py PATH_TO_OFFICIAL_STEAMCLIENT64_DLL
+```
+
+Portable sanitizer tests reject unknown/partial/changed fingerprints and
+mismatched method pointers. A native Windows probe using the isolated official
+January DLL verified all session pointers, with login/launch disabled, and
+exited 0. Disabling the January adapter reproduces rejection 30. This does not prove native-token authentication or iOS game launch.
+The original supported September table is also checked for regression.
+
+## Device result motivating the change
+
+Log 60 / ml1850 got past the earlier native stale-image crash, loaded both
+interfaces, then returned session-unsupported-client=1 / probe-result=30.
+It never reached authentication. The apparent infinite wait was separately a
+public runtime notification gap on normal Wine exit. ml1860 fixes the common
+exit wrapper and exports a bounded whitelist of Dock report fields, including
+this adapter revision and fingerprint, in the normal Madeira log.
+
+## ml1990 — custom executable (CEG) preparation
+
+Both pinned builds add one called method, independently identified in each:
+IClientUserMap slot 71 wrapper, September RVA `0x84e8b0`, January RVA
+`0x82a8c0`. Slot 70 is GetCustomBinariesState (`0x769b60` / `0x74cc60`;
+not called). Each wrapper names "RequestCustomBinaries" through a
+RIP-relative LEA and serializes IPC function ID `0x08711e2c` and fencepost
+`0x08b15ab0`; `tools/check-client-layout.py` now verifies slot, RVA, name
+and function ID. Slot 70's wrapper fails that name check (January negative control).
+
+Wrapper ABI (both builds, identical instructions except call targets):
+rcx this, edx u32 AppID, r8b bool, r9b bool, one stack argument serialized
+as 8 bytes; it reads one response byte (must be 11) and a 4-byte result,
+returning 55 (k_EResultRemoteCallFailed) on IPC failure. The server
+dispatcher (`cmp eax,0x8711e2c`) calls the user object's slot 71 with the
+same five values. That implementation (`0x9b0860` Jan / `0x9e0d40` Sep)
+immediately writes `0` through the fifth value, so it is a `uint32 *`
+(the older 32-bit reference lists it as bytes4), then returns: 2 unknown
+or uninstalled app, 10 app busy (updating/running flags), 1 with no
+CustomExecutable entries, 9 no install folder, else 1 and the count of
+per-file jobs started or already in progress. OpenSteamworks reference
+lists the older build as `RequestCustomBinaries(AppId_t, bool, bool, uint)`.
+
+First bool: skip DRM-identifier extraction and force a refresh. With zero
+identifiers the job reports success without downloading, so Dock passes
+false. Second bool: job flag 0x10, which ends the job with Busy (10) after a
+server Busy reply instead of Valve's own retry loop; Dock passes false and
+bounds the total wait itself (5 minutes).
+
+Completion: CDRM::OnDRMDownloadJobFinish posts callback **1020025**
+(`0xf9079`), 8 bytes: int32 EResult, uint32 AppID, once per job (source file
+clientjobrequestcustombinary.cpp; strings "OnDRMDownloadJobFinish: %u (%s)").
+Each server reply also posts 1020024 (`0xf9078`), 12 bytes: EResult, AppID,
+bool. Identical IDs/sizes in both builds. The launch-time runtime DRM path
+posts 1020025 with the same layout (Timeout 16) after a 0x8000DEAD report.
+
+LaunchApp does not itself request custom binaries: the only callers of the
+per-file request (`0x4f2a50` Jan) are this IClientUser method and the running
+game's legacy DRM IPC fix-up. Hence the explicit request before LaunchApp.
+Extraction reads PE resources (STEAM_SPLIT_GUID/STEAM_GUIDD/STEAM_MINSTANCE)
+in process. The file list comes from the app manifest's CheckGuid entries.
+Delivery of 1020025 to a global-user pipe and server success remain unproven
+at runtime: this is static evidence only.
+
+## Offline logon (see OFFLINE.md)
+
+Both pinned builds add three called methods on IClientUserMap, at the same
+slots in each: 5 `GetLogonState` (September RVA `0x77e460`, January
+`0x7612c0`, IPC function `0xb3679023`), 214 `CanLogonOffline` (`0x73cbb0` /
+`0x720330`, `0xe391b9f0`) and 215 `LogOnOffline` (`0x8415d0` / `0x81dad0`,
+`0x706f013f`). `tools/check-client-layout.py` verifies slot, RVA, the method
+name each wrapper references through a RIP-relative LEA, and the function ID.
+
+Wrapper ABI, identical in both builds apart from call targets and the known
+signed-negative cleanup test: slots 5 and 214 take only `this` and read back a
+4-byte result; slot 215 takes `this` and one byte (dl, serialized as 1 byte)
+and reads back a 4-byte result. Neighbouring slots 216
+`ValidateOfflineLogonTicket` and 217 `BGetOfflineLogonTicket` are not called:
+Dock never handles the ticket itself.
diff --git a/server/dock/docs/OFFLINE.md b/server/dock/docs/OFFLINE.md
new file mode 100644
index 00000000..f3b325ec
--- /dev/null
+++ b/server/dock/docs/OFFLINE.md
@@ -0,0 +1,74 @@
+# Offline start
+
+Steam's own client can log an account on without a connection. It does this
+with an *offline logon ticket*: during an online logon the client asks Steam
+for one and stores it (`Offline.GetOfflineLogonTicket`; the client's settings
+`bEnableOfflineLogonTicket` and `bRequireOfflineLogonTicket` both default to
+on), and a later offline logon is only accepted with a valid ticket. Desktop
+Steam's "Offline Mode" is this mechanism.
+
+Dock uses it as it is. It does not store, read, copy or check the ticket and
+does not decide anything about ownership:
+
+1. **Online starts are unchanged.** After Valve's client has confirmed the
+ game's licence, Dock asks it `CanLogonOffline` and reports the answer as
+ `session-offline-ready` (again after the game ends, since the client fetches
+ the ticket on its own schedule). The launcher uses that to show whether a
+ game has been "saved for offline play".
+2. **An offline start** (`MADEIRA_DOCK_OFFLINE=1`, set by the launcher when the
+ device has no network) submits the sign-in as usual, then asks
+ `CanLogonOffline`. Only if Valve's client answers yes does Dock call
+ `LogOnOffline`, wait for the client to load its cached licences, ask the same
+ `BIsSubscribedApp` / `GetSubscribedApps` questions as online, and start the
+ game through the same `LaunchApp` call. DRM, tickets and the game's own Steam
+ API calls are answered by Valve's client from its own cache, exactly as in
+ desktop Steam's Offline Mode.
+3. **Fallback.** An online start whose connection fails (a
+ `SteamServerConnectFailure` callback, 20 s without signing in) asks
+ `CanLogonOffline` once per failed connection and switches to the offline
+ start if the client says yes. A client that says no keeps waiting as before.
+
+A refusal ends the session with its own code and never starts the game:
+
+| Code | Meaning |
+| --- | --- |
+| 50 | Valve's client cannot log this account on offline: no valid offline logon ticket. Start the game once while online. |
+| 51 | Valve's client refused the offline logon. |
+| 52 | Logged on offline, but the client's cached licences did not list the game within 60 s. |
+
+Report fields (numbers only): `session-offline-abi`, `session-offline-requested`,
+`session-offline-can`, `session-offline-logon-result`, `session-offline-logon-retry`,
+`session-offline-logon-state`, `session-offline-callback-id`, `session-offline-entitled`,
+`session-offline-listed`, `session-offline-timeout-state`, `session-offline-fallback`,
+`session-offline-ready`.
+
+`MADEIRA_DOCK_OFFLINE_LOGON=0` removes the feature: the three methods are not
+looked up, an offline request ends with 50, and nothing else changes.
+
+## What is and is not known
+
+The three methods are pinned per client build like every other private call
+(`docs/CLIENT_LAYOUTS.md`): `IClientUser` slot 5 `GetLogonState`, 214
+`CanLogonOffline`, 215 `LogOnOffline`, identified by the method name and IPC
+function id each wrapper carries. Their wrappers take no argument (5, 214) and
+one bool (215) and return 32 bits.
+
+Not established by inspection: the meaning of `LogOnOffline`'s bool (Dock asks
+with `false` and, only on refusal, once with `true`, and reports which was
+accepted), the values `GetLogonState` takes offline (reported, not interpreted),
+and how long Steam's offline logon ticket stays valid (Valve's client enforces
+that itself; when it expires the answer is 50 and an online start renews it).
+
+## Device result
+
+2026-10-04, iPhone 18,3 / iOS 27.0, January client (adapter 202601), no network
+path: `session-offline-can=1`, `session-offline-logon-result=1` (accepted with
+`false`, no retry), `session-offline-logon-state=0` and unchanged (the state
+does not signal an offline logon, so nothing waits on it),
+`session-offline-entitled=1`, `session-offline-listed=1` with 1584 cached
+subscriptions one second after the logon, `launch-client-error=0`, the game's
+window 8 s after the host started. The account had signed in online earlier
+through the one-use token handoff, so that handoff leaves Valve's client able
+to log on offline. Not yet exercised on a device: a refusal (50, 51, 52), the
+connection-failure fallback, the September client, and a game with per-user
+executables.
diff --git a/server/dock/notices/LLVM.txt b/server/dock/notices/LLVM.txt
new file mode 100644
index 00000000..fa6ac540
--- /dev/null
+++ b/server/dock/notices/LLVM.txt
@@ -0,0 +1,279 @@
+==============================================================================
+The LLVM Project is under the Apache License v2.0 with LLVM Exceptions:
+==============================================================================
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+
+
+---- LLVM Exceptions to the Apache 2.0 License ----
+
+As an exception, if, as a result of your compiling your source code, portions
+of this Software are embedded into an Object form of such source code, you
+may redistribute such embedded portions in such Object form without complying
+with the conditions of Sections 4(a), 4(b) and 4(d) of the License.
+
+In addition, if you combine or link compiled forms of this Software with
+software that is licensed under the GPLv2 ("Combined Software") and if a
+court of competent jurisdiction determines that the patent provision (Section
+3), the indemnity provision (Section 9) or other Section of the License
+conflicts with the conditions of the GPLv2, you may retroactively and
+prospectively choose to deem waived or otherwise exclude such Section(s) of
+the License, but only in their entirety and only with respect to the Combined
+Software.
+
+==============================================================================
+Software from third parties included in the LLVM Project:
+==============================================================================
+The LLVM Project contains third party software which is under different license
+terms. All such code will be identified clearly using at least one of two
+mechanisms:
+1) It will be in a separate directory tree with its own `LICENSE.txt` or
+ `LICENSE` file at the top containing the specific license and restrictions
+ which apply to that software, or
+2) It will contain specific license and restriction terms at the top of every
+ file.
+
+==============================================================================
+Legacy LLVM License (https://llvm.org/docs/DeveloperPolicy.html#legacy):
+==============================================================================
+University of Illinois/NCSA
+Open Source License
+
+Copyright (c) 2003-2019 University of Illinois at Urbana-Champaign.
+All rights reserved.
+
+Developed by:
+
+ LLVM Team
+
+ University of Illinois at Urbana-Champaign
+
+ http://llvm.org
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of
+this software and associated documentation files (the "Software"), to deal with
+the Software without restriction, including without limitation the rights to
+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
+of the Software, and to permit persons to whom the Software is furnished to do
+so, subject to the following conditions:
+
+ * Redistributions of source code must retain the above copyright notice,
+ this list of conditions and the following disclaimers.
+
+ * Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimers in the
+ documentation and/or other materials provided with the distribution.
+
+ * Neither the names of the LLVM Team, University of Illinois at
+ Urbana-Champaign, nor the names of its contributors may be used to
+ endorse or promote products derived from this Software without specific
+ prior written permission.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
+FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE
+SOFTWARE.
+
diff --git a/server/dock/notices/MinGW-w64-runtime.txt b/server/dock/notices/MinGW-w64-runtime.txt
new file mode 100644
index 00000000..776d5f10
--- /dev/null
+++ b/server/dock/notices/MinGW-w64-runtime.txt
@@ -0,0 +1,265 @@
+MinGW-w64 runtime licensing
+***************************
+
+This program or library was built using MinGW-w64 and statically
+linked against the MinGW-w64 runtime. Some parts of the runtime
+are under licenses which require that the copyright and license
+notices are included when distributing the code in binary form.
+These notices are listed below.
+
+
+========================
+Overall copyright notice
+========================
+
+Copyright (c) 2009, 2010, 2011, 2012, 2013 by the mingw-w64 project
+
+This license has been certified as open source. It has also been designated
+as GPL compatible by the Free Software Foundation (FSF).
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+ 1. Redistributions in source code must retain the accompanying copyright
+ notice, this list of conditions, and the following disclaimer.
+ 2. Redistributions in binary form must reproduce the accompanying
+ copyright notice, this list of conditions, and the following disclaimer
+ in the documentation and/or other materials provided with the
+ distribution.
+ 3. Names of the copyright holders must not be used to endorse or promote
+ products derived from this software without prior written permission
+ from the copyright holders.
+ 4. The right to distribute this software or to use it for any purpose does
+ not give you the right to use Servicemarks (sm) or Trademarks (tm) of
+ the copyright holders. Use of them is covered by separate agreement
+ with the copyright holders.
+ 5. If any files are modified, you must cause the modified files to carry
+ prominent notices stating that you changed the files and the date of
+ any change.
+
+Disclaimer
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY EXPRESSED
+OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
+EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY DIRECT, INDIRECT,
+INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
+OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
+EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+========================================
+getopt, getopt_long, and getop_long_only
+========================================
+
+Copyright (c) 2002 Todd C. Miller
+
+Permission to use, copy, modify, and distribute this software for any
+purpose with or without fee is hereby granted, provided that the above
+copyright notice and this permission notice appear in all copies.
+
+THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
+Sponsored in part by the Defense Advanced Research Projects
+Agency (DARPA) and Air Force Research Laboratory, Air Force
+Materiel Command, USAF, under agreement number F39502-99-1-0512.
+
+ * * * * * * *
+
+Copyright (c) 2000 The NetBSD Foundation, Inc.
+All rights reserved.
+
+This code is derived from software contributed to The NetBSD Foundation
+by Dieter Baron and Thomas Klausner.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions
+are met:
+ 1. Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ 2. Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+
+THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
+``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
+TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
+BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGE.
+
+
+===============================================================
+gdtoa: Converting between IEEE floating point numbers and ASCII
+===============================================================
+
+The author of this software is David M. Gay.
+
+Copyright (C) 1997, 1998, 1999, 2000, 2001 by Lucent Technologies
+All Rights Reserved
+
+Permission to use, copy, modify, and distribute this software and
+its documentation for any purpose and without fee is hereby
+granted, provided that the above copyright notice appear in all
+copies and that both that the copyright notice and this
+permission notice and warranty disclaimer appear in supporting
+documentation, and that the name of Lucent or any of its entities
+not be used in advertising or publicity pertaining to
+distribution of the software without specific, written prior
+permission.
+
+LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
+INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
+IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY
+SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
+IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
+ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
+THIS SOFTWARE.
+
+ * * * * * * *
+
+The author of this software is David M. Gay.
+
+Copyright (C) 2005 by David M. Gay
+All Rights Reserved
+
+Permission to use, copy, modify, and distribute this software and its
+documentation for any purpose and without fee is hereby granted,
+provided that the above copyright notice appear in all copies and that
+both that the copyright notice and this permission notice and warranty
+disclaimer appear in supporting documentation, and that the name of
+the author or any of his current or former employers not be used in
+advertising or publicity pertaining to distribution of the software
+without specific, written prior permission.
+
+THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
+INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN
+NO EVENT SHALL THE AUTHOR OR ANY OF HIS CURRENT OR FORMER EMPLOYERS BE
+LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY
+DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
+WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
+ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
+SOFTWARE.
+
+ * * * * * * *
+
+The author of this software is David M. Gay.
+
+Copyright (C) 2004 by David M. Gay.
+All Rights Reserved
+Based on material in the rest of /netlib/fp/gdota.tar.gz,
+which is copyright (C) 1998, 2000 by Lucent Technologies.
+
+Permission to use, copy, modify, and distribute this software and
+its documentation for any purpose and without fee is hereby
+granted, provided that the above copyright notice appear in all
+copies and that both that the copyright notice and this
+permission notice and warranty disclaimer appear in supporting
+documentation, and that the name of Lucent or any of its entities
+not be used in advertising or publicity pertaining to
+distribution of the software without specific, written prior
+permission.
+
+LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
+INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
+IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY
+SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
+IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
+ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
+THIS SOFTWARE.
+
+
+=========================
+Parts of the math library
+=========================
+
+Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
+
+Developed at SunSoft, a Sun Microsystems, Inc. business.
+Permission to use, copy, modify, and distribute this
+software is freely granted, provided that this notice
+is preserved.
+
+ * * * * * * *
+
+Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
+
+Developed at SunPro, a Sun Microsystems, Inc. business.
+Permission to use, copy, modify, and distribute this
+software is freely granted, provided that this notice
+is preserved.
+
+ * * * * * * *
+
+FIXME: Cephes math lib
+Copyright (C) 1984-1998 Stephen L. Moshier
+
+It sounds vague, but as to be found at
+, it gives an
+impression that the author could be willing to give an explicit
+permission to distribute those files e.g. under a BSD style license. So
+probably there is no problem here, although it could be good to get a
+permission from the author and then add a license into the Cephes files
+in MinGW runtime. At least on follow-up it is marked that debian sees the
+version a-like BSD one. As MinGW.org (where those cephes parts are coming
+from) distributes them now over 6 years, it should be fine.
+
+=================================================
+Some string, memory and time conversion functions
+=================================================
+
+Copyright © 2005-2020 Rich Felker, et al.
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+===================================
+Headers and IDLs imported from Wine
+===================================
+
+Some header and IDL files were imported from the Wine project. These files
+are prominent maked in source. Their copyright belongs to contributors and
+they are distributed under LGPL license.
+
+Disclaimer
+
+This library is free software; you can redistribute it and/or
+modify it under the terms of the GNU Lesser General Public
+License as published by the Free Software Foundation; either
+version 2.1 of the License, or (at your option) any later version.
+
+This library is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+Lesser General Public License for more details.
diff --git a/server/dock/src/auth.c b/server/dock/src/auth.c
new file mode 100644
index 00000000..febb2072
--- /dev/null
+++ b/server/dock/src/auth.c
@@ -0,0 +1,97 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ * Copyright 2026 125hz
+ * Madeira Converter Exception: see LICENSE-EXCEPTION.md
+ * ml1830: bounded, single-use native credential handoff. */
+#include "auth.h"
+#include
+#ifdef _WIN32
+#include
+#endif
+
+void dock_auth_clear(void *bytes, size_t size)
+{
+ volatile unsigned char *p = bytes;
+ while (size--) *p++ = 0;
+}
+
+static uint64_t little(const unsigned char *p, unsigned count)
+{
+ uint64_t value = 0;
+ for (unsigned i = 0; i < count; ++i) value |= (uint64_t)p[i] << (8 * i);
+ return value;
+}
+
+bool dock_auth_parse(const unsigned char *bytes, size_t size, struct dock_auth *out)
+{
+ if (!out) return false;
+ dock_auth_clear(out, sizeof(*out));
+ if (!bytes || size < 24 || size > DOCK_AUTH_MAX || memcmp(bytes, "MDOCK001", 8)) return false;
+ uint64_t id = little(bytes + 8, 8);
+ uint32_t app = (uint32_t)little(bytes + 16, 4);
+ size_t name_size = (size_t)little(bytes + 20, 2), token_size = (size_t)little(bytes + 22, 2);
+ if ((id >> 56) != 1 || ((id >> 52) & 15) != 1 ||
+ ((id >> 32) & 0xfffff) != 1 || !(uint32_t)id || !app || app == UINT32_MAX ||
+ !name_size || name_size > 64 || !token_size || token_size > 8192 ||
+ size != 24 + name_size + token_size) return false;
+ for (size_t i = 24; i < 24 + name_size; ++i)
+ if (bytes[i] < 33 || bytes[i] > 126) return false;
+ for (size_t i = 24 + name_size; i < size; ++i) {
+ unsigned char c = bytes[i];
+ if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
+ (c >= '0' && c <= '9') || c == '.' || c == '_' || c == '-')) return false;
+ }
+ out->steam_id = id;
+ out->app_id = app;
+ memcpy(out->account, bytes + 24, name_size);
+ memcpy(out->token, bytes + 24 + name_size, token_size);
+ return true;
+}
+
+#ifdef _WIN32
+bool dock_auth_consume_diagnostic(const wchar_t *path, struct dock_auth *out,
+ struct dock_auth_failure *failure)
+{
+ unsigned char bytes[DOCK_AUTH_MAX];
+ DWORD read = 0;
+ LARGE_INTEGER size;
+ bool ok = false;
+ *failure = (struct dock_auth_failure){0};
+ dock_auth_clear(out, sizeof(*out));
+ /* Exclusive open and delete-on-close: the file is gone before login.
+ * Reparse points are not followed. iOS also deletes any unconsumed file
+ * after launch failure, session exit, sign-out, and the next app start. */
+ HANDLE file = CreateFileW(path, GENERIC_READ | DELETE, 0, NULL, OPEN_EXISTING,
+ FILE_FLAG_DELETE_ON_CLOSE | FILE_FLAG_OPEN_REPARSE_POINT, NULL);
+ if (file == INVALID_HANDLE_VALUE) {
+ *failure = (struct dock_auth_failure){DOCK_AUTH_OPEN, GetLastError()};
+ return false;
+ }
+ BY_HANDLE_FILE_INFORMATION info;
+ if (!GetFileInformationByHandle(file, &info))
+ *failure = (struct dock_auth_failure){DOCK_AUTH_INFO, GetLastError()};
+ else if (info.dwFileAttributes & (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_REPARSE_POINT))
+ failure->stage = DOCK_AUTH_TYPE;
+ else if (!GetFileSizeEx(file, &size))
+ *failure = (struct dock_auth_failure){DOCK_AUTH_SIZE, GetLastError()};
+ else if (size.QuadPart < 24 || size.QuadPart > DOCK_AUTH_MAX)
+ failure->stage = DOCK_AUTH_BOUNDS;
+ else if (!ReadFile(file, bytes, (DWORD)size.QuadPart, &read, NULL))
+ *failure = (struct dock_auth_failure){DOCK_AUTH_READ, GetLastError()};
+ else if (read != size.QuadPart)
+ failure->stage = DOCK_AUTH_READ;
+ else if (!(ok = dock_auth_parse(bytes, read, out)))
+ failure->stage = DOCK_AUTH_PARSE;
+ if (!CloseHandle(file)) {
+ if (!failure->stage) *failure = (struct dock_auth_failure){DOCK_AUTH_CLOSE, GetLastError()};
+ ok = false;
+ }
+ dock_auth_clear(bytes, sizeof(bytes));
+ if (!ok) dock_auth_clear(out, sizeof(*out));
+ return ok;
+}
+bool dock_auth_consume(const wchar_t *path, struct dock_auth *out)
+{
+ struct dock_auth_failure failure;
+ return dock_auth_consume_diagnostic(path, out, &failure);
+}
+#endif
diff --git a/server/dock/src/auth.h b/server/dock/src/auth.h
new file mode 100644
index 00000000..31c90131
--- /dev/null
+++ b/server/dock/src/auth.h
@@ -0,0 +1,29 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ * Copyright 2026 125hz
+ * Madeira Converter Exception: see LICENSE-EXCEPTION.md */
+#ifndef MADEIRA_DOCK_AUTH_H
+#define MADEIRA_DOCK_AUTH_H
+#include
+#include
+#include
+#define DOCK_AUTH_MAX (24 + 64 + 8192)
+struct dock_auth {
+ uint64_t steam_id;
+ uint32_t app_id;
+ char account[65];
+ char token[8193];
+};
+/* This envelope transports a credential, never an entitlement assertion.
+ * Authentication and ownership still require Valve's online response. */
+bool dock_auth_parse(const unsigned char *bytes, size_t size, struct dock_auth *out);
+void dock_auth_clear(void *bytes, size_t size);
+#ifdef _WIN32
+/* Numeric operation/error only; never a path or credential payload. */
+struct dock_auth_failure { int32_t stage; uint32_t error; };
+enum { DOCK_AUTH_OPEN = 1, DOCK_AUTH_INFO, DOCK_AUTH_TYPE, DOCK_AUTH_SIZE,
+ DOCK_AUTH_BOUNDS, DOCK_AUTH_READ, DOCK_AUTH_PARSE, DOCK_AUTH_CLOSE, DOCK_AUTH_PATH };
+bool dock_auth_consume(const wchar_t *path, struct dock_auth *out);
+bool dock_auth_consume_diagnostic(const wchar_t *path, struct dock_auth *out,
+ struct dock_auth_failure *failure);
+#endif
+#endif
diff --git a/server/dock/src/client_layout.c b/server/dock/src/client_layout.c
new file mode 100644
index 00000000..aa248084
--- /dev/null
+++ b/server/dock/src/client_layout.c
@@ -0,0 +1,38 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ * Copyright 2026 125hz
+ * Madeira Converter Exception: see LICENSE-EXCEPTION.md
+ * ml1860: exact, independently inspected Valve builds. Never select an ABI
+ * from a date/version or interface presence alone. See docs/CLIENT_LAYOUTS.md.
+ */
+#include "client_layout.h"
+#include
+static const struct dock_client_layout layouts[] = {
+ {
+ "caba4826aa3501039d095aee1843a6bfb270fb43a3ab4455b2d6733223579fee", 202609,
+ 0x972ff0, 0x970ba0, 0x970d30,
+ 0x8412f0, 0x736110, 0x729a20, 0x72ee00, 0x859860, 0x869f80,
+ 0x7324e0, 0x735670, 0x792860, 0x83f0f0, 0x758760,
+ 0x84e8b0,
+ 0x77e460, 0x73cbb0, 0x8415d0
+ },
+ {
+ "71b391fe9f3e2006cbc81a5c75eef3eb4186012deabfdb2c8b7e8d4850ecf640", 202601,
+ 0x9450e0, 0x942d40, 0x942ed0,
+ 0x81d7f0, 0x719dc0, 0x70d170, 0x712af0, 0x8352d0, 0x8459b0,
+ 0x716040, 0x719320, 0x775440, 0x81b840, 0x73b930,
+ 0x82a8c0,
+ 0x7612c0, 0x720330, 0x81dad0
+ }
+};
+const struct dock_client_layout *dock_client_layout(const char *sha256)
+{
+ if (!sha256) return NULL;
+ for (unsigned i = 0; i < sizeof(layouts) / sizeof(layouts[0]); ++i)
+ if (!strcmp(sha256, layouts[i].sha256)) return &layouts[i];
+ return NULL;
+}
+bool dock_method_is(uintptr_t module, void *object, unsigned slot, uintptr_t rva)
+{
+ return object && *(void ***)object && module && rva &&
+ (*(void ***)object)[slot] == (void *)(module + rva);
+}
diff --git a/server/dock/src/client_layout.h b/server/dock/src/client_layout.h
new file mode 100644
index 00000000..eb419765
--- /dev/null
+++ b/server/dock/src/client_layout.h
@@ -0,0 +1,24 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ * Copyright 2026 125hz
+ * Madeira Converter Exception: see LICENSE-EXCEPTION.md */
+#ifndef MADEIRA_DOCK_CLIENT_LAYOUT_H
+#define MADEIRA_DOCK_CLIENT_LAYOUT_H
+#include
+#include
+struct dock_client_layout {
+ const char *sha256;
+ int revision;
+ uintptr_t engine_user, engine_result, engine_manager;
+ uintptr_t logon, logged_on, connected, cached, select_account, token;
+ uintptr_t running, subscribed, subscriptions, launch, install_dir;
+ /* ml1990: IClientUserMap slot 71, RequestCustomBinaries (see CLIENT_LAYOUTS.md). */
+ uintptr_t ceg_request;
+ /* Offline logon: IClientUserMap slots 5 GetLogonState, 214 CanLogonOffline,
+ * 215 LogOnOffline (see CLIENT_LAYOUTS.md). Valve's client decides whether the
+ * account may log on offline, from the offline logon ticket it fetched itself
+ * during an earlier online logon. */
+ uintptr_t logon_state, can_offline, logon_offline;
+};
+const struct dock_client_layout *dock_client_layout(const char *sha256);
+bool dock_method_is(uintptr_t module, void *object, unsigned slot, uintptr_t rva);
+#endif
diff --git a/server/dock/src/hold.c b/server/dock/src/hold.c
new file mode 100644
index 00000000..4d407597
--- /dev/null
+++ b/server/dock/src/hold.c
@@ -0,0 +1,137 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ * Copyright 2026 125hz
+ * Madeira Converter Exception: see LICENSE-EXCEPTION.md
+ * ml2020: follow the game's process tree and decide whether it still holds
+ * the session (hold.h). Only observation: snapshots, limited process queries
+ * and window enumeration; nothing is created, ended or signalled.
+ */
+#define WIN32_LEAN_AND_MEAN
+#include
+#include
+#include
+#include "hold.h"
+#include "validation.h"
+
+void sh_hold_init(struct sh_hold *hold, const wchar_t *listed)
+{
+ memset(hold, 0, sizeof(*hold));
+ hold->self = GetCurrentProcessId();
+ hold->listed = listed && *listed ? listed : NULL;
+ UINT length = GetWindowsDirectoryW(hold->windows_dir, MAX_PATH);
+ if (!length || length >= MAX_PATH) wcscpy(hold->windows_dir, L"C:\\windows");
+}
+
+static struct sh_hold_entry *find_entry(struct sh_hold *hold, uint32_t pid)
+{
+ for (unsigned i = 0; i < hold->count; ++i)
+ if (hold->entries[i].pid == pid) return &hold->entries[i];
+ return NULL;
+}
+
+/* A member's child joins; a Windows image's child (a service, rpcss, a
+ * console host) does not: those belong to Windows, not to the game. */
+static bool parent_is_member(struct sh_hold *hold, uint32_t parent)
+{
+ if (parent == hold->self) return true;
+ const struct sh_hold_entry *entry = find_entry(hold, parent);
+ return entry && !entry->windows_image;
+}
+
+/* The image path and start time of a process this host may query; both are
+ * optional (a process may be gone, or refuse): then the name decides and
+ * the first sighting counts as its birth. */
+static void describe(struct sh_hold *hold, uint32_t pid, const wchar_t *name, uint64_t now,
+ struct sh_hold_entry *entry)
+{
+ entry->pid = pid;
+ entry->born_ms = now;
+ entry->last_seen_ms = now;
+ entry->windows_image = false;
+ HANDLE process = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid);
+ if (!process) process = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pid);
+ static wchar_t path[32768];
+ DWORD length = 32768;
+ if (process && QueryFullProcessImageNameW(process, 0, path, &length) && length && length < 32768)
+ entry->windows_image = sh_image_is_windows(path, hold->windows_dir);
+ else if (name)
+ entry->windows_image = sh_image_is_windows(name, hold->windows_dir);
+ FILETIME created, exited, kernel, user, current;
+ if (process && GetProcessTimes(process, &created, &exited, &kernel, &user)) {
+ GetSystemTimeAsFileTime(¤t);
+ uint64_t born = ((uint64_t)created.dwHighDateTime << 32) | created.dwLowDateTime;
+ uint64_t at = ((uint64_t)current.dwHighDateTime << 32) | current.dwLowDateTime;
+ if (at > born) {
+ uint64_t age = (at - born) / 10000ULL;
+ entry->born_ms = age < now ? now - age : 0;
+ }
+ }
+ if (process) CloseHandle(process);
+}
+
+struct window_scan { uint32_t *pids; unsigned count, capacity; };
+
+static BOOL CALLBACK on_window(HWND window, LPARAM parameter)
+{
+ struct window_scan *scan = (struct window_scan *)parameter;
+ if (!IsWindowVisible(window)) return TRUE;
+ DWORD pid = 0;
+ GetWindowThreadProcessId(window, &pid);
+ if (!pid) return TRUE;
+ for (unsigned i = 0; i < scan->count; ++i) if (scan->pids[i] == pid) return TRUE;
+ if (scan->count < scan->capacity) scan->pids[scan->count++] = pid;
+ return TRUE;
+}
+
+bool sh_hold_poll(struct sh_hold *hold, const struct sh_observer *o)
+{
+ uint64_t now = o->now_ms();
+ if (hold->polls && now - hold->polled_at < SH_HOLD_POLL_MS) return hold->holding;
+ hold->polled_at = now;
+ hold->polls++;
+ HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
+ if (snapshot == INVALID_HANDLE_VALUE) return hold->holding;
+ PROCESSENTRY32W process = {0};
+ process.dwSize = sizeof(process);
+ /* Two passes over one snapshot: a child listed before its parent joins
+ * in the second. Deeper chains join at the next poll. */
+ for (unsigned pass = 0; pass < 2; ++pass) {
+ if (!Process32FirstW(snapshot, &process)) break;
+ do {
+ uint32_t pid = process.th32ProcessID, parent = process.th32ParentProcessID;
+ if (!pid || pid == hold->self) continue;
+ struct sh_hold_entry *entry = find_entry(hold, pid);
+ if (entry) {
+ entry->last_seen_ms = now;
+ entry->parent = parent;
+ continue;
+ }
+ if (!parent_is_member(hold, parent) && !sh_keep_alive_listed(hold->listed, process.szExeFile)) continue;
+ if (hold->count >= SH_HOLD_ENTRIES) {
+ hold->dropped++;
+ continue;
+ }
+ entry = &hold->entries[hold->count++];
+ describe(hold, pid, process.szExeFile, now, entry);
+ entry->parent = parent;
+ } while (Process32NextW(snapshot, &process));
+ }
+ CloseHandle(snapshot);
+ uint32_t visible[SH_HOLD_ENTRIES];
+ struct window_scan scan = {visible, 0, SH_HOLD_ENTRIES};
+ EnumWindows(on_window, (LPARAM)&scan);
+ unsigned holders = 0, kept = 0;
+ for (unsigned i = 0; i < hold->count; ++i) {
+ struct sh_hold_entry *entry = &hold->entries[i];
+ bool alive = entry->last_seen_ms == now;
+ if (!alive && now - entry->last_seen_ms >= SH_HOLD_FORGET_MS) continue; /* gone for good; forget it */
+ hold->entries[kept++] = *entry;
+ if (!alive) continue;
+ bool window = false;
+ for (unsigned k = 0; k < scan.count && !window; ++k) window = scan.pids[k] == entry->pid;
+ if (sh_keep_alive_holds(entry->windows_image, window, now - entry->born_ms, SH_KEEP_ALIVE_YOUNG_MS)) holders++;
+ }
+ hold->count = kept;
+ hold->holders = holders;
+ hold->holding = holders > 0;
+ return hold->holding;
+}
diff --git a/server/dock/src/hold.h b/server/dock/src/hold.h
new file mode 100644
index 00000000..77d5b12e
--- /dev/null
+++ b/server/dock/src/hold.h
@@ -0,0 +1,39 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ * Copyright 2026 125hz
+ * Madeira Converter Exception: see LICENSE-EXCEPTION.md */
+#ifndef MADEIRA_STEAM_HOST_HOLD_H
+#define MADEIRA_STEAM_HOST_HOLD_H
+#include
+#include
+#include
+#include "probe.h"
+/* ml2020: the game's own process tree, followed while the game runs so the
+ * session can be held when Valve's client stops reporting the game as
+ * running although the tree is still starting or showing something
+ * (validation.h, sh_keep_alive_*). Dock only looks: it opens processes for
+ * their image path and start time and enumerates windows; it never ends or
+ * signals any of them.
+ */
+#define SH_HOLD_ENTRIES 256
+#define SH_HOLD_POLL_MS 1000ULL
+#define SH_HOLD_FORGET_MS 30000ULL
+struct sh_hold_entry {
+ uint32_t pid, parent;
+ uint64_t born_ms, last_seen_ms; /* observer clock; born from the process's own start time when known */
+ bool windows_image;
+};
+struct sh_hold {
+ struct sh_hold_entry entries[SH_HOLD_ENTRIES];
+ unsigned count, holders, polls, dropped;
+ uint64_t polled_at;
+ bool holding;
+ uint32_t self;
+ const wchar_t *listed; /* MADEIRA_DOCK_KEEP_ALIVE's image names, or NULL */
+ wchar_t windows_dir[MAX_PATH];
+};
+void sh_hold_init(struct sh_hold *hold, const wchar_t *listed);
+/* Called at any rate; at most once per SH_HOLD_POLL_MS it takes a process
+ * snapshot, follows the tree and recomputes whether any member holds the
+ * session. Returns that answer (the last one between polls). */
+bool sh_hold_poll(struct sh_hold *hold, const struct sh_observer *o);
+#endif
diff --git a/server/dock/src/launch.c b/server/dock/src/launch.c
new file mode 100644
index 00000000..8ee966d8
--- /dev/null
+++ b/server/dock/src/launch.c
@@ -0,0 +1,492 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ * Copyright 2026 125hz
+ * Madeira Converter Exception: see LICENSE-EXCEPTION.md
+ * ml1820: launch through Valve's real app manager after authenticated
+ * entitlement checks. The installed game, API DLLs and DRM remain unchanged.
+ */
+#include "launch.h"
+#include "hold.h"
+#include "scm.h"
+#include "validation.h"
+#include
+#include
+#include
+
+/* ml1970: an interrupted or stalled client update eventually fails closed. */
+#define SH_CONTENT_WAIT_MS (6ULL * 60 * 60 * 1000)
+#define SH_CONFIG_WAIT_MS (2ULL * 60 * 1000) /* ml2011 */
+#define SH_CONFIG_RETRY_MS 5000
+#define SH_SESSION_WAIT_MS (3ULL * 60 * 1000) /* ml2015 */
+#define SH_SESSION_RETRY_MS 15000
+
+#ifdef _WIN64
+typedef void *(__thiscall *get_manager_fn)(void *, int32_t, int32_t);
+typedef int32_t (__thiscall *install_dir_fn)(void *, uint32_t, char *, int32_t);
+typedef uint64_t (__thiscall *launch_fn)(void *, const uint64_t *, uint32_t, int32_t, const char *);
+typedef bool (__thiscall *running_fn)(void *, const uint64_t *);
+typedef bool (__thiscall *call_result_fn)(void *, int32_t, uint64_t, void *, int32_t, int32_t, bool *);
+
+static bool method_is(HMODULE module, void *object, unsigned slot, uintptr_t rva)
+{
+ return dock_method_is((uintptr_t)module, object, slot, rva);
+}
+
+struct saved_value { HKEY key; const wchar_t *name; DWORD previous, written; bool existed, changed; };
+static bool publish(struct saved_value *v, DWORD value)
+{
+ DWORD type = 0, size = sizeof(DWORD);
+ LSTATUS status = RegQueryValueExW(v->key, v->name, NULL, &type, (BYTE *)&v->previous, &size);
+ v->existed = status == ERROR_SUCCESS;
+ if ((v->existed && (type != REG_DWORD || size != sizeof(DWORD))) ||
+ (!v->existed && status != ERROR_FILE_NOT_FOUND)) return false;
+ v->written = value;
+ if (RegSetValueExW(v->key, v->name, 0, REG_DWORD, (BYTE *)&value, sizeof(value)) != ERROR_SUCCESS) return false;
+ v->changed = true;
+ return true;
+}
+
+static bool restore(struct saved_value *v)
+{
+ if (!v->changed) return true;
+ DWORD current = 0, size = sizeof(current), type = 0;
+ if (RegQueryValueExW(v->key, v->name, NULL, &type, (BYTE *)¤t, &size) != ERROR_SUCCESS ||
+ type != REG_DWORD || current != v->written) return false;
+ LSTATUS status = v->existed ?
+ RegSetValueExW(v->key, v->name, 0, REG_DWORD, (BYTE *)&v->previous, sizeof(DWORD)) :
+ RegDeleteValueW(v->key, v->name);
+ return status == ERROR_SUCCESS;
+}
+
+static volatile LONG interrupted;
+static BOOL WINAPI on_control(DWORD control)
+{
+ if (control != CTRL_C_EVENT && control != CTRL_BREAK_EVENT) return FALSE;
+ InterlockedExchange(&interrupted, 1);
+ return TRUE;
+}
+
+/* ml1990: ask Valve's client to prepare the user's licensed custom
+ * executables (CEG) before LaunchApp, as desktop Steam does. Valve's client
+ * reads the files to prepare from the app manifest, extracts their DRM
+ * identifiers, and requests the per-user binaries from Valve with this
+ * account's own licence. Dock never creates, alters or bypasses them.
+ *
+ * IClientUserMap slot 71 (both pinned builds): EResult(uint32 AppID,
+ * bool bForce, bool bFailFastWhenBusy, uint32 *pJobsStarted). The wrapper
+ * sends the pointer's value to the in-process engine, which writes the job
+ * count before the call returns; it is never NULL. bForce=false keeps
+ * Valve's own identifier extraction (true skips it and reports success
+ * without preparing anything). bFailFastWhenBusy=false keeps Valve's own
+ * server retry policy; this host bounds the total wait instead.
+ */
+#define SH_CEG_WAIT_MS (5ULL * 60 * 1000)
+#define SH_CEG_BUSY_RETRY_MS 10000
+typedef int32_t (__thiscall *ceg_request_fn)(void *, uint32_t, bool, bool, uint32_t *);
+
+static bool wide_flag(const wchar_t *name, wchar_t expected)
+{
+ wchar_t value[4] = {0};
+ return GetEnvironmentVariableW(name, value, 4) == 1 && value[0] == expected;
+}
+
+/* Returns 0 once every started job reported success, otherwise 49 (or 12
+ * for a malformed callback). Only numeric results are reported: no paths.
+ */
+static int prepare_custom_binaries(HMODULE module, void *client_user,
+ const struct sh_api *api, const struct sh_observer *o,
+ int32_t pipe, uint32_t appid,
+ const struct dock_client_layout *layout)
+{
+ if (!layout->ceg_request || !method_is(module, client_user, 71, layout->ceg_request)) {
+ o->event("ceg-unsupported-client", 1);
+ o->event("ceg-result", -2);
+ return 49;
+ }
+ struct sh_ceg_progress progress = {0};
+ uint64_t begin = o->now_ms(), retry_at = begin;
+ bool waiting = false;
+ unsigned busy = 0, logged_jobs = 0;
+ int32_t logged_reply = INT32_MIN;
+ while (!InterlockedCompareExchange(&interrupted, 0, 0)) {
+ uint64_t now = o->now_ms();
+ if (now - begin >= SH_CEG_WAIT_MS) {
+ o->event("ceg-finished-jobs", (int32_t)progress.finished);
+ o->event("ceg-result", -1);
+ return 49;
+ }
+ if (!waiting && now >= retry_at) {
+ uint32_t jobs = UINT32_MAX;
+ int32_t status = ((ceg_request_fn)(*(void ***)client_user)[71])(
+ client_user, appid, false, false, &jobs);
+ enum sh_ceg_step step = sh_ceg_request_step(status, jobs, &progress);
+ if (step == SH_CEG_RETRY) {
+ if (busy++ == 0) o->event("ceg-request-busy", status);
+ retry_at = now + SH_CEG_BUSY_RETRY_MS;
+ } else {
+ o->event("ceg-request-result", status);
+ o->event("ceg-request", jobs == UINT32_MAX ? -1 : (int32_t)jobs);
+ if (step != SH_CEG_WAIT) {
+ o->event("ceg-result", progress.failure);
+ return 49;
+ }
+ waiting = true;
+ }
+ }
+ for (unsigned batch = 0; batch < 64; ++batch) {
+ struct sh_callback cb = {0};
+ if (!api->get_callback(pipe, &cb)) break;
+ bool valid = cb.id > 0 && cb.size >= 0 && (!cb.size || cb.data);
+ enum sh_ceg_step step = SH_CEG_WAIT;
+ int32_t value = 0;
+ if (valid && cb.id == SH_CEG_JOB_FINISHED &&
+ sh_decode_ceg_job(cb.data, (size_t)cb.size, appid, &value)) {
+ /* A finish before any accepted request cannot be counted. */
+ if (waiting) step = sh_ceg_record_job(&progress, value);
+ if (waiting && (value != 1 || logged_jobs++ < 8)) o->event("ceg-job-result", value);
+ } else if (valid && cb.id == SH_CEG_SERVER_REPLY &&
+ sh_decode_ceg_reply(cb.data, (size_t)cb.size, appid, &value) &&
+ value != logged_reply) {
+ o->event("ceg-server-result", value);
+ logged_reply = value;
+ }
+ api->free_callback(pipe);
+ if (!valid) return SH_CALLBACK_INVALID;
+ if (step == SH_CEG_DONE) {
+ o->event("ceg-result", 1);
+ return 0;
+ }
+ if (step == SH_CEG_FAIL) {
+ o->event("ceg-finished-jobs", (int32_t)progress.finished);
+ o->event("ceg-result", progress.failure);
+ return 49;
+ }
+ }
+ o->sleep_ms(50);
+ }
+ o->event("ceg-result", -3);
+ return 49;
+}
+
+int sh_launch(HMODULE module, void *engine, void *client_user,
+ const struct sh_api *api, const struct sh_observer *o,
+ int32_t pipe, int32_t user, uint64_t steamid, uint32_t appid,
+ const struct dock_client_layout *layout)
+{
+ if (!layout || !method_is(module, engine, 43, layout->engine_manager) ||
+ !method_is(module, engine, 33, layout->engine_result) ||
+ !method_is(module, client_user, 67, layout->running)) return 40;
+ void *manager = ((get_manager_fn)(*(void ***)engine)[43])(engine, user, pipe);
+ if (!method_is(module, manager, 2, layout->launch) ||
+ !method_is(module, manager, 5, layout->install_dir)) return 40;
+ char option_text[16] = {0};
+ uint32_t launch_option = 0;
+ SetLastError(ERROR_SUCCESS);
+ DWORD option_length = GetEnvironmentVariableA("MADEIRA_STEAM_HOST_LAUNCH_OPTION", option_text, sizeof(option_text));
+ if ((!option_length && GetLastError() != ERROR_ENVVAR_NOT_FOUND) || option_length >= sizeof(option_text) ||
+ (option_length && !sh_parse_launch_option(option_text, &launch_option))) {
+ o->event("launch-option-invalid", 1);
+ return 45;
+ }
+ o->event("launch-option-index", (int32_t)launch_option);
+ // One launch's user arguments go directly to Valve's existing pszUserArgs
+ // parameter, with the selected launch option unchanged on every retry.
+ static wchar_t arguments_wide[SH_LAUNCH_ARGUMENTS_CAPACITY];
+ static char user_arguments[SH_LAUNCH_ARGUMENTS_CAPACITY];
+ user_arguments[0] = 0;
+ SetLastError(ERROR_SUCCESS);
+ DWORD arguments_length = GetEnvironmentVariableW(L"MADEIRA_STEAM_HOST_ARGUMENTS",
+ arguments_wide, SH_LAUNCH_ARGUMENTS_CAPACITY);
+ if (arguments_length >= SH_LAUNCH_ARGUMENTS_CAPACITY ||
+ (!arguments_length && GetLastError() != ERROR_SUCCESS && GetLastError() != ERROR_ENVVAR_NOT_FOUND)) {
+ o->event("launch-user-arguments-invalid", 1);
+ return 54;
+ }
+ if (arguments_length) {
+ int bytes = WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, arguments_wide, -1,
+ user_arguments, sizeof user_arguments, NULL, NULL);
+ if (!bytes || !sh_launch_arguments_valid(user_arguments, (size_t)bytes - 1)) {
+ o->event("launch-user-arguments-invalid", 1);
+ return 54;
+ }
+ }
+ o->event("launch-user-arguments-bytes", (int32_t)strlen(user_arguments));
+ static char actual_utf8[32768];
+ static wchar_t actual[32768], expected[32768], normalized[32768];
+ DWORD length = GetEnvironmentVariableW(L"MADEIRA_STEAM_HOST_EXPECTED_INSTALL", expected, 32768);
+ if (!length || length >= 32768) return 41;
+ int32_t got = ((install_dir_fn)(*(void ***)manager)[5])(manager, appid, actual_utf8, sizeof(actual_utf8));
+ if (got <= 0 || got >= (int32_t)sizeof(actual_utf8) ||
+ !memchr(actual_utf8, 0, sizeof(actual_utf8)) ||
+ !MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, actual_utf8, -1, actual, 32768)) return 41;
+ length = GetFullPathNameW(actual, 32768, normalized, NULL);
+ if (!length || length >= 32768 || _wcsicmp(normalized, expected)) {
+ o->event("launch-install-directory-mismatch", 1);
+ return 41;
+ }
+ o->event("launch-install-directory-verified", 1);
+ /* ml2020: a game whose launcher installed a Windows service of its own
+ * needs a service manager in the game session, which otherwise has none
+ * (RPC 1722 at every start of that service). MADEIRA_DOCK_GAME_SCM: 0
+ * never, 1 always; unset, only when the prefix's registry lists such a
+ * service (an automatic Win32 service outside the Windows folder: a
+ * read-only count, game-scm-services). The start is the --start-services
+ * one, bounded; it never decides whether the game launches.
+ */
+ {
+ wchar_t scm_value[4] = {0};
+ DWORD scm_length = GetEnvironmentVariableW(L"MADEIRA_DOCK_GAME_SCM", scm_value, 4);
+ enum sh_game_scm_mode scm_mode = sh_game_scm_mode(scm_length ? scm_value : NULL);
+ int32_t foreign = 0;
+ if (scm_mode == SH_GAME_SCM_AUTO) {
+ foreign = sh_game_scm_foreign_services();
+ o->event("game-scm-services", foreign);
+ }
+ if (sh_game_scm_wanted(scm_mode, foreign > 0 ? (unsigned)foreign : 0u)) {
+ bool timed_out = false;
+ int32_t outcome = sh_game_scm_start(o, &timed_out);
+ if (timed_out) o->event("game-scm-timeout", 1);
+ else o->event("game-scm", outcome);
+ } else if (scm_mode == SH_GAME_SCM_OFF) o->event("game-scm", SH_INSTALL_SCM_OFF);
+ }
+ HKEY active = NULL, machine = NULL;
+ int result = 42;
+ struct saved_value values[3] = {0};
+ /* ml1990: the public app sets MADEIRA_STEAM_HOST_CEG=1 only for an app
+ * whose depot manifests flag CustomExecutable files, and records them in
+ * the manifest's CheckGuid block. Failure never launches the game.
+ * MADEIRA_DOCK_CEG=0 restores the previous direct LaunchApp.
+ */
+ if (wide_flag(L"MADEIRA_STEAM_HOST_CEG", L'1')) {
+ if (wide_flag(L"MADEIRA_DOCK_CEG", L'0')) o->event("ceg-disabled", 1);
+ else {
+ /* ml2000: Valve's client reaches its own client service through
+ * the service manager; start Wine's if this session lacks one.
+ * It stays up for the game run and is ended at host exit.
+ * MADEIRA_DOCK_CEG_SCM=0 restores the ml1990 behaviour.
+ */
+ int32_t scm = wide_flag(L"MADEIRA_DOCK_CEG_SCM", L'0') ? 0 : sh_ceg_scm_prepare(o, module);
+ if (scm) {
+ o->event("ceg-result", scm);
+ result = 49;
+ goto done;
+ }
+ result = prepare_custom_binaries(module, client_user, api, o, pipe, appid, layout);
+ if (result) goto done;
+ result = 42;
+ }
+ }
+ if (RegOpenKeyExW(HKEY_CURRENT_USER, L"Software\\Valve\\Steam\\ActiveProcess", 0,
+ KEY_QUERY_VALUE | KEY_SET_VALUE, &active) != ERROR_SUCCESS ||
+ RegOpenKeyExW(HKEY_LOCAL_MACHINE, L"Software\\Valve\\Steam", 0,
+ KEY_QUERY_VALUE | KEY_SET_VALUE | KEY_WOW64_32KEY, &machine) != ERROR_SUCCESS) goto done;
+ values[0] = (struct saved_value){.key=active, .name=L"pid"};
+ values[1] = (struct saved_value){.key=active, .name=L"ActiveUser"};
+ values[2] = (struct saved_value){.key=machine, .name=L"SteamPID"};
+ if (!publish(&values[0], GetCurrentProcessId()) ||
+ !publish(&values[1], (DWORD)steamid) || !publish(&values[2], GetCurrentProcessId())) goto done;
+ o->event("launch-client-discovery-published", 1);
+ SetConsoleCtrlHandler(on_control, TRUE);
+ uint64_t gameid = appid;
+ uint64_t call = ((launch_fn)(*(void ***)manager)[2])(manager, &gameid, launch_option, 0, user_arguments);
+ o->event("launch-request-submitted", call != 0);
+ if (!call) { result = 43; goto done; }
+ uint64_t begin = o->now_ms(), stopped_at = 0;
+ bool seen_running = false, result_received = false, result_rejected = false;
+ /* ml1970: a content refusal keeps Valve's client alive while it installs
+ * what the launch needs, then asks it again. It never turns a refusal
+ * into a launch: only Valve's own later success starts the game.
+ * MADEIRA_DOCK_CONTENT_WAIT=0 restores the immediate failure.
+ */
+ wchar_t wait_flag[4] = {0};
+ bool content_wait = !(GetEnvironmentVariableW(L"MADEIRA_DOCK_CONTENT_WAIT", wait_flag, 4) == 1 &&
+ wait_flag[0] == L'0');
+ /* ml2011: a configuration refusal right after sign-in waits for Valve's client to
+ * receive the app's configuration. MADEIRA_DOCK_CONFIG_WAIT=0 fails immediately.
+ */
+ wchar_t config_flag[4] = {0};
+ bool config_wait = !(GetEnvironmentVariableW(L"MADEIRA_DOCK_CONFIG_WAIT", config_flag, 4) == 1 &&
+ config_flag[0] == L'0');
+ uint64_t config_began = 0;
+ /* ml2015: "another session is playing" also comes back for a session that
+ * ended without telling Steam (the app was closed under a running game):
+ * Steam's servers keep it until that connection times out. The host asks
+ * again for a bounded time; a session that is really playing elsewhere
+ * still fails once the bound passes. MADEIRA_DOCK_SESSION_WAIT=0 fails
+ * immediately.
+ */
+ wchar_t session_flag[4] = {0};
+ bool session_wait = !(GetEnvironmentVariableW(L"MADEIRA_DOCK_SESSION_WAIT", session_flag, 4) == 1 &&
+ session_flag[0] == L'0');
+ uint64_t session_began = 0;
+ uint64_t wait_began = 0, retry_at = 0;
+ unsigned retries = 0;
+ int32_t logged_error = INT32_MIN;
+ /* ml2020: Valve's client stops reporting the game as running when the
+ * program it started exits, also when that program only handed over to a
+ * launcher that restarts itself or starts the game later. The game's own
+ * process tree is followed while it runs (hold.c); after the report ends,
+ * the session is held while a member still shows a window or is young.
+ * MADEIRA_DOCK_KEEP_ALIVE=0 ends it 3 s after the report as before; a
+ * `;` list of image names adds programs outside the tree to it.
+ */
+ static wchar_t keep_value[1024];
+ DWORD keep_length = GetEnvironmentVariableW(L"MADEIRA_DOCK_KEEP_ALIVE", keep_value, 1024);
+ if (keep_length >= 1024) keep_value[0] = 0;
+ enum sh_keep_alive_mode keep_mode = sh_keep_alive_mode(keep_length ? keep_value : NULL);
+ static struct sh_hold hold;
+ sh_hold_init(&hold, keep_mode == SH_KEEP_ALIVE_OFF ? NULL : keep_value);
+ uint64_t held_since = 0;
+ bool held = false;
+ result = 44;
+ while (!InterlockedCompareExchange(&interrupted, 0, 0)) {
+ for (unsigned batch = 0; batch < 64; ++batch) {
+ struct sh_callback cb = {0};
+ if (!api->get_callback(pipe, &cb)) break;
+ bool valid = cb.id > 0 && cb.size >= 0 && (!cb.size || cb.data);
+ if (valid && cb.id == 703 && cb.size >= 16) {
+ uint64_t finished; int32_t kind; uint32_t size;
+ memcpy(&finished, cb.data, 8);
+ memcpy(&kind, (char *)cb.data+8, 4);
+ memcpy(&size, (char *)cb.data+12, 4);
+ if (finished == call) {
+ /* Do not print the error-detail string: it can contain
+ * private paths. Only decode the fixed numeric result.
+ */
+ /* This client reports 524 bytes: 8-byte GameID, 4-byte
+ * EAppError and 512 detail bytes, without tail padding.
+ */
+ unsigned char payload[524] = {0};
+ bool failed = false;
+ bool read = kind == 1270027 && size == sizeof(payload) &&
+ ((call_result_fn)(*(void ***)engine)[33])(
+ engine, pipe, call, payload, sizeof(payload), kind, &failed);
+ int32_t error = -1;
+ bool decoded = read && !failed && sh_decode_launch_result(payload, size, gameid, &error);
+ bool missing_option = decoded && error == 22 && sh_launch_option_missing(payload, size, launch_option);
+ if (missing_option) o->event("launch-option-missing", (int32_t)launch_option);
+ /* Repeated requests while waiting report only changes,
+ * keeping the bounded report file small.
+ */
+ if (error != logged_error || !decoded) {
+ o->event("launch-result-kind", kind);
+ o->event("launch-result-size", (int32_t)size);
+ o->event("launch-client-error", error);
+ logged_error = error;
+ }
+ result_received = decoded && error == 0;
+ result_rejected = !result_received;
+ if (result_received && wait_began) o->event("launch-update-ready", (int32_t)retries);
+ if (!result_received && decoded && content_wait && !seen_running &&
+ sh_launch_error_waits_for_content(error) &&
+ (!wait_began || o->now_ms() - wait_began < SH_CONTENT_WAIT_MS)) {
+ if (!wait_began) {
+ wait_began = o->now_ms();
+ o->event("launch-update-wait", error);
+ }
+ retry_at = o->now_ms() + sh_launch_retry_delay_ms(retries);
+ result_rejected = false;
+ }
+ else if (!result_received && decoded && config_wait && !seen_running && !missing_option &&
+ sh_launch_error_waits_for_config(error) &&
+ (!config_began || o->now_ms() - config_began < SH_CONFIG_WAIT_MS)) {
+ if (!config_began) {
+ config_began = o->now_ms();
+ o->event("launch-config-wait", error);
+ }
+ retry_at = o->now_ms() + SH_CONFIG_RETRY_MS;
+ result_rejected = false;
+ }
+ else if (!result_received && decoded && session_wait && !seen_running &&
+ sh_launch_error_waits_for_session(error) &&
+ (!session_began || o->now_ms() - session_began < SH_SESSION_WAIT_MS)) {
+ if (!session_began) {
+ session_began = o->now_ms();
+ o->event("launch-session-wait", error);
+ }
+ retry_at = o->now_ms() + SH_SESSION_RETRY_MS;
+ result_rejected = false;
+ }
+ /* A game can start before this callback is decoded. Keep
+ * serving it until exit even if a result is rejected.
+ */
+ }
+ }
+ api->free_callback(pipe);
+ if (!valid) { result = SH_CALLBACK_INVALID; goto done; }
+ }
+ bool running = ((running_fn)(*(void ***)client_user)[67])(client_user, &gameid);
+ if (running && !seen_running) {
+ o->event("launch-game-running", 1);
+ seen_running = true;
+ retry_at = 0;
+ }
+ bool holding = false;
+ if (keep_mode != SH_KEEP_ALIVE_OFF && seen_running) {
+ /* Polled while the game runs too, so the tree is known by the time
+ * the report ends; at most one snapshot a second. */
+ holding = sh_hold_poll(&hold, o) && !running;
+ if (holding && !held) {
+ held = true;
+ held_since = o->now_ms();
+ o->event("launch-keep-alive", (int32_t)hold.holders);
+ }
+ }
+ if (running || holding) stopped_at = 0;
+ else if (seen_running) {
+ if (!stopped_at) stopped_at = o->now_ms();
+ if (o->now_ms() - stopped_at >= 3000) {
+ if (held) o->event("launch-keep-alive-held", (int32_t)((o->now_ms() - held_since) / 1000));
+ o->event("launch-game-ended", 1);
+ result = result_received && !result_rejected ? 0 : 46;
+ break;
+ }
+ }
+ if (retry_at && !seen_running && o->now_ms() >= retry_at) {
+ retry_at = 0;
+ call = ((launch_fn)(*(void ***)manager)[2])(manager, &gameid, launch_option, 0, user_arguments);
+ ++retries;
+ if (retries <= 3 || retries % 60 == 0) o->event("launch-update-retry", (int32_t)retries);
+ if (!call) { result = 43; goto done; }
+ begin = o->now_ms();
+ }
+ if (retry_at) { o->sleep_ms(50); continue; }
+ if (!seen_running && result_rejected && o->now_ms() - begin > 5000) {
+ if (config_began) o->event("launch-config-gave-up", (int32_t)retries);
+ if (session_began) o->event("launch-session-gave-up", (int32_t)retries);
+ result = wait_began ? 48 : 45;
+ break;
+ }
+ if (!seen_running && o->now_ms() - begin > 90000) break;
+ o->sleep_ms(50);
+ }
+done:
+ SetConsoleCtrlHandler(on_control, FALSE);
+ bool restored = true;
+ /* Another Steam process may have claimed registration while this host was
+ * alive. Never restore account metadata over a different current PID.
+ */
+ if (values[0].changed) {
+ DWORD current = 0, bytes = sizeof(current), type = 0;
+ if (RegQueryValueExW(active, L"pid", NULL, &type, (BYTE *)¤t, &bytes) != ERROR_SUCCESS ||
+ type != REG_DWORD || current != GetCurrentProcessId()) restored = false;
+ }
+ if (restored)
+ for (int i = 2; i >= 0; --i) if (!restore(&values[i])) restored = false;
+ o->event("launch-discovery-restored", restored);
+ if (machine) RegCloseKey(machine);
+ if (active) RegCloseKey(active);
+ if (!restored) result = 47;
+ o->event("launch-host-result", result);
+ return result;
+}
+#else
+int sh_launch(HMODULE module, void *engine, void *client_user,
+ const struct sh_api *api, const struct sh_observer *o,
+ int32_t pipe, int32_t user, uint64_t steamid, uint32_t appid,
+ const struct dock_client_layout *layout)
+{
+ (void)module; (void)engine; (void)client_user; (void)api; (void)o;
+ (void)pipe; (void)user; (void)steamid; (void)appid; (void)layout;
+ return 40;
+}
+#endif
diff --git a/server/dock/src/launch.h b/server/dock/src/launch.h
new file mode 100644
index 00000000..e601aa91
--- /dev/null
+++ b/server/dock/src/launch.h
@@ -0,0 +1,11 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ * Copyright 2026 125hz
+ * Madeira Converter Exception: see LICENSE-EXCEPTION.md */
+#ifndef MADEIRA_STEAM_HOST_LAUNCH_H
+#define MADEIRA_STEAM_HOST_LAUNCH_H
+#include "session.h"
+int sh_launch(HMODULE module, void *engine, void *client_user,
+ const struct sh_api *api, const struct sh_observer *o,
+ int32_t pipe, int32_t user, uint64_t steamid, uint32_t appid,
+ const struct dock_client_layout *layout);
+#endif
diff --git a/server/dock/src/main.c b/server/dock/src/main.c
new file mode 100644
index 00000000..6f04ab66
--- /dev/null
+++ b/server/dock/src/main.c
@@ -0,0 +1,340 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ * Copyright 2026 125hz
+ * Madeira Converter Exception: see LICENSE-EXCEPTION.md
+ * ml1820: native Windows milestone for a host of Valve's genuine client.
+ * No Valve binaries are bundled with this program. Opt-in session mode calls
+ * independently verified private methods only for an exact client SHA-256;
+ * shutdown uses the versioned public SteamClient021 interface.
+ * Export presence, engine construction and global-user construction
+ * are separate observations; none establishes authentication or game ownership.
+ */
+#define WIN32_LEAN_AND_MEAN
+#include
+#include
+#include
+#include
+#include
+#include
+#include "probe.h"
+#include "session.h"
+#include "scm.h"
+#include "validation.h"
+
+#define PATH_CAP 32768
+static FILE *report;
+static const struct dock_client_layout *client_layout;
+
+static void event(const char *stage, int32_t value)
+{
+ const char *round = !strncmp(stage, "game-scm", 8) || !strncmp(stage, "launch-keep-alive", 17) ? "ml2020" :
+ !strncmp(stage, "install-scm", 11) ? "ml2014" :
+ !strncmp(stage, "ceg-scm", 7) || !strncmp(stage, "ceg-service-", 12) ? "ml2000" :
+ !strncmp(stage, "ceg-", 4) ? "ml1990" :
+ !strncmp(stage, "launch-update-", 14) ? "ml1970" :
+ !strncmp(stage, "launch-config-", 14) ? "ml2011" :
+ !strncmp(stage, "launch-session-", 15) ? "ml2015" :
+ !strncmp(stage, "session-offline-", 16) ? "ml2016" :
+ !strncmp(stage, "session-handoff-", 16) ? "ml1870" :
+ !strcmp(stage, "session-client-adapter") ? "ml1860" : "ml1830";
+ fprintf(stderr, "[steam-host] %s %s=%ld\n", round, stage, (long)value);
+ fflush(stderr);
+ if (report) {
+ fprintf(report, "[steam-host] %s %s=%ld\n", round, stage, (long)value);
+ fflush(report);
+ }
+}
+
+static bool enabled(const wchar_t *name)
+{
+ wchar_t value[4];
+ return GetEnvironmentVariableW(name, value, 4) == 1 && value[0] == L'1';
+}
+
+static bool client_directory(wchar_t *directory)
+{
+ DWORD count = GetEnvironmentVariableW(L"MADEIRA_STEAM_HOST_CLIENT_DIR", directory, PATH_CAP);
+ if (count >= PATH_CAP) return false;
+ if (!count) {
+ DWORD bytes = PATH_CAP * sizeof(wchar_t);
+ LSTATUS status = RegGetValueW(HKEY_CURRENT_USER, L"Software\\Valve\\Steam",
+ L"SteamPath", RRF_RT_REG_SZ, NULL, directory, &bytes);
+ if (status != ERROR_SUCCESS)
+ wcscpy(directory, L"C:\\Program Files (x86)\\Steam");
+ }
+ /* Only a local absolute DOS path, with space for the fixed DLL basename.
+ * A relative path would let the selected game's working directory decide
+ * which client library gets loaded.
+ */
+ size_t length = wcslen(directory);
+ if (length < 3 || length + 32 >= PATH_CAP || directory[1] != L':' ||
+ (directory[2] != L'\\' && directory[2] != L'/')) return false;
+ if (!((directory[0] >= L'A' && directory[0] <= L'Z') ||
+ (directory[0] >= L'a' && directory[0] <= L'z'))) return false;
+ return true;
+}
+
+static bool no_other_client(void)
+{
+ HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
+ if (snapshot == INVALID_HANDLE_VALUE) return false;
+ PROCESSENTRY32W process = {0};
+ process.dwSize = sizeof(process);
+ bool clear = true;
+ if (!Process32FirstW(snapshot, &process)) {
+ CloseHandle(snapshot);
+ return false;
+ }
+ do {
+ if (process.th32ProcessID == GetCurrentProcessId()) continue;
+ if (!_wcsicmp(process.szExeFile, L"steam.exe") ||
+ !_wcsicmp(process.szExeFile, L"steamwebhelper.exe") ||
+ !_wcsicmp(process.szExeFile, L"steamhost64.exe") ||
+ !_wcsicmp(process.szExeFile, L"madeira-steamhost-probe.exe")) {
+ clear = false;
+ break;
+ }
+ } while (Process32NextW(snapshot, &process));
+ if (clear && GetLastError() != ERROR_NO_MORE_FILES) clear = false;
+ CloseHandle(snapshot);
+ return clear;
+}
+
+static bool identify_client(HANDLE file)
+{
+ IMAGE_DOS_HEADER dos;
+ IMAGE_FILE_HEADER header;
+ DWORD read = 0, signature = 0;
+ LARGE_INTEGER length, offset;
+ if (!GetFileSizeEx(file, &length) || length.QuadPart < 64 ||
+ !ReadFile(file, &dos, sizeof(dos), &read, NULL) || read != sizeof(dos) ||
+ dos.e_magic != IMAGE_DOS_SIGNATURE || dos.e_lfanew < (LONG)sizeof(dos) ||
+ (LONGLONG)dos.e_lfanew + 4 + (LONGLONG)sizeof(header) > length.QuadPart)
+ return false;
+ offset.QuadPart = dos.e_lfanew;
+ if (!SetFilePointerEx(file, offset, NULL, FILE_BEGIN) ||
+ !ReadFile(file, &signature, 4, &read, NULL) || read != 4 || signature != IMAGE_NT_SIGNATURE ||
+ !ReadFile(file, &header, sizeof(header), &read, NULL) || read != sizeof(header))
+ return false;
+ event("client-machine", header.Machine);
+ event("client-pe-timestamp", (int32_t)header.TimeDateStamp);
+#ifdef _WIN64
+ if (header.Machine != IMAGE_FILE_MACHINE_AMD64) return false;
+#else
+ if (header.Machine != IMAGE_FILE_MACHINE_I386) return false;
+#endif
+ if (!(header.Characteristics & IMAGE_FILE_DLL)) return false;
+
+ /* SHA-256 identifies the exact file for subsequent ABI research. It is
+ * not an Authenticode check and is not proof that a file came from Valve.
+ * The open handle disallows writes/deletes while this probe uses the DLL.
+ */
+ HCRYPTPROV provider = 0;
+ HCRYPTHASH hash = 0;
+ unsigned char buffer[32768], digest[32];
+ char hex[65];
+ DWORD size = sizeof(digest);
+ bool ok = false;
+ offset.QuadPart = 0;
+ if (!SetFilePointerEx(file, offset, NULL, FILE_BEGIN) ||
+ !CryptAcquireContextW(&provider, NULL, NULL, PROV_RSA_AES, CRYPT_VERIFYCONTEXT) ||
+ !CryptCreateHash(provider, CALG_SHA_256, 0, 0, &hash)) goto done;
+ for (;;) {
+ if (!ReadFile(file, buffer, sizeof(buffer), &read, NULL)) goto done;
+ if (!read) break;
+ if (!CryptHashData(hash, buffer, read, 0)) goto done;
+ }
+ if (!CryptGetHashParam(hash, HP_HASHVAL, digest, &size, 0) || size != 32) goto done;
+ for (unsigned i = 0; i < 32; ++i) sprintf(hex + i * 2, "%02x", digest[i]);
+ client_layout = dock_client_layout(hex);
+ if (client_layout && client_layout->revision == 202601) {
+ const char *compat = getenv("MADEIRA_DOCK_CLIENT_202601");
+ if (compat && !strcmp(compat, "0")) client_layout = NULL;
+ }
+ event("session-client-adapter", client_layout ? client_layout->revision : 0);
+ fprintf(stderr, "[steam-host] ml1820 client-sha256=%s\n", hex);
+ fflush(stderr);
+ if (report) {
+ fprintf(report, "[steam-host] ml1820 client-sha256=%s\n", hex);
+ fflush(report);
+ }
+ ok = true;
+done:
+ if (hash) CryptDestroyHash(hash);
+ if (provider) CryptReleaseContext(provider, 0);
+ return ok;
+}
+
+static FARPROC symbol(HMODULE module, const char *name)
+{
+ FARPROC address = GetProcAddress(module, name);
+ event(name, address != NULL);
+ return address;
+}
+
+static uint64_t now_ms(void) { return GetTickCount64(); }
+/* Alertable: the host's own overlapped completions (and any user APC) run
+ * during the poll pause instead of waiting for a later blocking wait. */
+static void sleep_ms(uint32_t ms) { SleepEx(ms, TRUE); }
+static const struct sh_observer host_observer = {now_ms, sleep_ms, event};
+
+/* BShutdownIfAllPipesClosed is slot 23 in the public SteamClient021 ABI,
+ * including GetISteamGameSearch and the reserved RunFrame slot. Verified
+ * against ValveSoftware/Proton steamworks_sdk_162/isteamclient.h. Never apply
+ * this layout to CLIENTENGINE_INTERFACE_VERSION005 or an arbitrary version.
+ */
+typedef bool (__thiscall *sh_shutdown_fn)(void *client);
+static bool shutdown_client(void *client)
+{
+ void **methods = *(void ***)client;
+ return ((sh_shutdown_fn)methods[23])(client);
+}
+
+#define SH_INSTALL_SCM_STEP_MS 20000 /* ml2015 */
+static volatile int32_t install_scm_outcome;
+
+static DWORD WINAPI install_scm_worker(void *unused)
+{
+ (void)unused;
+ install_scm_outcome = sh_install_scm_start(&host_observer);
+ return 0;
+}
+
+int main(int argc, char **argv)
+{
+ static wchar_t directory[PATH_CAP], path[PATH_CAP];
+ HANDLE mutex = NULL, file = INVALID_HANDLE_VALUE;
+ void *public_client = NULL;
+ int result = 20;
+
+ /* ml2014: Madeira's one-time-install batch runs this before a game's
+ * installers. No Steam client is loaded; the one stdout line ("services
+ * started|already|failed|off") goes to the batch's result file. Exit 0
+ * always: installers run either way.
+ */
+ if (argc == 2 && !strcmp(argv[1], "--start-services")) {
+ /* ml2015: a service manager that never answered its RPC pipe left
+ * OpenSCManager blocked, and the batch (and the game) waited forever.
+ * The step runs on a worker thread for at most SH_INSTALL_SCM_STEP_MS;
+ * then it reports "services timeout" and this process ends at once
+ * (the blocked call may hold loader or RPC locks, so no exit cleanup).
+ */
+ HANDLE worker = CreateThread(NULL, 0, install_scm_worker, NULL, 0, NULL);
+ if (!worker) {
+ printf("services %s\n", sh_install_scm_word(sh_install_scm_start(&host_observer)));
+ fflush(stdout);
+ return 0;
+ }
+ if (WaitForSingleObject(worker, SH_INSTALL_SCM_STEP_MS) != WAIT_OBJECT_0) {
+ printf("services timeout\n");
+ fflush(stdout);
+ TerminateProcess(GetCurrentProcess(), 0);
+ }
+ CloseHandle(worker);
+ printf("services %s\n", sh_install_scm_word(install_scm_outcome));
+ fflush(stdout);
+ return 0;
+ }
+
+ if (!enabled(L"MADEIRA_STEAM_HOST_PROBE")) {
+ event("disabled-set-MADEIRA_STEAM_HOST_PROBE", 0);
+ return 2;
+ }
+ /* This log is separate from Steam's own logs and contains no tokens,
+ * usernames, SteamIDs, paths, environment dump, or callback payloads.
+ */
+ DWORD log_length = GetEnvironmentVariableW(L"MADEIRA_STEAM_HOST_LOG", path, PATH_CAP);
+ if (!log_length) wcscpy(path, L"C:\\madeira-steamhost-probe.txt");
+ if (log_length < PATH_CAP) report = _wfopen(path, L"w");
+ event("probe-start-bits", (int32_t)(sizeof(void *) * 8));
+ mutex = CreateMutexW(NULL, FALSE, L"Local\\MadeiraSteamHostProbe");
+ if (!mutex || GetLastError() == ERROR_ALREADY_EXISTS) {
+ event("another-probe-or-mutex-error", 1);
+ goto done;
+ }
+ if (!client_directory(directory)) {
+ event("invalid-client-directory", 1);
+ goto done;
+ }
+ if (!no_other_client()) {
+ event("another-client-or-process-query-error", 1);
+ goto done;
+ }
+ wcscpy(path, directory);
+#ifdef _WIN64
+ wcscat(path, L"\\steamclient64.dll");
+#else
+ wcscat(path, L"\\steamclient.dll");
+#endif
+ file = CreateFileW(path, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
+ if (file == INVALID_HANDLE_VALUE || !identify_client(file)) {
+ event("client-file-or-identity-error", (int32_t)GetLastError());
+ goto done;
+ }
+ if (!SetCurrentDirectoryW(directory)) {
+ event("client-working-directory-error", (int32_t)GetLastError());
+ goto done;
+ }
+ /* Restrict dependency search to the client directory and system32. No
+ * fallback to a current-directory LoadLibrary or to a renamed client DLL.
+ */
+ event("load-client-begin", 0);
+ HMODULE module = LoadLibraryExW(path, NULL,
+ LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_SYSTEM32);
+ if (!module) {
+ event("load-client-error", (int32_t)GetLastError());
+ goto done;
+ }
+ struct sh_api api = {
+ (int32_t (SH_CALL *)(int32_t *))symbol(module, "Steam_CreateGlobalUser"),
+ (void (SH_CALL *)(int32_t, int32_t))symbol(module, "Steam_ReleaseUser"),
+ (bool (SH_CALL *)(int32_t))symbol(module, "Steam_BReleaseSteamPipe"),
+ (bool (SH_CALL *)(int32_t, struct sh_callback *))symbol(module, "Steam_BGetCallback"),
+ (void (SH_CALL *)(int32_t))symbol(module, "Steam_FreeLastCallback"),
+ (bool (SH_CALL *)(int32_t, int32_t))symbol(module, "Steam_BLoggedOn")
+ };
+ void *(SH_CALL *factory)(const char *, int *) =
+ (void *(SH_CALL *)(const char *, int *))symbol(module, "CreateInterface");
+ if (!factory || !api.create_global_user || !api.release_user || !api.release_pipe ||
+ !api.get_callback || !api.free_callback || !api.logged_on) goto done;
+ int factory_result = -1;
+ public_client = factory("SteamClient021", &factory_result);
+ event("public-client021-present", public_client != NULL);
+ if (!public_client) goto done;
+ event("engine-factory-begin", 0);
+ void *engine = factory("CLIENTENGINE_INTERFACE_VERSION005", &factory_result);
+ event("engine005-present", engine != NULL);
+ event("engine-factory-result", factory_result);
+ if (!engine) goto done;
+
+ if (enabled(L"MADEIRA_STEAM_HOST_SESSION")) {
+ result = sh_session(module, engine, &api, &host_observer, client_layout);
+ } else if (enabled(L"MADEIRA_STEAM_HOST_BOOTSTRAP")) {
+ result = sh_probe_bootstrap(&api, &host_observer);
+ } else {
+ event("bootstrap-disabled", 1);
+ result = SH_OK;
+ }
+ /* Never unload an initialized client DLL while its internal workers may
+ * still be alive. The guest process owns it until process/session teardown.
+ * Full engine shutdown and repeated sessions need separate device evidence.
+ */
+done:
+ if (public_client) {
+ event("shutdown-begin", 0);
+ bool stopped = shutdown_client(public_client);
+ event("shutdown-complete", stopped ? 1 : 0);
+ if (!stopped && result == SH_OK) result = SH_RELEASE_FAILED;
+ }
+ /* ml2000: after Valve's client has shut down, end the service manager
+ * this host started for CEG (no-op when it was already running), so a
+ * leftover service process cannot keep the app's session alive.
+ */
+ sh_ceg_scm_release(&host_observer);
+ if (!enabled(L"MADEIRA_STEAM_HOST_SESSION"))
+ event("ownership-unchecked-game-launch-disabled", 1);
+ event("probe-result", result);
+ if (file != INVALID_HANDLE_VALUE) CloseHandle(file);
+ if (mutex) CloseHandle(mutex);
+ if (report) fclose(report);
+ return result;
+}
diff --git a/server/dock/src/probe.c b/server/dock/src/probe.c
new file mode 100644
index 00000000..5435e7c4
--- /dev/null
+++ b/server/dock/src/probe.c
@@ -0,0 +1,68 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ * Copyright 2026 125hz
+ * Madeira Converter Exception: see LICENSE-EXCEPTION.md */
+#include "probe.h"
+#include
+
+_Static_assert(offsetof(struct sh_callback, data) == 8, "callback payload offset");
+_Static_assert(sizeof(struct sh_callback) == (sizeof(void *) == 8 ? 24 : 16),
+ "Windows callback packing");
+
+int sh_probe_bootstrap(const struct sh_api *api, const struct sh_observer *o)
+{
+ int32_t pipe = 0, user;
+ int result = SH_OK, callbacks = 0;
+ uint64_t start;
+
+ if (!api || !o || !api->create_global_user || !api->release_user ||
+ !api->release_pipe || !api->get_callback || !api->free_callback ||
+ !api->logged_on || !o->now_ms || !o->sleep_ms || !o->event)
+ return SH_BAD_API;
+
+ o->event("create-global-user-begin", 0);
+ user = api->create_global_user(&pipe);
+ if (user <= 0 || pipe <= 0) {
+ o->event("create-global-user-failed", 0);
+ /* A failed creation may still allocate a pipe. Release only handles
+ * returned by this call; never attach to another client's global user.
+ */
+ result = SH_CREATE_FAILED;
+ goto cleanup;
+ }
+ o->event("global-user-created", 1);
+ o->event("logged-on-not-ownership", api->logged_on(user, pipe) ? 1 : 0);
+
+ start = o->now_ms();
+ /* Bound both time and iteration count. A busy callback queue must not
+ * starve the deadline; a stalled clock must not cause an endless probe.
+ * These limits cannot interrupt a blocked call inside Valve's DLL.
+ */
+ for (unsigned tick = 0; tick < 250 && o->now_ms() - start < 5000; ++tick) {
+ for (unsigned batch = 0; batch < 64; ++batch) {
+ struct sh_callback msg = {0};
+ if (!api->get_callback(pipe, &msg)) break;
+ ++callbacks;
+ /* Release each borrowed buffer exactly once, including malformed
+ * callbacks. Do not dereference its payload or infer a licence.
+ */
+ bool valid = msg.id > 0 && msg.size >= 0 && (!msg.size || msg.data);
+ if (callbacks <= 8) o->event("callback-id", msg.id);
+ api->free_callback(pipe);
+ if (!valid) {
+ result = SH_CALLBACK_INVALID;
+ goto cleanup;
+ }
+ }
+ o->sleep_ms(20);
+ }
+ o->event("callback-count", callbacks);
+ o->event("logged-on-not-ownership", api->logged_on(user, pipe) ? 1 : 0);
+
+cleanup:
+ o->event("release-begin", 0);
+ if (pipe > 0 && user > 0) api->release_user(pipe, user);
+ if (pipe > 0 && !api->release_pipe(pipe) && result == SH_OK)
+ result = SH_RELEASE_FAILED;
+ o->event("bootstrap-result", result);
+ return result;
+}
diff --git a/server/dock/src/probe.h b/server/dock/src/probe.h
new file mode 100644
index 00000000..07a872a4
--- /dev/null
+++ b/server/dock/src/probe.h
@@ -0,0 +1,58 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ * Copyright 2026 125hz
+ * Madeira Converter Exception: see LICENSE-EXCEPTION.md
+ * ml1810: exported-API bootstrap experiment for an installed Steam client.
+ * This is a diagnostic host, not a game launcher or an ownership authority.
+ */
+#ifndef MADEIRA_STEAM_HOST_PROBE_H
+#define MADEIRA_STEAM_HOST_PROBE_H
+
+#include
+#include
+
+#ifdef _WIN32
+#define SH_CALL __cdecl
+#else
+#define SH_CALL
+#endif
+
+/* Native Windows callback layout (default packing: 8). No payload is decoded
+ * or logged: callbacks may contain account information and authentication data.
+ * The handle and callback layout are described by OpenSteamworks; see README.
+ */
+struct sh_callback {
+ int32_t user;
+ int32_t id;
+ void *data;
+ int32_t size;
+};
+
+struct sh_api {
+ int32_t (SH_CALL *create_global_user)(int32_t *pipe);
+ void (SH_CALL *release_user)(int32_t pipe, int32_t user);
+ bool (SH_CALL *release_pipe)(int32_t pipe);
+ bool (SH_CALL *get_callback)(int32_t pipe, struct sh_callback *callback);
+ void (SH_CALL *free_callback)(int32_t pipe);
+ bool (SH_CALL *logged_on)(int32_t user, int32_t pipe);
+};
+
+struct sh_observer {
+ uint64_t (*now_ms)(void);
+ void (*sleep_ms)(uint32_t milliseconds);
+ void (*event)(const char *stage, int32_t value);
+};
+
+enum sh_result {
+ SH_OK = 0, /* bootstrap only; never authorization */
+ SH_BAD_API = 10,
+ SH_CREATE_FAILED = 11,
+ SH_CALLBACK_INVALID = 12,
+ SH_RELEASE_FAILED = 13
+};
+
+/* All Steam calls execute on one thread. This never logs on, logs off,
+ * revokes credentials, publishes ActiveProcess, or starts a game.
+ */
+int sh_probe_bootstrap(const struct sh_api *api, const struct sh_observer *observer);
+
+#endif
diff --git a/server/dock/src/scm.c b/server/dock/src/scm.c
new file mode 100644
index 00000000..6e958631
--- /dev/null
+++ b/server/dock/src/scm.c
@@ -0,0 +1,380 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ * Copyright 2026 125hz
+ * Madeira Converter Exception: see LICENSE-EXCEPTION.md
+ * ml2000: Valve's client performs custom-executable (CEG) preparation
+ * through its own installed client service, which it demand-starts through
+ * the Windows service manager. A Dock session runs only this host, so Wine's
+ * service manager may not be running; desktop routes start it themselves.
+ * This file starts only Wine's standard service manager and checks, read-only,
+ * that Valve's service is registered; if not, it runs Valve's own service
+ * installer as Valve's client would. Dock itself never creates, registers,
+ * configures or starts any service, and logs only numeric results.
+ */
+#define WIN32_LEAN_AND_MEAN
+#include
+#include
+#include
+#include
+#include "scm.h"
+#include "validation.h"
+
+#define SH_SCM_START_MS 30000ULL
+#define SH_SERVICE_STOP_MS 15000ULL
+#define SH_SERVICE_CONTROL_RETRY_MS 1000ULL
+#define SH_PROCESS_EXIT_MS 5000
+#define SH_SERVICE_INSTALL_MS 60000
+
+static const wchar_t steam_service[] = L"Steam Client Service";
+/* Wine's include/wine/svcctl.idl SVCCTL_STARTED_EVENT: services.exe sets this
+ * manual-reset event once its \pipe\svcctl RPC endpoint listens. wineboot
+ * creates it before starting services.exe and waits for it the same way.
+ */
+static const wchar_t started_event_name[] = L"__wine_SvcctlStartedEvent";
+
+/* The service manager this host started; NULL when it was already running. */
+static HANDLE manager_process;
+
+static DWORD start_manager(const struct sh_observer *o, SC_HANDLE *manager, const char *started_stage)
+{
+ wchar_t directory[MAX_PATH], path[MAX_PATH + 16];
+ UINT length = GetSystemDirectoryW(directory, MAX_PATH);
+ if (!length || length >= MAX_PATH) return ERROR_PATH_NOT_FOUND;
+ wcscpy(path, directory);
+ wcscat(path, L"\\services.exe");
+ uint64_t begin = o->now_ms();
+ HANDLE started = CreateEventW(NULL, TRUE, FALSE, started_event_name);
+ /* An existing event means another launcher is already starting one:
+ * never run a second service manager, only wait for that one.
+ */
+ bool other = started && GetLastError() == ERROR_ALREADY_EXISTS;
+ HANDLE process = NULL;
+ if (!other) {
+ STARTUPINFOW startup = {0};
+ PROCESS_INFORMATION info = {0};
+ startup.cb = sizeof(startup);
+ if (!CreateProcessW(path, NULL, NULL, NULL, FALSE, DETACHED_PROCESS, NULL,
+ directory, &startup, &info)) {
+ DWORD error = GetLastError();
+ if (started) CloseHandle(started);
+ return error;
+ }
+ CloseHandle(info.hThread);
+ manager_process = process = info.hProcess;
+ o->event(started_stage, 1);
+ }
+ HANDLE handles[2];
+ DWORD count = 0;
+ if (started) handles[count++] = started;
+ if (process) handles[count++] = process;
+ /* Wine's services.exe sets the started event once its RPC endpoint
+ * listens, but a manager that answers is started whether or not the
+ * event reaches this waiter: on Madeira's iOS port it was seen never to
+ * arrive while the new manager already answered other clients within a
+ * second. So the wait runs in short slices and the manager is asked
+ * between them; the event, the process's exit and the bound end it as
+ * before.
+ */
+ while (count) {
+ uint32_t left = sh_remaining_ms(o->now_ms(), begin, SH_SCM_START_MS);
+ DWORD wait = WaitForMultipleObjects(count, handles, FALSE, sh_scm_poll_slice_ms(left));
+ if (process && wait == WAIT_OBJECT_0 + count - 1) {
+ if (started) CloseHandle(started);
+ return ERROR_PROCESS_ABORTED;
+ }
+ if (wait == WAIT_OBJECT_0 || !left) break;
+ if (wait == WAIT_FAILED) o->sleep_ms(sh_scm_poll_slice_ms(left));
+ *manager = OpenSCManagerW(NULL, NULL, SC_MANAGER_CONNECT);
+ if (*manager) {
+ if (started) CloseHandle(started);
+ return 0;
+ }
+ DWORD error = GetLastError();
+ if (!sh_scm_error_retryable(error)) {
+ if (started) CloseHandle(started);
+ return error;
+ }
+ }
+ if (started) CloseHandle(started);
+ for (;;) {
+ *manager = OpenSCManagerW(NULL, NULL, SC_MANAGER_CONNECT);
+ if (*manager) return 0;
+ DWORD error = GetLastError();
+ if (!sh_scm_error_retryable(error)) return error;
+ if (process && WaitForSingleObject(process, 0) == WAIT_OBJECT_0) return ERROR_PROCESS_ABORTED;
+ if (!sh_remaining_ms(o->now_ms(), begin, SH_SCM_START_MS)) return ERROR_TIMEOUT;
+ o->sleep_ms(100);
+ }
+}
+
+/* Read-only registration check; *missing is true only for "does not exist". */
+static bool service_registered(const struct sh_observer *o, SC_HANDLE manager, bool *missing)
+{
+ SC_HANDLE service = OpenServiceW(manager, steam_service, SERVICE_QUERY_STATUS);
+ bool registered = service != NULL;
+ DWORD error = registered ? 0 : GetLastError();
+ *missing = error == ERROR_SERVICE_DOES_NOT_EXIST;
+ o->event("ceg-service-registered", registered);
+ if (!registered && !*missing) o->event("ceg-scm-error", (int32_t)error);
+ if (service) CloseServiceHandle(service);
+ return registered;
+}
+
+/* ml2000: when Valve's service is not registered, run Valve's own service
+ * installer exactly as Valve's client does when it finds the service missing
+ * (static inspection of both pinned client builds: GetModuleFileName of the
+ * Steam process, "%s\bin\SteamService.exe", ShellExecuteEx "open" with
+ * "/install", working directory the Steam folder, then wait). Dock's process
+ * is not in the Steam folder, so the folder of the loaded genuine client DLL
+ * is used; Valve's install-script launcher uses the same bin\SteamService.exe
+ * under the Steam install folder. Valve's binary registers Valve's service;
+ * Dock writes no service keys and creates no service. Returns the installer's
+ * exit code, -1 on timeout (installer ended) or -2 if the file is missing.
+ */
+static int32_t install_client_service(const struct sh_observer *o, HMODULE client)
+{
+ static wchar_t folder[32768], path[32768 + 32], command[32768 + 48];
+ DWORD length = GetModuleFileNameW(client, folder, 32768);
+ if (!client || !length || length >= 32768) return sh_service_install_report(false, false, 0);
+ wchar_t *slash = wcsrchr(folder, L'\\');
+ if (!slash || slash == folder) return sh_service_install_report(false, false, 0);
+ *slash = 0;
+ wcscpy(path, folder);
+ wcscat(path, L"\\bin\\SteamService.exe");
+ DWORD attributes = GetFileAttributesW(path);
+ if (attributes == INVALID_FILE_ATTRIBUTES || (attributes & FILE_ATTRIBUTE_DIRECTORY))
+ return sh_service_install_report(false, false, 0);
+ wcscpy(command, L"\"");
+ wcscat(command, path);
+ wcscat(command, L"\" /install");
+ STARTUPINFOW startup = {0};
+ PROCESS_INFORMATION info = {0};
+ startup.cb = sizeof(startup);
+ if (!CreateProcessW(path, command, NULL, NULL, FALSE, DETACHED_PROCESS, NULL, folder,
+ &startup, &info)) {
+ o->event("ceg-scm-error", (int32_t)GetLastError());
+ return sh_service_install_report(true, true, (uint32_t)-3);
+ }
+ CloseHandle(info.hThread);
+ bool finished = WaitForSingleObject(info.hProcess, SH_SERVICE_INSTALL_MS) == WAIT_OBJECT_0;
+ DWORD code = 0;
+ if (!finished) {
+ /* A stuck installer would keep the app's session alive; fail closed. */
+ if (TerminateProcess(info.hProcess, 1)) WaitForSingleObject(info.hProcess, SH_PROCESS_EXIT_MS);
+ } else if (!GetExitCodeProcess(info.hProcess, &code)) code = (DWORD)-3;
+ CloseHandle(info.hProcess);
+ return sh_service_install_report(true, finished, code);
+}
+
+static bool wide_flag(const wchar_t *name, wchar_t expected)
+{
+ wchar_t value[4] = {0};
+ return GetEnvironmentVariableW(name, value, 4) == 1 && value[0] == expected;
+}
+
+int32_t sh_ceg_scm_prepare(const struct sh_observer *o, HMODULE client)
+{
+ SC_HANDLE manager = OpenSCManagerW(NULL, NULL, SC_MANAGER_CONNECT);
+ DWORD error = manager ? 0 : GetLastError();
+ if (!manager && !manager_process && sh_scm_error_means_absent(error))
+ error = start_manager(o, &manager, "ceg-scm-started");
+ o->event("ceg-scm", manager != NULL);
+ if (!manager) {
+ o->event("ceg-scm-error", (int32_t)error);
+ return sh_ceg_scm_result(false, false);
+ }
+ bool missing = false;
+ bool registered = service_registered(o, manager, &missing);
+ /* MADEIRA_DOCK_CEG_SERVICE_INSTALL=0 keeps the fail-fast -5. */
+ if (sh_should_install_service(registered, missing,
+ !wide_flag(L"MADEIRA_DOCK_CEG_SERVICE_INSTALL", L'0'))) {
+ o->event("ceg-service-install", install_client_service(o, client));
+ registered = service_registered(o, manager, &missing);
+ }
+ CloseServiceHandle(manager);
+ return sh_ceg_scm_result(true, registered);
+}
+
+static bool query_state(SC_HANDLE service, SERVICE_STATUS_PROCESS *status)
+{
+ DWORD needed = 0;
+ return QueryServiceStatusEx(service, SC_STATUS_PROCESS_INFO, (BYTE *)status,
+ sizeof(*status), &needed);
+}
+
+/* Stop Valve's client service only through the service manager. A service
+ * process that outlives the bound would keep the app's session alive, so the
+ * process this host's manager started for it is then ended.
+ */
+static enum sh_service_stop stop_client_service(const struct sh_observer *o)
+{
+ SC_HANDLE manager = OpenSCManagerW(NULL, NULL, SC_MANAGER_CONNECT);
+ if (!manager) return SH_SERVICE_STOP_FAILED;
+ SC_HANDLE service = OpenServiceW(manager, steam_service, SERVICE_STOP | SERVICE_QUERY_STATUS);
+ if (!service) {
+ DWORD error = GetLastError();
+ CloseServiceHandle(manager);
+ return error == ERROR_SERVICE_DOES_NOT_EXIST ? SH_SERVICE_NOT_RUNNING : SH_SERVICE_STOP_FAILED;
+ }
+ SERVICE_STATUS_PROCESS status = {0};
+ bool known = query_state(service, &status);
+ bool running = !known || status.dwCurrentState != SERVICE_STOPPED;
+ HANDLE process = NULL;
+ if (known && running && status.dwProcessId)
+ process = OpenProcess(SYNCHRONIZE | PROCESS_TERMINATE, FALSE, status.dwProcessId);
+ bool stopped = !running, gone = false, ended = false;
+ uint64_t begin = o->now_ms(), control_at = 0;
+ bool controlled = false;
+ while (running && !stopped && sh_remaining_ms(o->now_ms(), begin, SH_SERVICE_STOP_MS)) {
+ if (query_state(service, &status) && status.dwCurrentState == SERVICE_STOPPED) {
+ stopped = true;
+ break;
+ }
+ /* A start- or stop-pending service may refuse the control; ask again. */
+ if (status.dwCurrentState != SERVICE_STOP_PENDING &&
+ (!controlled || o->now_ms() - control_at >= SH_SERVICE_CONTROL_RETRY_MS)) {
+ SERVICE_STATUS ignored;
+ if (!ControlService(service, SERVICE_CONTROL_STOP, &ignored) &&
+ GetLastError() == ERROR_SERVICE_NOT_ACTIVE) {
+ stopped = true;
+ break;
+ }
+ controlled = true;
+ control_at = o->now_ms();
+ }
+ o->sleep_ms(100);
+ }
+ if (process) {
+ uint32_t left = sh_remaining_ms(o->now_ms(), begin, SH_SERVICE_STOP_MS);
+ gone = WaitForSingleObject(process, left < 1000 ? 1000 : left) == WAIT_OBJECT_0;
+ if (!gone && TerminateProcess(process, 1))
+ ended = WaitForSingleObject(process, SH_PROCESS_EXIT_MS) == WAIT_OBJECT_0;
+ CloseHandle(process);
+ } else gone = stopped;
+ CloseServiceHandle(service);
+ CloseServiceHandle(manager);
+ return sh_service_stop_outcome(running, stopped, gone, ended);
+}
+
+void sh_ceg_scm_release(const struct sh_observer *o)
+{
+ if (!manager_process) return;
+ bool alive = WaitForSingleObject(manager_process, 0) != WAIT_OBJECT_0;
+ o->event("ceg-service-stop", alive ? stop_client_service(o) : SH_SERVICE_STOP_FAILED);
+ bool ended = !alive;
+ if (alive && TerminateProcess(manager_process, 0))
+ ended = WaitForSingleObject(manager_process, SH_PROCESS_EXIT_MS) == WAIT_OBJECT_0;
+ o->event("ceg-scm-stopped", ended);
+ CloseHandle(manager_process);
+ manager_process = NULL;
+}
+
+/* ml2014: `dockhost.exe --start-services`. Madeira's one-time-install batch
+ * runs this before a game's installers: Windows installers expect a service
+ * manager, and a Dock session otherwise starts none before this host. Only
+ * Wine's standard services.exe is started (the same bounded start as above),
+ * and only when no manager answers. It is left running: a Wine system process
+ * that ends with the session. The later host run finds it already running,
+ * so it does not own it and never stops it. MADEIRA_DOCK_INSTALL_SCM=0: no-op.
+ */
+int32_t sh_install_scm_start(const struct sh_observer *o)
+{
+ bool enabled = !wide_flag(L"MADEIRA_DOCK_INSTALL_SCM", L'0');
+ SC_HANDLE manager = NULL;
+ DWORD first = 0, error = 0;
+ if (enabled) {
+ manager = OpenSCManagerW(NULL, NULL, SC_MANAGER_CONNECT);
+ first = error = manager ? 0 : GetLastError();
+ if (!manager && sh_install_scm_should_spawn(enabled, first))
+ error = start_manager(o, &manager, "install-scm-started");
+ }
+ bool spawned = manager_process != NULL;
+ enum sh_install_scm outcome = sh_install_scm_outcome(enabled, first, spawned, manager != NULL);
+ if (outcome == SH_INSTALL_SCM_FAILED) o->event("install-scm-error", (int32_t)error);
+ if (manager) CloseServiceHandle(manager);
+ if (manager_process) {
+ /* A manager this call started but that never answered is not left
+ * behind half-started; a working one stays for the session.
+ */
+ if (outcome == SH_INSTALL_SCM_FAILED && WaitForSingleObject(manager_process, 0) != WAIT_OBJECT_0 &&
+ TerminateProcess(manager_process, 0))
+ WaitForSingleObject(manager_process, SH_PROCESS_EXIT_MS);
+ CloseHandle(manager_process);
+ manager_process = NULL;
+ }
+ o->event("install-scm", outcome);
+ return outcome;
+}
+
+/* ml2020: the game session's service manager (scm.h). */
+int32_t sh_game_scm_foreign_services(void)
+{
+ wchar_t windows[MAX_PATH];
+ UINT length = GetWindowsDirectoryW(windows, MAX_PATH);
+ if (!length || length >= MAX_PATH) wcscpy(windows, L"C:\\windows");
+ HKEY services = NULL;
+ if (RegOpenKeyExW(HKEY_LOCAL_MACHINE, L"System\\CurrentControlSet\\Services", 0,
+ KEY_READ, &services) != ERROR_SUCCESS) return -1;
+ int32_t foreign = 0;
+ static wchar_t image[8192], expanded[8192];
+ for (DWORD index = 0; index < 4096; ++index) {
+ wchar_t name[256];
+ DWORD name_length = 256;
+ LSTATUS status = RegEnumKeyExW(services, index, name, &name_length, NULL, NULL, NULL, NULL);
+ if (status == ERROR_NO_MORE_ITEMS) break;
+ if (status != ERROR_SUCCESS) continue;
+ HKEY service = NULL;
+ if (RegOpenKeyExW(services, name, 0, KEY_QUERY_VALUE, &service) != ERROR_SUCCESS) continue;
+ DWORD type = 0, start = 0, size = sizeof(DWORD), kind = 0;
+ bool known = RegQueryValueExW(service, L"Type", NULL, &kind, (BYTE *)&type, &size) == ERROR_SUCCESS &&
+ kind == REG_DWORD && size == sizeof(DWORD);
+ size = sizeof(DWORD);
+ known = known && RegQueryValueExW(service, L"Start", NULL, &kind, (BYTE *)&start, &size) == ERROR_SUCCESS &&
+ kind == REG_DWORD && size == sizeof(DWORD);
+ /* Only automatic Win32 services need the image read at all. */
+ if (known && (type & 0x30u) && start == 2) {
+ size = sizeof(image) - sizeof(wchar_t);
+ const wchar_t *path = NULL;
+ if (RegQueryValueExW(service, L"ImagePath", NULL, &kind, (BYTE *)image, &size) == ERROR_SUCCESS &&
+ (kind == REG_SZ || kind == REG_EXPAND_SZ) && size >= sizeof(wchar_t)) {
+ image[size / sizeof(wchar_t)] = 0;
+ path = image;
+ if (kind == REG_EXPAND_SZ) {
+ DWORD got = ExpandEnvironmentStringsW(image, expanded, 8192);
+ if (got && got < 8192) path = expanded;
+ }
+ }
+ if (sh_service_is_foreign_autostart(type, start, path, windows)) foreign++;
+ }
+ RegCloseKey(service);
+ }
+ RegCloseKey(services);
+ return foreign;
+}
+
+struct game_scm_work { const struct sh_observer *o; volatile LONG outcome; };
+
+/* The worker's events would interleave with the host's after a timeout, so
+ * it reports nothing; the host reports the outcome. */
+static void quiet_event(const char *stage, int32_t value) { (void)stage; (void)value; }
+
+static DWORD WINAPI game_scm_worker(void *parameter)
+{
+ struct game_scm_work *work = parameter;
+ struct sh_observer quiet = {work->o->now_ms, work->o->sleep_ms, quiet_event};
+ InterlockedExchange(&work->outcome, sh_install_scm_start(&quiet));
+ return 0;
+}
+
+int32_t sh_game_scm_start(const struct sh_observer *o, bool *timed_out)
+{
+ /* Static: a timed-out worker may still write to it after this returns. */
+ static struct game_scm_work work;
+ *timed_out = false;
+ work.o = o;
+ InterlockedExchange(&work.outcome, SH_INSTALL_SCM_FAILED);
+ HANDLE worker = CreateThread(NULL, 0, game_scm_worker, &work, 0, NULL);
+ if (!worker) return sh_install_scm_start(o);
+ if (WaitForSingleObject(worker, SH_GAME_SCM_STEP_MS) != WAIT_OBJECT_0) *timed_out = true;
+ CloseHandle(worker);
+ return *timed_out ? SH_INSTALL_SCM_FAILED : InterlockedCompareExchange(&work.outcome, 0, 0);
+}
diff --git a/server/dock/src/scm.h b/server/dock/src/scm.h
new file mode 100644
index 00000000..1ea449ca
--- /dev/null
+++ b/server/dock/src/scm.h
@@ -0,0 +1,41 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ * Copyright 2026 125hz
+ * Madeira Converter Exception: see LICENSE-EXCEPTION.md */
+#ifndef MADEIRA_STEAM_HOST_SCM_H
+#define MADEIRA_STEAM_HOST_SCM_H
+#include
+#include
+#include "probe.h"
+/* ml2000: make Wine's service manager reachable for Valve's client and check
+ * (read-only) that Valve's own client service is registered. If it is not,
+ * run Valve's own bin\SteamService.exe /install from the folder of the loaded
+ * genuine client (as Valve's client does), then check again. Returns 0 or the
+ * ceg-result failure code (-4 unreachable, -5 not registered). Dock itself
+ * never writes service registration or starts a service.
+ */
+int32_t sh_ceg_scm_prepare(const struct sh_observer *o, HMODULE client);
+/* Host exit: only if this host started the service manager, stop Valve's
+ * client service (bounded) and end that service manager. Otherwise no-op.
+ */
+void sh_ceg_scm_release(const struct sh_observer *o);
+/* ml2014: `dockhost.exe --start-services` (Madeira's one-time-install batch):
+ * make Wine's service manager reachable, starting services.exe only when none
+ * answers, and leave it running for the session. Returns enum sh_install_scm
+ * (validation.h). MADEIRA_DOCK_INSTALL_SCM=0: no-op (off).
+ */
+int32_t sh_install_scm_start(const struct sh_observer *o);
+/* ml2020: the game session's own service manager (launch.c). How many
+ * services another program installed in this prefix with automatic start
+ * outside the Windows folder (validation.h, sh_service_is_foreign_autostart):
+ * read-only registry enumeration, bounded; -1 when the key cannot be read.
+ */
+int32_t sh_game_scm_foreign_services(void);
+/* The --start-services start (sh_install_scm_start), on a worker thread
+ * waited for at most SH_GAME_SCM_STEP_MS: a manager that never answers must
+ * not keep the game from starting. On a timeout *timed_out is set and the
+ * worker is left to its blocked call (it reports nothing). Returns enum
+ * sh_install_scm (validation.h), SH_INSTALL_SCM_FAILED on a timeout.
+ */
+#define SH_GAME_SCM_STEP_MS 20000
+int32_t sh_game_scm_start(const struct sh_observer *o, bool *timed_out);
+#endif
diff --git a/server/dock/src/session.c b/server/dock/src/session.c
new file mode 100644
index 00000000..ea7fa16a
--- /dev/null
+++ b/server/dock/src/session.c
@@ -0,0 +1,410 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ * Copyright 2026 125hz
+ * Madeira Converter Exception: see LICENSE-EXCEPTION.md
+ * ml1820: opt-in native Windows authentication experiment. All login and
+ * entitlement decisions belong to Valve's unmodified client. No credential
+ * extraction, token fabrication, or API replacement is performed here.
+ */
+#include "session.h"
+#include "launch.h"
+#include "validation.h"
+#include "auth.h"
+#include
+#include
+#include
+
+#ifdef _WIN64
+typedef void *(__thiscall *get_user_fn)(void *, int32_t, int32_t);
+typedef bool (__thiscall *query_fn)(void *);
+typedef bool (__thiscall *cached_fn)(void *, const char *);
+typedef bool (__thiscall *select_fn)(void *, const char *, bool);
+typedef int32_t (__thiscall *logon_fn)(void *, uint64_t);
+typedef void (__thiscall *token_fn)(void *, const char *, const char *);
+typedef bool (__thiscall *subscribed_fn)(void *, uint32_t);
+typedef int32_t (__thiscall *subscriptions_fn)(void *, uint32_t *, int32_t, bool);
+
+/* Each layout has an exact SHA-256 gate and independently inspected methods.
+ * Unsupported versions fail closed before any private call. */
+static bool method_is(HMODULE module, void *object, unsigned slot, uintptr_t rva)
+{
+ return dock_method_is((uintptr_t)module, object, slot, rva);
+}
+
+static bool enabled(const char *name)
+{
+ const char *s = getenv(name);
+ return s && !strcmp(s, "1");
+}
+
+typedef int32_t (__thiscall *state_fn)(void *);
+typedef int32_t (__thiscall *can_offline_fn)(void *);
+typedef int32_t (__thiscall *logon_offline_fn)(void *, bool);
+
+/* Offline start.
+ *
+ * Nothing here decides ownership or lets a game start by itself. Valve's client
+ * is asked whether this account may log on offline (CanLogonOffline: it needs the
+ * offline logon ticket Steam issued to it during an earlier online logon, which
+ * the client requests and stores on its own), is told to do so (LogOnOffline),
+ * and is then asked the same licence question as online, which it answers from
+ * what it cached itself. The game is started through the same LaunchApp call. A
+ * client that says no at any step ends the session with its own code:
+ * 50 the client cannot log this account on offline (start once online first)
+ * 51 the client refused the offline logon
+ * 52 logged on offline, but the client's cache does not list the game
+ * There is no path from a refusal to a started game. */
+static int offline_session(HMODULE module, void *engine, void *client_user, const struct sh_api *api,
+ const struct sh_observer *o, int32_t pipe, int32_t user, uint64_t id,
+ uint32_t app, const struct dock_client_layout *layout, bool use_list)
+{
+ void **v = *(void ***)client_user;
+ int32_t can = ((can_offline_fn)v[214])(client_user);
+ o->event("session-offline-can", can);
+ if (can != 1) return 50;
+ /* The wrapper takes one bool whose meaning the interface does not name; the
+ * client is asked with false first and, only if it refuses, once with true.
+ * Which one it accepted is reported. */
+ int32_t started = ((logon_offline_fn)v[215])(client_user, false);
+ o->event("session-offline-logon-result", started);
+ if (started != 1) {
+ started = ((logon_offline_fn)v[215])(client_user, true);
+ o->event("session-offline-logon-retry", started);
+ }
+ if (started != 1) return 51;
+
+ uint64_t begin = o->now_ms(), last_list = 0;
+ int32_t last_state = -1;
+ unsigned logged_callbacks = 0;
+ for (unsigned tick = 0; tick < 3000 && o->now_ms() - begin < 60000; ++tick) {
+ for (unsigned batch = 0; batch < 64; ++batch) {
+ struct sh_callback cb = {0};
+ if (!api->get_callback(pipe, &cb)) break;
+ bool valid = cb.id > 0 && cb.size >= 0 && (!cb.size || cb.data);
+ if (logged_callbacks++ < 16) o->event("session-offline-callback-id", cb.id);
+ api->free_callback(pipe);
+ if (!valid) return SH_CALLBACK_INVALID;
+ }
+ int32_t state = ((state_fn)v[5])(client_user);
+ if (state != last_state) {
+ o->event("session-offline-logon-state", state);
+ last_state = state;
+ }
+ uint64_t now = o->now_ms();
+ /* The client loads its cached licences after the offline logon; give it a
+ * second before the first question, then ask once a second. */
+ if (now - begin >= 1000 && now - last_list >= 1000) {
+ bool entitled = ((subscribed_fn)v[181])(client_user, app);
+ bool listed = false;
+ int32_t count = -1;
+ if (entitled || use_list) {
+ uint32_t *apps = calloc(65536, sizeof(uint32_t));
+ if (!apps) return 36;
+ count = ((subscriptions_fn)v[182])(client_user, apps, 65536, true);
+ if (count < 0 || count >= 65536) { free(apps); return 36; }
+ listed = sh_subscription_list_contains(apps, count, 65536, app);
+ free(apps);
+ }
+ last_list = now;
+ if (entitled || listed) {
+ o->event("session-offline-entitled", entitled);
+ o->event("session-offline-listed", listed);
+ o->event("session-subscription-count", count);
+ if (!listed) return 35;
+ if (!enabled("MADEIRA_STEAM_HOST_LAUNCH")) return 0;
+ return sh_launch(module, engine, client_user, api, o, pipe, user, id, app, layout);
+ }
+ }
+ o->sleep_ms(20);
+ }
+ o->event("session-offline-timeout-state", last_state);
+ return 52;
+}
+
+int sh_session(HMODULE module, void *engine, const struct sh_api *api,
+ const struct sh_observer *o, const struct dock_client_layout *layout)
+{
+ int result = 30;
+ struct dock_auth auth = {0};
+ int32_t pipe = 0, user = 0;
+ if (!layout || !method_is(module, engine, 8, layout->engine_user)) {
+ o->event("session-unsupported-client", 1);
+ return result;
+ }
+ user = api->create_global_user(&pipe);
+ if (user <= 0 || pipe <= 0) goto done;
+ void *client_user = ((get_user_fn)(*(void ***)engine)[8])(engine, user, pipe);
+ if (!client_user) goto done;
+ o->event("session-user-vtable-rva", (int32_t)((uintptr_t)*(void **)client_user - (uintptr_t)module));
+ const struct { unsigned slot; uintptr_t rva; } methods[] = {
+ {1, layout->logon}, {4, layout->logged_on}, {6, layout->connected},
+ {49, layout->cached}, {50, layout->select_account}, {56, layout->token},
+ {181, layout->subscribed}, {182, layout->subscriptions}
+ };
+ for (unsigned i = 0; i < sizeof(methods)/sizeof(methods[0]); ++i) {
+ if (!method_is(module, client_user, methods[i].slot, methods[i].rva)) {
+ o->event("session-user-method-mismatch", (int32_t)methods[i].slot);
+ goto done;
+ }
+ }
+ o->event("session-private-abi-verified", 1);
+ /* Offline logon needs three more methods. A client where they do not check out
+ * (or MADEIRA_DOCK_OFFLINE_LOGON=0) simply has no offline start; the online
+ * path above is unaffected. */
+ const char *offline_setting = getenv("MADEIRA_DOCK_OFFLINE_LOGON");
+ bool offline_abi = !(offline_setting && !strcmp(offline_setting, "0")) &&
+ method_is(module, client_user, 5, layout->logon_state) &&
+ method_is(module, client_user, 214, layout->can_offline) &&
+ method_is(module, client_user, 215, layout->logon_offline);
+ o->event("session-offline-abi", offline_abi);
+ if (!enabled("MADEIRA_STEAM_HOST_LOGIN")) {
+ o->event("session-login-disabled", 1);
+ result = 0;
+ goto done;
+ }
+ /* Account identifiers are passed by the local launcher without printing
+ * them. These are not credentials; cached secrets stay inside Valve code.
+ * Never call InvalidateCredentials/DestroyCachedCredentials on this path.
+ */
+ const char *name = getenv("MADEIRA_STEAM_HOST_ACCOUNT");
+ const char *id_text = getenv("MADEIRA_STEAM_HOST_STEAMID");
+ const char *app_text = getenv("MADEIRA_STEAM_HOST_APPID");
+ char *end = NULL;
+ uint64_t id = id_text ? strtoull(id_text, &end, 10) : 0;
+ wchar_t handoff[32768];
+ DWORD handoff_size = GetEnvironmentVariableW(L"MADEIRA_DOCK_AUTH_FILE", handoff, 32768);
+ bool native_auth = handoff_size > 0;
+ if (native_auth) {
+ struct dock_auth_failure failure = {DOCK_AUTH_PATH, 0};
+ if (handoff_size >= 32768 || !dock_auth_consume_diagnostic(handoff, &auth, &failure)) {
+ const char *diagnostics = getenv("MADEIRA_DOCK_HANDOFF_DIAGNOSTICS");
+ if (!diagnostics || strcmp(diagnostics, "0")) {
+ o->event("session-handoff-stage", failure.stage);
+ o->event("session-handoff-error", (int32_t)failure.error);
+ }
+ o->event("session-native-handoff-invalid", 1);
+ result = 37; goto done;
+ }
+ name = auth.account; id = auth.steam_id;
+ }
+ if (!name || !*name || strlen(name) > 64 || !id || (!native_auth && (!end || *end)) ||
+ (id >> 56) != 1 || ((id >> 52) & 15) != 1) {
+ o->event("session-account-input-invalid", 1);
+ goto done;
+ }
+ end = NULL;
+ unsigned long app = app_text ? strtoul(app_text, &end, 10) : 0;
+ if (!app || app == UINT32_MAX || !end || *end) {
+ o->event("session-app-input-invalid", 1);
+ goto done;
+ }
+ if (native_auth && app != auth.app_id) {
+ o->event("session-native-handoff-app-mismatch", 1);
+ result = 37; goto done;
+ }
+ void **v = *(void ***)client_user;
+ if (native_auth) {
+ ((token_fn)v[56])(client_user, auth.token, auth.account);
+ dock_auth_clear(auth.token, sizeof(auth.token));
+ o->event("session-native-token-submitted", 1);
+ } else {
+ bool cached = ((cached_fn)v[49])(client_user, name);
+ o->event("session-cached-credentials-available", cached);
+ if (!cached) { result = 31; goto done; }
+ bool selected = ((select_fn)v[50])(client_user, name, false);
+ o->event("session-cached-account-selected", selected);
+ if (!selected) { result = 32; goto done; }
+ }
+ /* MADEIRA_DOCK_LIST_ENTITLEMENT=0: only the single-app query decides, as before. */
+ const char *list_setting = getenv("MADEIRA_DOCK_LIST_ENTITLEMENT");
+ bool use_list = !(list_setting && !strcmp(list_setting, "0"));
+ /* MADEIRA_DOCK_OFFLINE=1: the launcher found no network. Valve's client is
+ * asked for an offline logon straight away instead of waiting out a
+ * connection that cannot happen. */
+ if (enabled("MADEIRA_DOCK_OFFLINE")) {
+ o->event("session-offline-requested", 1);
+ if (!offline_abi) { result = 50; goto done; }
+ result = offline_session(module, engine, client_user, api, o, pipe, user, id,
+ (uint32_t)app, layout, use_list);
+ goto done;
+ }
+ int32_t started = ((logon_fn)v[1])(client_user, id);
+ o->event("session-logon-start-result", started);
+ if (started != 1) { result = 33; goto done; }
+
+ uint64_t begin = o->now_ms(), online_at = 0, last_probe = 0, last_list = 0, offline_since = 0;
+ bool was_online = false, offline_reported = false;
+ unsigned logged_callbacks = 0, online_callbacks = 0, blips = 0, lost = 0, connect_failures = 0;
+ /* How long after sign-in before ownership is first asked. The answer is only
+ * ever taken when it is yes, so asking early costs nothing: this used to be a
+ * fixed 5 s in which a client that already had the licence list sat idle.
+ * MADEIRA_DOCK_LICENCE_WAIT_MS sets it (0..30000). */
+ uint64_t licence_wait = 500;
+ const char *wait_setting = getenv("MADEIRA_DOCK_LICENCE_WAIT_MS");
+ uint32_t value;
+ if (sh_parse_launch_option(wait_setting, &value) && value <= 30000) licence_wait = value;
+ result = 34;
+ for (unsigned tick = 0; tick < 4500 && o->now_ms() - begin < 90000; ++tick) {
+ for (unsigned batch = 0; batch < 64; ++batch) {
+ struct sh_callback cb = {0};
+ if (!api->get_callback(pipe, &cb)) break;
+ bool valid = cb.id > 0 && cb.size >= 0 && (!cb.size || cb.data);
+ if (logged_callbacks++ < 16) o->event("session-callback-id", cb.id);
+ /* Which callback types arrive once signed in (numbers only): tells a
+ * licence list that never came from one that came and did not list
+ * the app. */
+ else if (was_online && online_callbacks < 32) {
+ o->event("session-online-callback-id", cb.id);
+ ++online_callbacks;
+ }
+ if (valid && (cb.id == 102 || cb.id == 103) && cb.size >= 4) {
+ int32_t error;
+ memcpy(&error, cb.data, 4);
+ o->event("session-connection-result", error);
+ if (cb.id == 102) ++connect_failures;
+ }
+ api->free_callback(pipe);
+ if (!valid) { result = SH_CALLBACK_INVALID; goto done; }
+ }
+ /* The network went away without the launcher noticing: the client has
+ * reported a failed connection, 20 s have passed and it never signed in.
+ * If Valve's client says the account may log on offline, do that instead
+ * of waiting out the 90 s. A client that says no keeps waiting as before. */
+ if (offline_abi && !was_online && connect_failures && o->now_ms() - begin >= 20000) {
+ int32_t can = ((can_offline_fn)v[214])(client_user);
+ o->event("session-offline-fallback", can);
+ if (can == 1) {
+ result = offline_session(module, engine, client_user, api, o, pipe, user, id,
+ (uint32_t)app, layout, use_list);
+ goto done;
+ }
+ connect_failures = 0; /* ask again only after another failed connection */
+ }
+ bool signed_in = api->logged_on(user, pipe) &&
+ ((query_fn)v[4])(client_user) && ((query_fn)v[6])(client_user);
+ uint64_t now = o->now_ms();
+ /* A momentary "not signed in" answer (the client between two of its own
+ * ticks, or an in-process answer that did not arrive in time) used to
+ * restart the 5 s licence wait, so a client that blipped every few
+ * seconds was never asked at all. Signed out now means signed out for a
+ * whole second; shorter blips are counted and reported (durations in ms). */
+ if (signed_in) {
+ if (offline_since) {
+ if (++blips <= 8) o->event("session-online-blip", (int32_t)(now - offline_since));
+ offline_since = 0;
+ }
+ if (!was_online) {
+ was_online = true;
+ online_at = now;
+ o->event("session-authenticated-online", 1);
+ }
+ } else if (was_online) {
+ if (!offline_since) offline_since = now;
+ else if (now - offline_since >= 1000) {
+ was_online = false;
+ online_at = 0;
+ offline_since = 0;
+ ++lost;
+ o->event("session-authenticated-online", 0);
+ }
+ }
+ /* Allow the real licence/app-info callbacks to arrive after logon.
+ * A true subscription is required; timeout never permits launch.
+ */
+ if (was_online && !offline_since && now - online_at >= licence_wait) {
+ bool entitled = ((subscribed_fn)v[181])(client_user, (uint32_t)app);
+ if (!entitled && now - last_probe >= 10000) {
+ /* Not yet, every 10 s: how many apps the account's licences give the
+ * client so far, and whether it owns app 0 (the client itself, which
+ * every account has). 0 and false mean the ownership map is not built
+ * yet; a count without the requested app means the licences arrived
+ * without it. Counts only, no App IDs. */
+ uint32_t *probe = calloc(65536, sizeof(uint32_t));
+ if (probe) {
+ o->event("session-online-subscription-count",
+ ((subscriptions_fn)v[182])(client_user, probe, 65536, true));
+ free(probe);
+ }
+ o->event("session-online-app-zero-query", ((subscribed_fn)v[181])(client_user, 0));
+ last_probe = now;
+ }
+ /* The list of the account's subscribed apps is Valve's client's other
+ * answer to the same question. On one platform the single-app query
+ * stayed false for the whole wait while this list held the app the
+ * whole time. Unless MADEIRA_DOCK_LIST_ENTITLEMENT=0, an app in that
+ * list counts as owned (once a second while the query says no); the
+ * client's own launch path still decides for itself. */
+ if (entitled || (use_list && now - last_list >= 250)) {
+ uint32_t *apps = calloc(65536, sizeof(uint32_t));
+ if (!apps) { result = 36; break; }
+ int32_t count = ((subscriptions_fn)v[182])(client_user, apps, 65536, true);
+ bool listed = false;
+ if (count < 0 || count >= 65536) {
+ free(apps); result = 36; break;
+ }
+ listed = sh_subscription_list_contains(apps, count, 65536, (uint32_t)app);
+ free(apps);
+ last_list = now;
+ if (entitled || listed) {
+ o->event("session-requested-app-entitled", entitled);
+ o->event("session-subscription-count", count);
+ o->event("session-requested-app-listed", listed);
+ if (!entitled) o->event("session-entitlement-source", 182);
+ o->event("session-app-zero-query", ((subscribed_fn)v[181])(client_user, 0));
+ o->event("session-invalid-app-query", ((subscribed_fn)v[181])(client_user, UINT32_MAX));
+ result = listed ? 0 : 35;
+ /* For the launcher's "saved for offline play" mark: whether
+ * Valve's client now holds what it needs to log this account
+ * on without a connection (1 = yes). Asked when the licence is
+ * confirmed and again after the game, since the client fetches
+ * its offline logon ticket on its own schedule. */
+ if (!result && offline_abi) {
+ int32_t ready = ((can_offline_fn)v[214])(client_user);
+ o->event("session-offline-ready", ready);
+ offline_reported = ready == 1;
+ }
+ if (!result && enabled("MADEIRA_STEAM_HOST_LAUNCH")) {
+ result = sh_launch(module, engine, client_user, api, o, pipe, user, id, (uint32_t)app, layout);
+ if (offline_abi && !offline_reported)
+ o->event("session-offline-ready", ((can_offline_fn)v[214])(client_user));
+ }
+ break;
+ }
+ }
+ }
+ o->sleep_ms(20);
+ }
+ if (blips) o->event("session-online-blips", (int32_t)blips);
+ if (lost) o->event("session-online-lost", (int32_t)lost);
+ /* Timed out while signed in: report how many apps the account's licences
+ * give Valve's client (a count, no App IDs) and whether the requested one
+ * is among them. 0 means the licence list never arrived or was never
+ * processed; a count without the app means it arrived without this game. */
+ if (result == 34 && was_online) {
+ uint32_t *apps = calloc(65536, sizeof(uint32_t));
+ if (apps) {
+ int32_t count = ((subscriptions_fn)v[182])(client_user, apps, 65536, true);
+ o->event("session-timeout-subscription-count", count);
+ if (count >= 0 && count < 65536)
+ o->event("session-timeout-app-listed",
+ sh_subscription_list_contains(apps, count, 65536, (uint32_t)app));
+ free(apps);
+ }
+ o->event("session-timeout-still-online", api->logged_on(user, pipe) &&
+ ((query_fn)v[4])(client_user) && ((query_fn)v[6])(client_user));
+ }
+done:
+ dock_auth_clear(&auth, sizeof(auth));
+ o->event("session-auth-test-result", result);
+ if (pipe > 0 && user > 0) api->release_user(pipe, user);
+ if (pipe > 0 && !api->release_pipe(pipe) && !result) result = SH_RELEASE_FAILED;
+ return result;
+}
+#else
+int sh_session(HMODULE module, void *engine, const struct sh_api *api,
+ const struct sh_observer *o, const struct dock_client_layout *layout)
+{
+ (void)module; (void)engine; (void)api; (void)layout;
+ o->event("session-requires-64-bit-host", 1);
+ return 30;
+}
+#endif
diff --git a/server/dock/src/session.h b/server/dock/src/session.h
new file mode 100644
index 00000000..b88647d8
--- /dev/null
+++ b/server/dock/src/session.h
@@ -0,0 +1,11 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ * Copyright 2026 125hz
+ * Madeira Converter Exception: see LICENSE-EXCEPTION.md */
+#ifndef MADEIRA_STEAM_HOST_SESSION_H
+#define MADEIRA_STEAM_HOST_SESSION_H
+#include
+#include "probe.h"
+#include "client_layout.h"
+int sh_session(HMODULE module, void *engine, const struct sh_api *api,
+ const struct sh_observer *observer, const struct dock_client_layout *layout);
+#endif
diff --git a/server/dock/src/validation.c b/server/dock/src/validation.c
new file mode 100644
index 00000000..0efe6da4
--- /dev/null
+++ b/server/dock/src/validation.c
@@ -0,0 +1,354 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ * Copyright 2026 125hz
+ * Madeira Converter Exception: see LICENSE-EXCEPTION.md
+ * ml1820: validation shared by the Windows host and native sanitizer tests.
+ */
+#include "validation.h"
+#include
+#include
+
+bool sh_parse_launch_option(const char *text, uint32_t *option)
+{
+ if (!text || !*text || !option) return false;
+ uint32_t value = 0;
+ for (unsigned i = 0; text[i]; ++i) {
+ if (i >= 10 || text[i] < '0' || text[i] > '9') return false;
+ unsigned digit = (unsigned)(text[i] - '0');
+ if (value > ((uint32_t)INT32_MAX - digit) / 10) return false;
+ value = value * 10 + digit;
+ }
+ *option = value;
+ return true;
+}
+
+bool sh_launch_option_missing(const void *payload, size_t size, uint32_t option)
+{
+ if (!payload || size != 524) return false;
+ const char *detail = (const char *)payload + 12;
+ const char *end = memchr(detail, 0, 512);
+ if (!end) return false;
+ char expected[80];
+ int length = snprintf(expected, sizeof(expected), "entry for launch option %u not found", (unsigned)option);
+ return length > 0 && (size_t)length < sizeof(expected) && strstr(detail, expected) != NULL;
+}
+bool sh_launch_arguments_valid(const char *arguments, size_t length)
+{
+ if (!arguments || length >= SH_LAUNCH_ARGUMENTS_CAPACITY) return false;
+ bool quoted = false, in_token = false;
+ unsigned tokens = 0, slashes = 0;
+ for (size_t i = 0; i < length; ++i) {
+ unsigned char c = (unsigned char)arguments[i];
+ if ((c < 32 && c != '\t') || c == 127) return false;
+ if (c == '"' && !(slashes & 1)) quoted = !quoted;
+ if (!quoted && (c == ' ' || c == '\t')) in_token = false;
+ else if (!in_token) { ++tokens; in_token = true; }
+ slashes = c == '\\' ? slashes + 1 : 0;
+ }
+ return !quoted && tokens <= SH_LAUNCH_ARGUMENTS_MAX_TOKENS;
+}
+
+bool sh_subscription_list_contains(const uint32_t *apps, int32_t count,
+ size_t capacity, uint32_t requested)
+{
+ if (!apps || count <= 0 || (size_t)count >= capacity || !requested || requested == UINT32_MAX)
+ return false;
+ for (int32_t i = 0; i < count; ++i) if (apps[i] == requested) return true;
+ return false;
+}
+
+bool sh_decode_launch_result(const void *payload, size_t size, uint64_t expected_game,
+ int32_t *error)
+{
+ uint64_t returned_game;
+ if (!payload || !error || size != 524) return false;
+ memcpy(&returned_game, payload, sizeof(returned_game));
+ if (returned_game != expected_game) return false;
+ memcpy(error, (const char *)payload+8, sizeof(*error));
+ return true;
+}
+
+/* ml1970: Valve's client refuses a launch while the app, or an app owning one
+ * of its shared depots, still needs content: 17 dependency not ready,
+ * 19 update required, 20 still busy. Desktop Steam lets its client finish
+ * that update and then starts the game; the host keeps Valve's client alive
+ * and asks again. Every other result, including licence and connection
+ * failures, still fails closed.
+ */
+bool sh_launch_error_waits_for_content(int32_t error)
+{
+ return error == 17 || error == 19 || error == 20;
+}
+
+/* ml2011: 22 invalid app config and 23 invalid depot config also come back when
+ * Valve's client has not yet received the app's configuration from Steam after
+ * signing in (a freshly started client begins with an empty app-info cache).
+ * The host asks again for a bounded time; a genuinely broken configuration
+ * still fails closed once the bound passes.
+ */
+bool sh_launch_error_waits_for_config(int32_t error)
+{
+ return error == 22 || error == 23;
+}
+
+/* ml2015: 35, another session is playing on this account. */
+bool sh_launch_error_waits_for_session(int32_t error)
+{
+ return error == 35;
+}
+
+/* 10 s, 20 s, then every 30 s: the client schedules its update after the
+ * first refusal, so later requests only confirm that it has finished.
+ */
+uint32_t sh_launch_retry_delay_ms(unsigned attempt)
+{
+ return attempt == 0 ? 10000 : attempt == 1 ? 20000 : 30000;
+}
+
+/* ml1990: Valve's client customizes CustomExecutable files per user. Its
+ * RequestCustomBinaries returns an EResult and writes the number of per-file
+ * jobs it started; each job then posts its own EResult for this AppID. Only
+ * k_EResultOK (1) from every started job counts as success. Busy (10) means
+ * the app is currently updating or running and may be asked again. Any
+ * other result, including OK with zero jobs, fails closed: without prepared
+ * binaries the protected executable cannot start.
+ */
+static bool decode_ceg(const void *payload, size_t size, size_t expected,
+ uint32_t appid, int32_t *result)
+{
+ uint32_t returned;
+ if (!payload || !result || size != expected || !appid) return false;
+ memcpy(&returned, (const char *)payload+4, sizeof(returned));
+ if (returned != appid) return false;
+ memcpy(result, payload, sizeof(*result));
+ return true;
+}
+
+bool sh_decode_ceg_job(const void *payload, size_t size, uint32_t appid, int32_t *result)
+{
+ return decode_ceg(payload, size, 8, appid, result);
+}
+
+bool sh_decode_ceg_reply(const void *payload, size_t size, uint32_t appid, int32_t *result)
+{
+ return decode_ceg(payload, size, 12, appid, result);
+}
+
+enum sh_ceg_step sh_ceg_request_step(int32_t result, uint32_t jobs, struct sh_ceg_progress *progress)
+{
+ if (!progress) return SH_CEG_FAIL;
+ if (result == 10) return SH_CEG_RETRY;
+ if (result != 1 || !jobs || jobs > SH_CEG_MAX_JOBS) {
+ progress->failure = result == 1 ? 0 : result;
+ return SH_CEG_FAIL;
+ }
+ *progress = (struct sh_ceg_progress){jobs, 0, 0};
+ return SH_CEG_WAIT;
+}
+
+enum sh_ceg_step sh_ceg_record_job(struct sh_ceg_progress *progress, int32_t result)
+{
+ if (!progress || !progress->expected || progress->finished >= progress->expected)
+ return SH_CEG_FAIL;
+ if (result != 1) {
+ progress->failure = result;
+ return SH_CEG_FAIL;
+ }
+ return ++progress->finished == progress->expected ? SH_CEG_DONE : SH_CEG_WAIT;
+}
+
+/* ml2000: Wine's sechost reports a missing \pipe\svcctl listener as
+ * RPC_S_SERVER_UNAVAILABLE (1722). Only that means "no service manager": any
+ * other failure (for example access denied) is not fixed by starting one.
+ * RPC_S_SERVER_TOO_BUSY (1723) can occur while a new manager is starting.
+ */
+bool sh_scm_error_means_absent(uint32_t error)
+{
+ return error == 1722;
+}
+
+bool sh_scm_error_retryable(uint32_t error)
+{
+ return error == 1722 || error == 1723;
+}
+
+int32_t sh_ceg_scm_result(bool manager_reachable, bool service_registered)
+{
+ if (!manager_reachable) return SH_CEG_SCM_UNAVAILABLE;
+ return service_registered ? 0 : SH_CEG_SERVICE_UNREGISTERED;
+}
+
+uint32_t sh_remaining_ms(uint64_t now, uint64_t begin, uint64_t bound)
+{
+ uint64_t elapsed = now >= begin ? now - begin : 0;
+ if (elapsed >= bound) return 0;
+ uint64_t left = bound - elapsed;
+ return left > UINT32_MAX - 1 ? UINT32_MAX - 1 : (uint32_t)left;
+}
+
+uint32_t sh_scm_poll_slice_ms(uint32_t left)
+{
+ return left < SH_SCM_POLL_MS ? left : SH_SCM_POLL_MS;
+}
+
+/* A service counts as stopped only when the manager reports it stopped and
+ * its process is gone; a process that outlives the bound is ended by the host.
+ */
+enum sh_service_stop sh_service_stop_outcome(bool was_running, bool stopped_by_manager,
+ bool process_gone, bool ended_by_host)
+{
+ if (!was_running) return SH_SERVICE_NOT_RUNNING;
+ if (stopped_by_manager && process_gone) return SH_SERVICE_STOPPED;
+ if (ended_by_host) return SH_SERVICE_ENDED_AFTER_BOUND;
+ return SH_SERVICE_STOP_FAILED;
+}
+
+/* Never re-run the installer over an existing registration or when the
+ * service manager answered with an unexpected error (fail closed as -5).
+ */
+bool sh_should_install_service(bool registered, bool missing, bool install_enabled)
+{
+ return install_enabled && !registered && missing;
+}
+
+int32_t sh_service_install_report(bool file_present, bool finished, uint32_t exit_code)
+{
+ if (!file_present) return SH_SERVICE_INSTALL_MISSING;
+ if (!finished) return SH_SERVICE_INSTALL_TIMEOUT;
+ return (int32_t)exit_code;
+}
+
+/* ml2014: the install batch's service manager. Never start a second manager:
+ * only a definite "no listener" (1722) on the first open spawns one.
+ */
+bool sh_install_scm_should_spawn(bool enabled, uint32_t first_error)
+{
+ return enabled && sh_scm_error_means_absent(first_error);
+}
+
+enum sh_install_scm sh_install_scm_outcome(bool enabled, uint32_t first_error,
+ bool spawned, bool reachable)
+{
+ if (!enabled) return SH_INSTALL_SCM_OFF;
+ if (!first_error) return SH_INSTALL_SCM_ALREADY;
+ if (!reachable) return SH_INSTALL_SCM_FAILED;
+ return spawned ? SH_INSTALL_SCM_STARTED : SH_INSTALL_SCM_ALREADY;
+}
+
+const char *sh_install_scm_word(int32_t outcome)
+{
+ switch (outcome) {
+ case SH_INSTALL_SCM_OFF: return "off";
+ case SH_INSTALL_SCM_ALREADY: return "already";
+ case SH_INSTALL_SCM_STARTED: return "started";
+ default: return "failed";
+ }
+}
+
+/* ml2020: the game session's service manager and the hold (validation.h). */
+static wchar_t sh_wide_lower(wchar_t c)
+{
+ return (c >= L'A' && c <= L'Z') ? (wchar_t)(c + (L'a' - L'A')) : c;
+}
+
+/* Case-insensitive, ASCII letters only (image names and Windows paths). */
+static bool sh_wide_prefix(const wchar_t *text, const wchar_t *prefix)
+{
+ if (!text || !prefix) return false;
+ for (; *prefix; ++text, ++prefix)
+ if (sh_wide_lower(*text) != sh_wide_lower(*prefix)) return false;
+ return true;
+}
+
+static bool sh_wide_separator(wchar_t c)
+{
+ return c == L'\\' || c == L'/';
+}
+
+enum sh_game_scm_mode sh_game_scm_mode(const wchar_t *value)
+{
+ if (!value) return SH_GAME_SCM_AUTO;
+ if (value[0] == L'0' && !value[1]) return SH_GAME_SCM_OFF;
+ if (value[0] == L'1' && !value[1]) return SH_GAME_SCM_ON;
+ return SH_GAME_SCM_AUTO;
+}
+
+bool sh_path_in_folder(const wchar_t *path, const wchar_t *folder)
+{
+ if (!path || !folder || !*folder) return false;
+ size_t length = wcslen(folder);
+ while (length && sh_wide_separator(folder[length - 1])) --length;
+ if (!length) return false;
+ for (size_t i = 0; i < length; ++i) {
+ wchar_t a = sh_wide_lower(path[i]), b = sh_wide_lower(folder[i]);
+ if (sh_wide_separator(a) && sh_wide_separator(b)) continue;
+ if (a != b) return false;
+ }
+ return sh_wide_separator(path[length]);
+}
+
+bool sh_image_is_windows(const wchar_t *image, const wchar_t *windows_dir)
+{
+ if (!image) return false;
+ /* Registry forms: a quoted path, an NT prefix, or a path relative to the
+ * Windows folder. The arguments after the image do not matter here. */
+ while (*image == L'"' || *image == L' ') ++image;
+ if (sh_wide_prefix(image, L"\\??\\")) image += 4;
+ if (sh_wide_prefix(image, L"%SystemRoot%") || sh_wide_prefix(image, L"\\SystemRoot") ||
+ sh_wide_prefix(image, L"System32\\") || sh_wide_prefix(image, L"SysWOW64\\") ||
+ sh_wide_prefix(image, L"%windir%")) return true;
+ return sh_path_in_folder(image, windows_dir);
+}
+
+bool sh_service_is_foreign_autostart(uint32_t type, uint32_t start, const wchar_t *image,
+ const wchar_t *windows_dir)
+{
+ /* SERVICE_WIN32_*; SERVICE_AUTO_START or SERVICE_DEMAND_START: a program
+ * that registered a demand-start service starts it itself through the
+ * manager, so it needs one as much as an automatic one does. */
+ if (!(type & 0x30u) || (start != 2 && start != 3)) return false;
+ if (!image) return false;
+ while (*image == L'"' || *image == L' ') ++image;
+ if (!*image) return false;
+ return !sh_image_is_windows(image, windows_dir);
+}
+
+bool sh_game_scm_wanted(enum sh_game_scm_mode mode, unsigned foreign_autostart)
+{
+ if (mode == SH_GAME_SCM_OFF) return false;
+ if (mode == SH_GAME_SCM_ON) return true;
+ return foreign_autostart > 0;
+}
+
+enum sh_keep_alive_mode sh_keep_alive_mode(const wchar_t *value)
+{
+ if (value && value[0] == L'0' && !value[1]) return SH_KEEP_ALIVE_OFF;
+ return SH_KEEP_ALIVE_AUTO;
+}
+
+bool sh_keep_alive_listed(const wchar_t *list, const wchar_t *name)
+{
+ if (!list || !name || !*name) return false;
+ size_t length = wcslen(name);
+ const wchar_t *entry = list;
+ for (;;) {
+ while (*entry == L' ' || *entry == L';') ++entry;
+ if (!*entry) return false;
+ const wchar_t *end = entry;
+ while (*end && *end != L';') ++end;
+ const wchar_t *stop = end;
+ while (stop > entry && stop[-1] == L' ') --stop;
+ if ((size_t)(stop - entry) == length) {
+ size_t i = 0;
+ while (i < length && sh_wide_lower(entry[i]) == sh_wide_lower(name[i])) ++i;
+ if (i == length) return true;
+ }
+ if (!*end) return false;
+ entry = end + 1;
+ }
+}
+
+bool sh_keep_alive_holds(bool windows_image, bool visible_window, uint64_t age_ms, uint64_t young_ms)
+{
+ if (windows_image) return false;
+ return visible_window || age_ms < young_ms;
+}
diff --git a/server/dock/src/validation.h b/server/dock/src/validation.h
new file mode 100644
index 00000000..db67869e
--- /dev/null
+++ b/server/dock/src/validation.h
@@ -0,0 +1,134 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ * Copyright 2026 125hz
+ * Madeira Converter Exception: see LICENSE-EXCEPTION.md */
+#ifndef MADEIRA_STEAM_HOST_VALIDATION_H
+#define MADEIRA_STEAM_HOST_VALIDATION_H
+#include
+#include
+#include
+#include
+/* Extra LaunchApp arguments are one bounded UTF-8 string, never a shell command.
+ * The Swift library profile enforces the same byte/quote/token/control bounds. */
+#define SH_LAUNCH_ARGUMENTS_CAPACITY 4096u
+#define SH_LAUNCH_ARGUMENTS_MAX_TOKENS 64u
+bool sh_launch_arguments_valid(const char *arguments, size_t length);
+bool sh_subscription_list_contains(const uint32_t *apps, int32_t count,
+ size_t capacity, uint32_t requested);
+bool sh_decode_launch_result(const void *payload, size_t size, uint64_t expected_game,
+ int32_t *error);
+/* ml1970: Valve's launch refusals that mean "content is still being prepared". */
+bool sh_launch_error_waits_for_content(int32_t error);
+uint32_t sh_launch_retry_delay_ms(unsigned attempt);
+bool sh_launch_error_waits_for_config(int32_t error);
+bool sh_launch_error_waits_for_session(int32_t error);
+/* Decimal config.launch key, bounded to the numeric report range. */
+bool sh_parse_launch_option(const char *text, uint32_t *option);
+/* Recognize only the client's bounded missing-entry diagnostic; never log it. */
+bool sh_launch_option_missing(const void *payload, size_t size, uint32_t option);
+
+/* ml1990: Valve custom-executable (CEG) preparation. Callback 1020025 is
+ * posted once per per-file job: int32 EResult, uint32 AppID (8 bytes).
+ * Callback 1020024 reports each server reply: EResult, AppID, bool (12).
+ */
+#define SH_CEG_JOB_FINISHED 1020025
+#define SH_CEG_SERVER_REPLY 1020024
+#define SH_CEG_MAX_JOBS 4096u
+enum sh_ceg_step { SH_CEG_WAIT, SH_CEG_RETRY, SH_CEG_DONE, SH_CEG_FAIL };
+struct sh_ceg_progress { uint32_t expected, finished; int32_t failure; };
+bool sh_decode_ceg_job(const void *payload, size_t size, uint32_t appid, int32_t *result);
+bool sh_decode_ceg_reply(const void *payload, size_t size, uint32_t appid, int32_t *result);
+enum sh_ceg_step sh_ceg_request_step(int32_t result, uint32_t jobs, struct sh_ceg_progress *progress);
+enum sh_ceg_step sh_ceg_record_job(struct sh_ceg_progress *progress, int32_t result);
+
+/* ml2000: Wine's service manager, which Valve's client needs to reach its own
+ * client service for CEG work. ceg-result -4: the service manager could not
+ * be reached; -5: Valve's client service is not registered in this prefix.
+ */
+#define SH_CEG_SCM_UNAVAILABLE (-4)
+#define SH_CEG_SERVICE_UNREGISTERED (-5)
+enum sh_service_stop { SH_SERVICE_STOP_FAILED = -1, SH_SERVICE_NOT_RUNNING = 0,
+ SH_SERVICE_STOPPED = 1, SH_SERVICE_ENDED_AFTER_BOUND = 2 };
+/* True only for "no service manager is listening" (so one may be started). */
+bool sh_scm_error_means_absent(uint32_t error);
+/* True while a just-started service manager may still be coming up. */
+bool sh_scm_error_retryable(uint32_t error);
+/* 0 ready, otherwise the ceg-result failure code above. */
+int32_t sh_ceg_scm_result(bool manager_reachable, bool service_registered);
+/* Milliseconds left of a bound (0 when elapsed; clock regressions count as 0 elapsed). */
+uint32_t sh_remaining_ms(uint64_t now, uint64_t begin, uint64_t bound);
+/* How long a manager start waits before asking the manager again: the time left, at most
+ * SH_SCM_POLL_MS. */
+#define SH_SCM_POLL_MS 250u
+uint32_t sh_scm_poll_slice_ms(uint32_t left);
+enum sh_service_stop sh_service_stop_outcome(bool was_running, bool stopped_by_manager,
+ bool process_gone, bool ended_by_host);
+/* Run Valve's service installer only for a definitely missing service. */
+bool sh_should_install_service(bool registered, bool missing, bool install_enabled);
+/* ceg-service-install value: installer exit code, -1 timeout, -2 file missing
+ * (-3, set by the caller, means the installer process could not be started).
+ */
+#define SH_SERVICE_INSTALL_TIMEOUT (-1)
+#define SH_SERVICE_INSTALL_MISSING (-2)
+int32_t sh_service_install_report(bool file_present, bool finished, uint32_t exit_code);
+
+/* ml2014: `dockhost.exe --start-services`, run by Madeira's one-time-install
+ * batch before the game's installers. Outcome of making Wine's service
+ * manager reachable: off (MADEIRA_DOCK_INSTALL_SCM=0), already running
+ * (reachable at once, or started by another launcher), started by this call,
+ * or failed. The printed word is the one Madeira's batch result expects.
+ */
+enum sh_install_scm { SH_INSTALL_SCM_FAILED = -1, SH_INSTALL_SCM_OFF = 0,
+ SH_INSTALL_SCM_ALREADY = 1, SH_INSTALL_SCM_STARTED = 2 };
+/* Spawn services.exe only when enabled and the first open said "absent". */
+bool sh_install_scm_should_spawn(bool enabled, uint32_t first_error);
+/* first_error 0: reachable at once; spawned: this call created services.exe. */
+enum sh_install_scm sh_install_scm_outcome(bool enabled, uint32_t first_error,
+ bool spawned, bool reachable);
+/* "started", "already", "off"; "failed" for any other value. */
+const char *sh_install_scm_word(int32_t outcome);
+
+/* ml2020: a game session's own service manager and the hold while a game's
+ * launcher restarts (launch.c, hold.c). Pure decisions; the Windows calls
+ * stay in the host files so the native sanitizer tests cover these.
+ *
+ * MADEIRA_DOCK_GAME_SCM: "0" never starts a service manager for the game
+ * session, "1" always does; unset (or any other value) starts one only when
+ * a program installed an automatic-start Windows service of its own in this
+ * prefix, which only a running service manager can start.
+ */
+enum sh_game_scm_mode { SH_GAME_SCM_OFF = 0, SH_GAME_SCM_ON = 1, SH_GAME_SCM_AUTO = 2 };
+enum sh_game_scm_mode sh_game_scm_mode(const wchar_t *value);
+/* A service entry under System\CurrentControlSet\Services that Windows
+ * a program may start and that is not part of Windows: a Win32 service
+ * (type 0x10 or 0x20) with start type 2 (automatic) or 3 (on demand, which
+ * the program that registered it starts itself) whose image is neither
+ * under the Windows folder nor given relative to it (%SystemRoot%,
+ * \SystemRoot, System32\, SysWOW64\). Wine's own services all fail this
+ * test; a launcher's own service passes it.
+ */
+bool sh_service_is_foreign_autostart(uint32_t type, uint32_t start, const wchar_t *image,
+ const wchar_t *windows_dir);
+bool sh_game_scm_wanted(enum sh_game_scm_mode mode, unsigned foreign_autostart);
+
+/* MADEIRA_DOCK_KEEP_ALIVE: "0" ends the session as before, 3 s after Valve's
+ * client stops reporting the game as running. Unset, empty or a `;`-separated
+ * list of image file names: the end is postponed while a process of the
+ * game's own tree (descended from this host, Windows images and their
+ * children excepted) or with a listed image name still shows a window or is
+ * younger than SH_KEEP_ALIVE_YOUNG_MS. A launcher that restarts itself is
+ * young; the game it then starts shows a window; a launcher left behind in
+ * the background after the game ends is neither, so the session ends.
+ */
+#define SH_KEEP_ALIVE_YOUNG_MS 60000ULL
+enum sh_keep_alive_mode { SH_KEEP_ALIVE_OFF = 0, SH_KEEP_ALIVE_AUTO = 1 };
+enum sh_keep_alive_mode sh_keep_alive_mode(const wchar_t *value);
+/* `name` (an image file name) is one of the `;`-separated entries, no case. */
+bool sh_keep_alive_listed(const wchar_t *list, const wchar_t *name);
+/* `path` lies inside `folder` (no case; a separator must follow the folder). */
+bool sh_path_in_folder(const wchar_t *path, const wchar_t *folder);
+/* `image` is Windows' own: inside windows_dir, or given relative to it. */
+bool sh_image_is_windows(const wchar_t *image, const wchar_t *windows_dir);
+/* One tracked process holds the session while it is not a Windows image and
+ * either shows a window or is younger than young_ms. */
+bool sh_keep_alive_holds(bool windows_image, bool visible_window, uint64_t age_ms, uint64_t young_ms);
+#endif
diff --git a/server/dock/tests/test-auth.c b/server/dock/tests/test-auth.c
new file mode 100644
index 00000000..cf8b35ae
--- /dev/null
+++ b/server/dock/tests/test-auth.c
@@ -0,0 +1,90 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ * Copyright 2026 125hz
+ * Madeira Converter Exception: see LICENSE-EXCEPTION.md */
+#include "auth.h"
+#include
+#include
+#include
+#ifdef _WIN32
+#include
+#endif
+
+static void put(unsigned char *p, uint64_t value, unsigned n)
+{ for (unsigned i = 0; i < n; ++i) p[i] = (unsigned char)(value >> (8 * i)); }
+
+int main(void)
+{
+ unsigned char bytes[DOCK_AUTH_MAX + 1] = "MDOCK001";
+ struct dock_auth auth;
+ put(bytes + 8, UINT64_C(76561197960265729), 8);
+ put(bytes + 16, 123, 4); put(bytes + 20, 4, 2); put(bytes + 22, 5, 2);
+ memcpy(bytes + 24, "usera.b-c", 9);
+ assert(dock_auth_parse(bytes, 33, &auth));
+ assert(auth.app_id == 123 && auth.steam_id == UINT64_C(76561197960265729));
+ assert(!strcmp(auth.account, "user") && !strcmp(auth.token, "a.b-c"));
+#ifdef _WIN32
+ wchar_t folder[MAX_PATH], path[MAX_PATH];
+ assert(GetTempPathW(MAX_PATH, folder) && GetTempFileNameW(folder, L"mdt", 0, path));
+ HANDLE file = CreateFileW(path, GENERIC_WRITE, 0, NULL, TRUNCATE_EXISTING, 0, NULL);
+ assert(file != INVALID_HANDLE_VALUE);
+ DWORD written;
+ struct dock_auth_failure failure;
+ assert(WriteFile(file, bytes, 33, &written, NULL) && written == 33);
+ assert(!dock_auth_consume_diagnostic(path, &auth, &failure));
+ assert(failure.stage == DOCK_AUTH_OPEN && failure.error == ERROR_SHARING_VIOLATION);
+ assert(CloseHandle(file));
+ assert(dock_auth_consume_diagnostic(path, &auth, &failure));
+ assert(!failure.stage && !failure.error);
+ assert(GetFileAttributesW(path) == INVALID_FILE_ATTRIBUTES);
+ assert(!dock_auth_consume_diagnostic(path, &auth, &failure));
+ assert(failure.stage == DOCK_AUTH_OPEN && failure.error == ERROR_FILE_NOT_FOUND);
+ assert(GetTempFileNameW(folder, L"mdt", 0, path));
+ assert(!dock_auth_consume_diagnostic(path, &auth, &failure));
+ assert(failure.stage == DOCK_AUTH_BOUNDS && !failure.error);
+ assert(GetFileAttributesW(path) == INVALID_FILE_ATTRIBUTES);
+ assert(GetTempFileNameW(folder, L"mdt", 0, path));
+ file = CreateFileW(path, GENERIC_WRITE, 0, NULL, TRUNCATE_EXISTING, 0, NULL);
+ assert(file != INVALID_HANDLE_VALUE);
+ bytes[0] = 'X';
+ assert(WriteFile(file, bytes, 33, &written, NULL) && written == 33);
+ assert(CloseHandle(file));
+ assert(!dock_auth_consume_diagnostic(path, &auth, &failure));
+ assert(failure.stage == DOCK_AUTH_PARSE && !failure.error);
+ assert(GetFileAttributesW(path) == INVALID_FILE_ATTRIBUTES);
+ bytes[0] = 'M';
+#endif
+ for (size_t size = 0; size < 33; ++size) assert(!dock_auth_parse(bytes, size, &auth));
+ assert(!dock_auth_parse(bytes, 34, &auth));
+ assert(!dock_auth_parse(bytes, sizeof(bytes), &auth));
+ assert(!dock_auth_parse(NULL, 33, &auth));
+ assert(!dock_auth_parse(bytes, 33, NULL));
+ for (unsigned i = 0; i < 8; ++i) {
+ bytes[i] ^= 0x80; assert(!dock_auth_parse(bytes, 33, &auth)); bytes[i] ^= 0x80;
+ }
+ for (unsigned i = 24; i < 33; ++i) {
+ unsigned char saved = bytes[i]; bytes[i] = 0;
+ assert(!dock_auth_parse(bytes, 33, &auth)); bytes[i] = saved;
+ }
+ put(bytes + 16, 0, 4); assert(!dock_auth_parse(bytes, 33, &auth));
+ put(bytes + 16, UINT32_MAX, 4); assert(!dock_auth_parse(bytes, 33, &auth));
+ put(bytes + 16, 123, 4);
+ put(bytes + 8, UINT64_C(76561197960265728), 8); assert(!dock_auth_parse(bytes, 33, &auth));
+ put(bytes + 8, UINT64_C(76561197960265729), 8);
+ put(bytes + 20, 65, 2); assert(!dock_auth_parse(bytes, 94, &auth));
+ put(bytes + 20, 64, 2); put(bytes + 22, 8192, 2);
+ memset(bytes + 24, 'a', 64 + 8192);
+ assert(dock_auth_parse(bytes, DOCK_AUTH_MAX, &auth));
+ put(bytes + 22, 8193, 2); assert(!dock_auth_parse(bytes, sizeof(bytes), &auth));
+ const unsigned char *cleared = (const unsigned char *)&auth;
+ for (size_t i = 0; i < sizeof(auth); ++i) assert(cleared[i] == 0);
+ /* Arbitrary malformed envelopes must stay bounded under ASan/UBSan. */
+ uint32_t seed = 1234;
+ for (unsigned n = 0; n < 2000; ++n) {
+ seed = seed * 1664525u + 1013904223u;
+ size_t size = seed % sizeof(bytes);
+ for (size_t i = 0; i < size; ++i) { seed = seed * 1664525u + 1013904223u; bytes[i] = (unsigned char)(seed >> 24); }
+ assert(!dock_auth_parse(bytes, size, &auth));
+ }
+ puts("dock: handoff bounds, truncation, account/app binding, clearing and 2000 malformed inputs passed");
+ return 0;
+}
diff --git a/server/dock/tests/test-client_layout.c b/server/dock/tests/test-client_layout.c
new file mode 100644
index 00000000..26141003
--- /dev/null
+++ b/server/dock/tests/test-client_layout.c
@@ -0,0 +1,39 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ * Copyright 2026 125hz
+ * Madeira Converter Exception: see LICENSE-EXCEPTION.md */
+#include "client_layout.h"
+#include
+#include
+#include
+int main(void)
+{
+ const struct dock_client_layout *jan = dock_client_layout(
+ "71b391fe9f3e2006cbc81a5c75eef3eb4186012deabfdb2c8b7e8d4850ecf640");
+ const struct dock_client_layout *sep = dock_client_layout(
+ "caba4826aa3501039d095aee1843a6bfb270fb43a3ab4455b2d6733223579fee");
+ assert(jan && sep && jan != sep && jan->revision == 202601 && sep->revision == 202609);
+ assert(!dock_client_layout(NULL) && !dock_client_layout("") && !dock_client_layout("71b391fe"));
+ char changed[66]; strcpy(changed, jan->sha256); changed[63] = '1';
+ assert(!dock_client_layout(changed));
+ strcpy(changed, jan->sha256); strcat(changed, "0");
+ assert(!dock_client_layout(changed));
+ uintptr_t base = 0x10000000;
+ void *vtable[216] = {0}; void **object = vtable;
+ vtable[8] = (void *)(base + jan->engine_user);
+ assert(dock_method_is(base, &object, 8, jan->engine_user));
+ assert(!dock_method_is(base, &object, 8, sep->engine_user));
+ assert(!dock_method_is(base, &object, 7, jan->engine_user));
+ assert(jan->ceg_request == 0x82a8c0 && sep->ceg_request == 0x84e8b0);
+ /* Offline logon: slots 5, 214 and 215, pinned per build. */
+ assert(jan->logon_state == 0x7612c0 && jan->can_offline == 0x720330 && jan->logon_offline == 0x81dad0);
+ assert(sep->logon_state == 0x77e460 && sep->can_offline == 0x73cbb0 && sep->logon_offline == 0x8415d0);
+ vtable[215] = (void *)(base + jan->logon_offline);
+ assert(dock_method_is(base, &object, 215, jan->logon_offline));
+ assert(!dock_method_is(base, &object, 215, sep->logon_offline));
+ assert(!dock_method_is(base, &object, 214, jan->logon_offline));
+ assert(!dock_method_is(base + 1, &object, 8, jan->engine_user));
+ assert(!dock_method_is(base, NULL, 8, jan->engine_user));
+ object = NULL;
+ assert(!dock_method_is(base, &object, 8, jan->engine_user));
+ puts("PASS: exact client selection, unknown/partial/changed hash rejection and mismatched method rejection");
+}
diff --git a/server/dock/tests/test-probe.c b/server/dock/tests/test-probe.c
new file mode 100644
index 00000000..d5e551da
--- /dev/null
+++ b/server/dock/tests/test-probe.c
@@ -0,0 +1,108 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ * Copyright 2026 125hz
+ * Madeira Converter Exception: see LICENSE-EXCEPTION.md
+ * Host-native fake-API tests. No Steam binaries, accounts or network are used.
+ * Exercise handle cleanup, a permanently busy callback queue, and invalid data.
+ */
+#include "probe.h"
+#include
+#include
+#include
+
+static int scenario, creates, releases, pipe_releases, borrowed, freed, events;
+static int sleeps, state_reads;
+static uint64_t clock_ms;
+
+static int32_t create_user(int32_t *pipe)
+{
+ ++creates;
+ *pipe = scenario == 1 ? 0 : 7;
+ return scenario <= 2 ? 0 : 8;
+}
+static void release_user(int32_t pipe, int32_t user)
+{
+ assert(pipe == 7 && user == 8 && borrowed == freed);
+ assert(pipe_releases == 0);
+ ++releases;
+}
+static bool release_pipe(int32_t pipe)
+{
+ assert(pipe == 7);
+ if (scenario > 2) assert(releases == 1);
+ ++pipe_releases;
+ return scenario != 7;
+}
+static bool get_callback(int32_t pipe, struct sh_callback *msg)
+{
+ assert(pipe == 7 && borrowed == freed);
+ if (scenario == 3 || scenario == 7) return false;
+ msg->user = 8;
+ msg->id = 101;
+ /* Deliberately invalid-to-read address: payloads must never be inspected. */
+ msg->data = (void *)(uintptr_t)1;
+ msg->size = 4;
+ if (scenario == 5) msg->size = -1;
+ if (scenario == 8) msg->data = NULL;
+ ++borrowed;
+ return true;
+}
+static void free_callback(int32_t pipe)
+{
+ assert(pipe == 7 && borrowed == freed + 1);
+ ++freed;
+}
+static bool logged_on(int32_t user, int32_t pipe)
+{
+ assert(user == 8 && pipe == 7);
+ ++state_reads;
+ return scenario == 6;
+}
+static uint64_t now_ms(void) { return clock_ms; }
+static void sleep_ms(uint32_t ms)
+{
+ assert(ms == 20);
+ ++sleeps;
+ if (scenario != 6) clock_ms += ms;
+}
+static void event(const char *stage, int32_t value)
+{
+ assert(stage && strlen(stage) < 64);
+ (void)value;
+ ++events;
+}
+
+int main(void)
+{
+ const struct sh_api api = {create_user, release_user, release_pipe,
+ get_callback, free_callback, logged_on};
+ const struct sh_observer observer = {now_ms, sleep_ms, event};
+ struct sh_api missing = api;
+ missing.free_callback = NULL;
+ assert(sh_probe_bootstrap(NULL, &observer) == SH_BAD_API);
+ assert(sh_probe_bootstrap(&api, NULL) == SH_BAD_API);
+ assert(sh_probe_bootstrap(&missing, &observer) == SH_BAD_API);
+ assert(creates == 0);
+
+ for (scenario = 1; scenario <= 8; ++scenario) {
+ creates = releases = pipe_releases = borrowed = freed = events = 0;
+ sleeps = state_reads = 0;
+ clock_ms = 0;
+ int result = sh_probe_bootstrap(&api, &observer);
+ assert(creates == 1 && borrowed == freed);
+ assert(releases == (scenario > 2 ? 1 : 0));
+ assert(pipe_releases == (scenario > 1 ? 1 : 0));
+ assert(events <= 16);
+ if (scenario <= 2) {
+ assert(result == SH_CREATE_FAILED && sleeps == 0 && state_reads == 0);
+ } else if (scenario == 5 || scenario == 8) {
+ assert(result == SH_CALLBACK_INVALID && borrowed == 1 && sleeps == 0);
+ } else {
+ assert(result == (scenario == 7 ? SH_RELEASE_FAILED : SH_OK));
+ assert(sleeps == 250 && state_reads == 2);
+ }
+ if (scenario == 4 || scenario == 6) assert(borrowed == 16000);
+ if (scenario == 6) assert(clock_ms == 0); /* stalled clock stays bounded */
+ }
+ puts("steam-host: 11 bootstrap lifecycle and failure scenarios passed");
+ return 0;
+}
diff --git a/server/dock/tests/test-validation.c b/server/dock/tests/test-validation.c
new file mode 100644
index 00000000..15900395
--- /dev/null
+++ b/server/dock/tests/test-validation.c
@@ -0,0 +1,224 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ * Copyright 2026 125hz
+ * Madeira Converter Exception: see LICENSE-EXCEPTION.md */
+#include "validation.h"
+#include
+#include
+#include
+int main(void)
+{
+ uint32_t option = 99;
+ assert(sh_parse_launch_option("0", &option) && option == 0);
+ assert(sh_parse_launch_option("1", &option) && option == 1);
+ assert(sh_parse_launch_option("17", &option) && option == 17);
+ assert(sh_parse_launch_option("2147483647", &option) && option == INT32_MAX);
+ assert(!sh_parse_launch_option("2147483648", &option));
+ assert(!sh_parse_launch_option("4294967295", &option));
+ assert(!sh_parse_launch_option("00000000000", &option));
+ assert(!sh_parse_launch_option("", &option) && !sh_parse_launch_option(NULL, &option));
+ assert(!sh_parse_launch_option("-1", &option) && !sh_parse_launch_option("+1", &option));
+ assert(!sh_parse_launch_option(" 1", &option) && !sh_parse_launch_option("1x", &option));
+ assert(!sh_parse_launch_option("1", NULL));
+ unsigned char missing[524] = {0};
+ const char missing_text[] = "entry for launch option 7 not found";
+ memcpy(missing + 12, missing_text, sizeof(missing_text));
+ assert(sh_launch_option_missing(missing, sizeof(missing), 7));
+ assert(!sh_launch_option_missing(missing, sizeof(missing), 0));
+ assert(!sh_launch_option_missing(missing, 12, 7));
+ assert(!sh_launch_option_missing(NULL, sizeof(missing), 7));
+ memset(missing + 12, 'x', 512);
+ assert(!sh_launch_option_missing(missing, sizeof(missing), 7));
+ memset(missing + 12, 0, 512);
+ const char pending_text[] = "configuration not yet available";
+ memcpy(missing + 12, pending_text, sizeof(pending_text));
+ assert(!sh_launch_option_missing(missing, sizeof(missing), 7));
+ assert(sh_launch_arguments_valid("", 0));
+ const char *arguments = "--renderer portable --label \"two words\"";
+ assert(sh_launch_arguments_valid(arguments, strlen(arguments)));
+ assert(sh_launch_arguments_valid("--value\t123", 11));
+ assert(!sh_launch_arguments_valid(NULL, 0));
+ assert(!sh_launch_arguments_valid("a\0b", 3));
+ assert(!sh_launch_arguments_valid("a\nb", 3));
+ assert(!sh_launch_arguments_valid("a\rb", 3));
+ assert(!sh_launch_arguments_valid("\"unclosed", 9));
+ const char escaped[] = {'"', 'a', '\\', '"', 'b', '"', 0};
+ const char unclosed[] = {'"', 'a', '\\', '"', 0};
+ assert(sh_launch_arguments_valid(escaped, sizeof escaped - 1));
+ assert(!sh_launch_arguments_valid(unclosed, sizeof unclosed - 1));
+ assert(!sh_launch_arguments_valid("a\177b", 3));
+ char bound[SH_LAUNCH_ARGUMENTS_CAPACITY];
+ memset(bound, 'x', sizeof bound);
+ assert(sh_launch_arguments_valid(bound, sizeof bound - 1));
+ assert(!sh_launch_arguments_valid(bound, sizeof bound));
+ char tokens[130];
+ for (size_t i = 0; i < sizeof tokens; ++i) tokens[i] = i % 2 ? ' ' : 'x';
+ assert(sh_launch_arguments_valid(tokens, 128));
+ assert(!sh_launch_arguments_valid(tokens, 130));
+ uint32_t apps[] = {17, 29, 44, 0};
+ assert(sh_subscription_list_contains(apps, 3, 4, 29));
+ assert(!sh_subscription_list_contains(apps, 3, 4, 30));
+ assert(!sh_subscription_list_contains(NULL, 3, 4, 29));
+ assert(!sh_subscription_list_contains(apps, -1, 4, 29));
+ assert(!sh_subscription_list_contains(apps, 0, 4, 29));
+ assert(!sh_subscription_list_contains(apps, 4, 4, 29));
+ assert(!sh_subscription_list_contains(apps, INT32_MAX, 4, 29));
+ assert(!sh_subscription_list_contains(apps, 3, 4, 0));
+ assert(!sh_subscription_list_contains(apps, 3, 4, UINT32_MAX));
+ unsigned char payload[524] = {0};
+ uint64_t gameid = 29;
+ int32_t error = -1, denied = 5;
+ memcpy(payload, &gameid, 8);
+ assert(sh_decode_launch_result(payload, sizeof(payload), gameid, &error) && error == 0);
+ memcpy(payload+8, &denied, 4);
+ assert(sh_decode_launch_result(payload, sizeof(payload), gameid, &error) && error == denied);
+ assert(!sh_decode_launch_result(payload, sizeof(payload), gameid+1, &error));
+ assert(!sh_decode_launch_result(payload, 12, gameid, &error));
+ assert(!sh_decode_launch_result(payload, 528, gameid, &error));
+ assert(!sh_decode_launch_result(NULL, 524, gameid, &error));
+ assert(!sh_decode_launch_result(payload, 524, gameid, NULL));
+ assert(sh_launch_error_waits_for_content(17));
+ assert(sh_launch_error_waits_for_content(19));
+ assert(sh_launch_error_waits_for_content(20));
+ assert(!sh_launch_error_waits_for_content(0));
+ assert(!sh_launch_error_waits_for_content(5));
+ assert(!sh_launch_error_waits_for_content(6));
+ assert(!sh_launch_error_waits_for_content(-1));
+ assert(sh_launch_error_waits_for_config(22) && sh_launch_error_waits_for_config(23));
+ assert(!sh_launch_error_waits_for_config(17) && !sh_launch_error_waits_for_config(24) &&
+ !sh_launch_error_waits_for_config(5) && !sh_launch_error_waits_for_config(0));
+ assert(sh_launch_error_waits_for_session(35) && !sh_launch_error_waits_for_session(16) &&
+ !sh_launch_error_waits_for_session(22) && !sh_launch_error_waits_for_session(0));
+ assert(sh_launch_retry_delay_ms(0) == 10000 && sh_launch_retry_delay_ms(1) == 20000);
+ assert(sh_launch_retry_delay_ms(2) == 30000 && sh_launch_retry_delay_ms(900) == 30000);
+ unsigned char job[12] = {0};
+ int32_t ok = 1, busy = 10, ceg = 0;
+ uint32_t app = 29;
+ memcpy(job, &ok, 4); memcpy(job+4, &app, 4);
+ assert(sh_decode_ceg_job(job, 8, 29, &ceg) && ceg == 1);
+ assert(!sh_decode_ceg_job(job, 8, 30, &ceg));
+ assert(!sh_decode_ceg_job(job, 12, 29, &ceg));
+ assert(!sh_decode_ceg_job(job, 4, 29, &ceg));
+ assert(!sh_decode_ceg_job(NULL, 8, 29, &ceg));
+ assert(!sh_decode_ceg_job(job, 8, 29, NULL));
+ assert(!sh_decode_ceg_job(job, 8, 0, &ceg));
+ memcpy(job, &busy, 4);
+ assert(sh_decode_ceg_reply(job, 12, 29, &ceg) && ceg == 10);
+ assert(!sh_decode_ceg_reply(job, 8, 29, &ceg));
+ struct sh_ceg_progress progress = {0};
+ assert(sh_ceg_request_step(10, 0, &progress) == SH_CEG_RETRY);
+ assert(sh_ceg_request_step(1, 0, &progress) == SH_CEG_FAIL && progress.failure == 0);
+ assert(sh_ceg_request_step(2, 0, &progress) == SH_CEG_FAIL && progress.failure == 2);
+ assert(sh_ceg_request_step(55, 3, &progress) == SH_CEG_FAIL && progress.failure == 55);
+ assert(sh_ceg_request_step(1, UINT32_MAX, &progress) == SH_CEG_FAIL);
+ assert(sh_ceg_request_step(1, SH_CEG_MAX_JOBS + 1, &progress) == SH_CEG_FAIL);
+ assert(sh_ceg_request_step(1, 2, NULL) == SH_CEG_FAIL);
+ assert(sh_ceg_request_step(1, 2, &progress) == SH_CEG_WAIT && progress.expected == 2);
+ assert(sh_ceg_record_job(&progress, 1) == SH_CEG_WAIT);
+ assert(sh_ceg_record_job(&progress, 1) == SH_CEG_DONE);
+ assert(sh_ceg_record_job(&progress, 1) == SH_CEG_FAIL);
+ assert(sh_ceg_request_step(1, 2, &progress) == SH_CEG_WAIT && progress.finished == 0);
+ assert(sh_ceg_record_job(&progress, 3) == SH_CEG_FAIL && progress.failure == 3);
+ assert(sh_ceg_request_step(1, 1, &progress) == SH_CEG_WAIT);
+ assert(sh_ceg_record_job(&progress, 0) == SH_CEG_FAIL);
+ struct sh_ceg_progress empty = {0};
+ assert(sh_ceg_record_job(&empty, 1) == SH_CEG_FAIL && sh_ceg_record_job(NULL, 1) == SH_CEG_FAIL);
+ /* ml2000: service-manager decisions. */
+ assert(sh_scm_error_means_absent(1722));
+ assert(!sh_scm_error_means_absent(1723) && !sh_scm_error_means_absent(5) && !sh_scm_error_means_absent(0));
+ assert(sh_scm_error_retryable(1722) && sh_scm_error_retryable(1723));
+ assert(!sh_scm_error_retryable(5) && !sh_scm_error_retryable(1060) && !sh_scm_error_retryable(0));
+ assert(sh_scm_poll_slice_ms(0) == 0 && sh_scm_poll_slice_ms(1) == 1);
+ assert(sh_scm_poll_slice_ms(SH_SCM_POLL_MS) == SH_SCM_POLL_MS && SH_SCM_POLL_MS == 250);
+ assert(sh_scm_poll_slice_ms(30000) == SH_SCM_POLL_MS && sh_scm_poll_slice_ms(UINT32_MAX - 1) == SH_SCM_POLL_MS);
+ assert(sh_ceg_scm_result(true, true) == 0);
+ assert(sh_ceg_scm_result(true, false) == SH_CEG_SERVICE_UNREGISTERED && SH_CEG_SERVICE_UNREGISTERED == -5);
+ assert(sh_ceg_scm_result(false, true) == SH_CEG_SCM_UNAVAILABLE && SH_CEG_SCM_UNAVAILABLE == -4);
+ assert(sh_ceg_scm_result(false, false) == SH_CEG_SCM_UNAVAILABLE);
+ assert(sh_remaining_ms(1000, 1000, 30000) == 30000);
+ assert(sh_remaining_ms(30999, 1000, 30000) == 1);
+ assert(sh_remaining_ms(31000, 1000, 30000) == 0 && sh_remaining_ms(UINT64_MAX, 0, 30000) == 0);
+ assert(sh_remaining_ms(500, 1000, 30000) == 30000);
+ assert(sh_remaining_ms(0, 0, UINT64_MAX) == UINT32_MAX - 1);
+ assert(sh_service_stop_outcome(false, false, false, false) == SH_SERVICE_NOT_RUNNING);
+ assert(sh_service_stop_outcome(false, true, true, true) == SH_SERVICE_NOT_RUNNING);
+ assert(sh_service_stop_outcome(true, true, true, false) == SH_SERVICE_STOPPED);
+ assert(sh_service_stop_outcome(true, true, false, true) == SH_SERVICE_ENDED_AFTER_BOUND);
+ assert(sh_service_stop_outcome(true, false, false, true) == SH_SERVICE_ENDED_AFTER_BOUND);
+ assert(sh_service_stop_outcome(true, true, false, false) == SH_SERVICE_STOP_FAILED);
+ assert(sh_service_stop_outcome(true, false, true, false) == SH_SERVICE_STOP_FAILED);
+ /* ml2000: Valve's own service installer decision and report value. */
+ assert(sh_should_install_service(false, true, true));
+ assert(!sh_should_install_service(false, true, false));
+ assert(!sh_should_install_service(true, false, true) && !sh_should_install_service(true, true, true));
+ assert(!sh_should_install_service(false, false, true));
+ assert(sh_service_install_report(false, true, 0) == SH_SERVICE_INSTALL_MISSING && SH_SERVICE_INSTALL_MISSING == -2);
+ assert(sh_service_install_report(true, false, 0) == SH_SERVICE_INSTALL_TIMEOUT && SH_SERVICE_INSTALL_TIMEOUT == -1);
+ assert(sh_service_install_report(true, true, 0) == 0 && sh_service_install_report(true, true, 5) == 5);
+ assert(sh_service_install_report(true, true, 0xC0000005u) == (int32_t)0xC0000005u);
+ /* ml2014: --start-services for the one-time-install batch. */
+ assert(sh_install_scm_should_spawn(true, 1722));
+ assert(!sh_install_scm_should_spawn(false, 1722));
+ assert(!sh_install_scm_should_spawn(true, 0) && !sh_install_scm_should_spawn(true, 1723) &&
+ !sh_install_scm_should_spawn(true, 5));
+ assert(sh_install_scm_outcome(false, 1722, false, false) == SH_INSTALL_SCM_OFF);
+ assert(sh_install_scm_outcome(false, 0, false, true) == SH_INSTALL_SCM_OFF);
+ assert(sh_install_scm_outcome(true, 0, false, true) == SH_INSTALL_SCM_ALREADY);
+ assert(sh_install_scm_outcome(true, 1722, true, true) == SH_INSTALL_SCM_STARTED);
+ assert(sh_install_scm_outcome(true, 1722, false, true) == SH_INSTALL_SCM_ALREADY);
+ assert(sh_install_scm_outcome(true, 1722, true, false) == SH_INSTALL_SCM_FAILED);
+ assert(sh_install_scm_outcome(true, 5, false, false) == SH_INSTALL_SCM_FAILED);
+ assert(!strcmp(sh_install_scm_word(SH_INSTALL_SCM_STARTED), "started"));
+ assert(!strcmp(sh_install_scm_word(SH_INSTALL_SCM_ALREADY), "already"));
+ assert(!strcmp(sh_install_scm_word(SH_INSTALL_SCM_OFF), "off"));
+ assert(!strcmp(sh_install_scm_word(SH_INSTALL_SCM_FAILED), "failed"));
+ assert(!strcmp(sh_install_scm_word(7), "failed"));
+ /* ml2020: the game session's service manager (auto: a foreign automatic service). */
+ assert(sh_game_scm_mode(NULL) == SH_GAME_SCM_AUTO && sh_game_scm_mode(L"") == SH_GAME_SCM_AUTO);
+ assert(sh_game_scm_mode(L"0") == SH_GAME_SCM_OFF && sh_game_scm_mode(L"1") == SH_GAME_SCM_ON);
+ assert(sh_game_scm_mode(L"01") == SH_GAME_SCM_AUTO && sh_game_scm_mode(L"auto") == SH_GAME_SCM_AUTO);
+ const wchar_t *windows = L"C:\\windows";
+ assert(sh_path_in_folder(L"C:\\windows\\system32\\services.exe", windows));
+ assert(sh_path_in_folder(L"c:/WINDOWS/system32/svchost.exe", L"C:\\Windows\\"));
+ assert(!sh_path_in_folder(L"C:\\windows2\\x.exe", windows));
+ assert(!sh_path_in_folder(L"C:\\windows", windows) && !sh_path_in_folder(L"C:\\win", windows));
+ assert(!sh_path_in_folder(NULL, windows) && !sh_path_in_folder(L"C:\\windows\\a", NULL) &&
+ !sh_path_in_folder(L"C:\\windows\\a", L"\\"));
+ assert(sh_image_is_windows(L"%SystemRoot%\\system32\\svchost.exe -k netsvcs", windows));
+ assert(sh_image_is_windows(L"\\SystemRoot\\System32\\drivers\\mountmgr.sys", windows));
+ assert(sh_image_is_windows(L"System32\\DRIVERS\\x.sys", windows));
+ assert(sh_image_is_windows(L"\\??\\C:\\windows\\system32\\drivers\\y.sys", windows));
+ assert(sh_image_is_windows(L"\"C:\\windows\\system32\\msiexec.exe\" /V", windows));
+ assert(!sh_image_is_windows(L"\"C:\\Program Files\\Publisher\\Launcher\\Service.exe\"", windows));
+ assert(!sh_image_is_windows(L"C:\\Games\\game\\service.exe", windows) && !sh_image_is_windows(NULL, windows));
+ /* type 0x10 own process, 0x20 shared; start 2 automatic, 3 demand, 4 disabled */
+ assert(sh_service_is_foreign_autostart(0x10, 2, L"\"C:\\Program Files\\Publisher\\Service.exe\"", windows));
+ assert(sh_service_is_foreign_autostart(0x20, 2, L"C:\\Games\\svc.exe --run", windows));
+ assert(sh_service_is_foreign_autostart(0x10, 3, L"C:\\Games\\svc.exe", windows)); /* demand start: the program starts it */
+ assert(!sh_service_is_foreign_autostart(0x10, 4, L"C:\\Games\\svc.exe", windows)); /* disabled */
+ assert(!sh_service_is_foreign_autostart(0x10, 0, L"C:\\Games\\svc.exe", windows) &&
+ !sh_service_is_foreign_autostart(0x10, 1, L"C:\\Games\\svc.exe", windows)); /* boot and system start: drivers */
+ assert(!sh_service_is_foreign_autostart(0x1, 2, L"C:\\Games\\drv.sys", windows));
+ assert(!sh_service_is_foreign_autostart(0x10, 2, L"%SystemRoot%\\system32\\svchost.exe -k x", windows));
+ assert(!sh_service_is_foreign_autostart(0x10, 2, L"C:\\windows\\system32\\spoolsv.exe", windows));
+ assert(!sh_service_is_foreign_autostart(0x10, 2, L"", windows) && !sh_service_is_foreign_autostart(0x10, 2, L"\"\"", windows));
+ assert(!sh_service_is_foreign_autostart(0x10, 2, NULL, windows));
+ assert(!sh_game_scm_wanted(SH_GAME_SCM_OFF, 5) && sh_game_scm_wanted(SH_GAME_SCM_ON, 0));
+ assert(!sh_game_scm_wanted(SH_GAME_SCM_AUTO, 0) && sh_game_scm_wanted(SH_GAME_SCM_AUTO, 1));
+ /* ml2020: the hold while a launcher restarts. */
+ assert(sh_keep_alive_mode(NULL) == SH_KEEP_ALIVE_AUTO && sh_keep_alive_mode(L"") == SH_KEEP_ALIVE_AUTO);
+ assert(sh_keep_alive_mode(L"0") == SH_KEEP_ALIVE_OFF && sh_keep_alive_mode(L"1") == SH_KEEP_ALIVE_AUTO);
+ assert(sh_keep_alive_mode(L"Launcher.exe;Game.exe") == SH_KEEP_ALIVE_AUTO);
+ assert(sh_keep_alive_listed(L"Launcher.exe;Game.exe", L"launcher.EXE"));
+ assert(sh_keep_alive_listed(L"Launcher.exe; Game.exe ", L"game.exe"));
+ assert(sh_keep_alive_listed(L";;Game.exe", L"Game.exe") && sh_keep_alive_listed(L"Game.exe", L"Game.exe"));
+ assert(!sh_keep_alive_listed(L"Launcher.exe;Game.exe", L"Game.ex") && !sh_keep_alive_listed(L"Launcher.exe", L"Launcher.exe2"));
+ assert(!sh_keep_alive_listed(L"", L"Game.exe") && !sh_keep_alive_listed(NULL, L"Game.exe") &&
+ !sh_keep_alive_listed(L"Game.exe", L"") && !sh_keep_alive_listed(L"Game.exe", NULL));
+ assert(!sh_keep_alive_listed(L"1", L"Game.exe"));
+ assert(sh_keep_alive_holds(false, true, 10 * 60000ULL, SH_KEEP_ALIVE_YOUNG_MS));
+ assert(sh_keep_alive_holds(false, false, 5000, SH_KEEP_ALIVE_YOUNG_MS));
+ assert(!sh_keep_alive_holds(false, false, SH_KEEP_ALIVE_YOUNG_MS, SH_KEEP_ALIVE_YOUNG_MS));
+ assert(!sh_keep_alive_holds(true, true, 0, SH_KEEP_ALIVE_YOUNG_MS));
+ puts("steam-host: launch-option, launch-arguments, entitlement-list, launch-result, content-wait, config-wait, session-wait, CEG, service-manager, "
+ "install-service-manager, game-service-manager and keep-alive validation cases passed");
+}
diff --git a/server/dock/tools/check-client-layout.py b/server/dock/tools/check-client-layout.py
new file mode 100644
index 00000000..ee2d9167
--- /dev/null
+++ b/server/dock/tools/check-client-layout.py
@@ -0,0 +1,84 @@
+#!/usr/bin/env python3
+# SPDX-License-Identifier: GPL-3.0-or-later
+# Copyright 2026 125hz
+# Madeira Converter Exception: see LICENSE-EXCEPTION.md
+"""Read-only check of pinned RVAs against an independently obtained Valve DLL.
+
+No Valve binaries are distributed with Dock. This check uses PE/RTTI metadata,
+not execution, and needs only Python's standard library. It does not establish
+call signatures; retain the disassembly review in docs/CLIENT_LAYOUTS.md.
+"""
+from pathlib import Path
+import hashlib, re, struct, sys
+
+raw = Path(sys.argv[1]).read_bytes()
+fingerprint = hashlib.sha256(raw).hexdigest()
+source = (Path(__file__).resolve().parents[1] / 'src/client_layout.c').read_text()
+block = re.search(r'"' + fingerprint + r'",\s*(\d+),([^}]+)', source)
+assert block, 'Unknown SHA-256; never infer a layout from similar metadata'
+rvas = [int(x, 16) for x in re.findall(r'0x[0-9a-f]+', block[2])]
+assert len(rvas) == 18
+pe = struct.unpack_from('&1 | tail -3 || fail=1
python3 tests/selftest_lite.py | tail -2 || fail=1
+step "madeira dock (unit tests, tools)"
+bash dock/check.sh | tail -2 || fail=1
+python3 -m py_compile dock/tools/check-client-layout.py || fail=1
+
step "compose"
WORLD=check docker compose -f compose.yaml config -q || fail=1
WORLD=check docker compose -f compose.yaml -f compose.build.yaml config -q || fail=1
From b48071c9f1065b5e9bf05ce8e82f0a73e99a32a0 Mon Sep 17 00:00:00 2001
From: ampynjord <82981605+ampynjord@users.noreply.github.com>
Date: Thu, 19 Nov 2026 16:15:48 +0100
Subject: [PATCH 14/47] CI/CD inside the project's workflows: ci.yml
(docker-server-checks, docker-server) and release.yml (docker_server option)
like the relay's image; shared smoke tests; standalone workflow removed
---
.github/workflows/ci.yml | 50 +++++++
.github/workflows/dedicated-server.yml | 182 -------------------------
.github/workflows/release.yml | 69 ++++++++++
docs/CHANGELOG.txt | 2 +-
docs/DOCKER-SERVER.md | 19 ++-
server/tests/check.sh | 2 +-
server/tests/smoke.sh | 27 ++++
7 files changed, 160 insertions(+), 191 deletions(-)
delete mode 100644 .github/workflows/dedicated-server.yml
create mode 100644 server/tests/smoke.sh
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 683bcd48..d7621487 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -129,3 +129,53 @@ jobs:
- name: Compose file
run: MPFEVER_RELAY_PASSWORD=ci docker compose -f relay/compose.yaml config -q
+
+ # The dedicated server in Docker (server/, docs/DOCKER-SERVER.md): shell (shellcheck), Python, Madeira Dock's unit tests, Compose files, no secrets, no
+ # binaries, no game or Valve file.
+ docker-server-checks:
+ runs-on: ubuntu-24.04
+ timeout-minutes: 10
+ steps:
+ - uses: actions/checkout@v4
+
+ - name: Tools
+ run: sudo apt-get update -qq && sudo apt-get install -y -qq shellcheck
+
+ - name: Static checks
+ run: bash server/tests/check.sh
+
+ # ... and its image, built from this commit's server archive (the job "build" above), then smoke-tested: it runs unprivileged, holds no game or
+ # Valve file, and an empty volume gives explicit messages. Nothing is pushed: the image is published by the Release build workflow.
+ docker-server:
+ needs: [build, docker-server-checks]
+ runs-on: ubuntu-24.04
+ timeout-minutes: 45
+ steps:
+ - uses: actions/checkout@v4
+
+ - uses: actions/download-artifact@v4
+ with:
+ name: MPFever-${{ github.sha }}
+ path: server/dist
+
+ - name: The server archive is the image's input
+ working-directory: server/dist
+ run: |
+ ls -l
+ cp ./MPFever-*-server.zip MPFever-server.zip
+
+ - uses: docker/setup-buildx-action@v3
+
+ - name: Build the image
+ uses: docker/build-push-action@v6
+ with:
+ context: server
+ load: true
+ tags: mpfever-server:ci
+ build-args: |
+ VCS_REF=${{ github.sha }}
+ cache-from: type=gha
+ cache-to: type=gha,mode=max
+
+ - name: Smoke tests
+ run: bash server/tests/smoke.sh mpfever-server:ci
diff --git a/.github/workflows/dedicated-server.yml b/.github/workflows/dedicated-server.yml
deleted file mode 100644
index f1d03bfc..00000000
--- a/.github/workflows/dedicated-server.yml
+++ /dev/null
@@ -1,182 +0,0 @@
-# The dedicated server in Docker (server/, docs/DOCKER-SERVER.md): static checks (shell, Python, Dock's unit tests, Compose, no secrets), the package, the image built (Dock built from server/dock/, with its tests) and smoke-tested.
-#
-# The image always carries the LATEST OFFICIAL MPFever release: the package is built from that release's tag (build.bat) with the launcher
-# changes of this branch applied on top (they disappear from the patch once a release contains them). So players on the official release can join.
-#
-# Publication to GHCR (ghcr.io//mpfever-server, named like the relay's mpfever-relay) happens ONLY on purpose, after every job above has passed:
-# - pushing a tag dedicated-server-v[-] (for example dedicated-server-v0.9.1): image tags "[-]" and "experimental"
-# - or a manual run (workflow_dispatch, workflow file on the default branch) with "publish" ticked.
-# A push or a pull request never publishes.
-name: Dedicated server
-
-on:
- pull_request:
- paths: ["server/**", "launcher/**", ".github/workflows/dedicated-server.yml"]
- push:
- branches: [main, "feature/dedicated-server"]
- tags: ["dedicated-server-v*"]
- paths: ["server/**", "launcher/**", ".github/workflows/dedicated-server.yml"]
- workflow_dispatch:
- inputs:
- publish:
- description: "Push the image to GHCR (only after the tests pass)"
- type: boolean
- default: false
- version_tag:
- description: "Image tag besides 'experimental' (the MPFever version, for example 0.9.1); empty: only 'experimental'"
- type: string
- default: ""
- mpfever_ref:
- description: "MPFever release tag to build the package from; empty: the latest official release"
- type: string
- default: ""
-
-concurrency:
- group: dedicated-server-${{ github.ref }}
- cancel-in-progress: true
-
-permissions:
- contents: read
-
-env:
- UPSTREAM: https://github.com/dkdknight/MPFever.git
-
-jobs:
- static:
- runs-on: ubuntu-24.04
- timeout-minutes: 10
- steps:
- - uses: actions/checkout@v4
- - name: Tools
- run: sudo apt-get update -qq && sudo apt-get install -y -qq shellcheck
- - name: Static checks (shell, Python, Compose, no secrets, no binaries)
- run: bash server/tests/check.sh
-
- package:
- # The same build as ci.yml (native module, launcher with warnings as errors, tests, archives), of the latest official release + this branch's launcher changes.
- runs-on: windows-2022
- timeout-minutes: 40
- outputs:
- mpfever_version: ${{ steps.ref.outputs.version }}
- steps:
- - uses: actions/checkout@v4
- with:
- fetch-depth: 0
- - uses: actions/setup-python@v5
- with:
- python-version: "3.12"
- - run: python -m pip install lupa==2.8
- - name: Release to build, and the launcher changes of this branch
- id: ref
- shell: bash
- env:
- GH_TOKEN: ${{ github.token }}
- WANTED: ${{ inputs.mpfever_ref }}
- run: |
- set -eu
- tag="${WANTED:-}"
- [ -n "$tag" ] || tag=$(gh release view --repo dkdknight/MPFever --json tagName --jq .tagName)
- echo "official release: $tag"
- git remote add upstream "$UPSTREAM" 2>/dev/null || true
- git fetch -q upstream main "refs/tags/$tag:refs/tags/upstream-$tag"
- git diff "upstream/main...HEAD" -- launcher > "$RUNNER_TEMP/launcher.patch"
- git worktree add -q --detach release-src "upstream-$tag"
- cd release-src
- if [ ! -s "$RUNNER_TEMP/launcher.patch" ]; then echo "no launcher changes to apply"
- elif git apply --reverse --check --ignore-whitespace "$RUNNER_TEMP/launcher.patch" 2>/dev/null; then echo "the release already contains the launcher changes"
- else git apply --ignore-whitespace "$RUNNER_TEMP/launcher.patch" && echo "launcher changes applied"; fi
- echo "version=$tag" >> "$GITHUB_OUTPUT"
- - name: Build, test, pack
- shell: pwsh
- working-directory: release-src
- run: |
- cmd /c build.bat 2>&1 | Tee-Object -FilePath build.log
- if ($LASTEXITCODE -ne 0) { exit 1 }
- - uses: actions/upload-artifact@v4
- with:
- name: MPFever-server-package-${{ github.sha }}
- path: release-src/release/MPFever-*-server.zip
- retention-days: 14
- if-no-files-found: error
-
- image:
- needs: [static, package]
- runs-on: ubuntu-24.04
- timeout-minutes: 45
- permissions:
- contents: read
- packages: write
- steps:
- - uses: actions/checkout@v4
- - uses: actions/download-artifact@v4
- with:
- name: MPFever-server-package-${{ github.sha }}
- path: server/dist
- - name: Package for the image
- working-directory: server/dist
- run: |
- ls -l
- cp ./*-server.zip MPFever-server.zip
- echo "PKG_VERSION=${{ needs.package.outputs.mpfever_version }}" >> "$GITHUB_ENV"
- - uses: docker/setup-buildx-action@v3
- - name: Build the image (not pushed)
- uses: docker/build-push-action@v6
- with:
- context: server
- load: true
- tags: mpfever-server:ci
- build-args: |
- VERSION=${{ env.PKG_VERSION }}
- VCS_REF=${{ github.sha }}
- SOURCE_REPO=${{ github.server_url }}/${{ github.repository }}
- cache-from: type=gha
- cache-to: type=gha,mode=max
- - name: Smoke tests
- run: |
- set -eu
- img=mpfever-server:ci
- # runs unprivileged
- test "$(docker run --rm --entrypoint id "$img" -u)" = 1001
- # contains no game file, no Valve file, no secret
- docker run --rm --entrypoint find "$img" / -xdev \( -iname 'TransportFever3.exe' -o -iname 'steamclient*.dll' -o -iname 'steam.exe' -o -iname 'steam.json' -o -iname '*.sav' \) -not -path '/proc/*' | tee /tmp/found
- test ! -s /tmp/found
- # licence texts and Dock are present, a healthcheck is defined
- docker run --rm --entrypoint sh "$img" -c 'test -f /opt/mpfever/dockhost.exe && test -f /opt/mpfever/licenses/madeira-dock/COPYING && test -f /opt/mpfever/pkg/MPFever.exe && test -f /opt/mpfever/pkg/winhttp.dll'
- docker inspect --format '{{.Config.Healthcheck.Test}}' "$img" | grep -q healthcheck.sh
- # pinned runtimes
- docker run --rm --entrypoint sh "$img" -c 'wine --version | grep -q "wine-11.0" && mono --version | head -1 && python3 -c "import qrcode"'
- # an empty volume gives explicit messages, not a crash
- docker volume create ci-data >/dev/null; docker volume create ci-game >/dev/null
- set +e
- out=$(docker run --rm -v ci-data:/data -v ci-game:/game "$img" status 2>&1); echo "$out"
- echo "$out" | grep -q "login" && echo "$out" | grep -q "install-game"
- out=$(docker run --rm -e WORLD=x -v ci-data:/data -v ci-game:/game "$img" run 2>&1); rc=$?; echo "$out"
- test $rc -eq 40 && echo "$out" | grep -q "run login"
- # the Dock build is the pinned one, the Vulkan layer loads
- docker run --rm --entrypoint sh "$img" -c 'ls -l /opt/mpfever/libVkLayer_mpf_nulldraw.so /etc/vulkan/implicit_layer.d/'
- - name: Decide the tags to publish
- id: tags
- run: |
- set -eu
- owner=$(echo "${{ github.repository_owner }}" | tr 'A-Z' 'a-z')
- pub=false; vtag=""
- if [ "${{ github.event_name }}" = workflow_dispatch ] && [ "${{ inputs.publish }}" = true ]; then pub=true; vtag="${{ inputs.version_tag }}"; fi
- if [ "${{ github.ref_type }}" = tag ]; then
- pub=true; vtag="${{ github.ref_name }}"; vtag="${vtag#dedicated-server-v}" # 0.9.1 or 0.9.1-2
- fi
- echo "publish=$pub" >> "$GITHUB_OUTPUT"; echo "repo=ghcr.io/$owner/mpfever-server" >> "$GITHUB_OUTPUT"; echo "vtag=$vtag" >> "$GITHUB_OUTPUT"
- - name: Log in to GHCR
- if: steps.tags.outputs.publish == 'true'
- uses: docker/login-action@v3
- with:
- registry: ghcr.io
- username: ${{ github.actor }}
- password: ${{ secrets.GITHUB_TOKEN }}
- - name: Publish (tag push or manual run only)
- if: steps.tags.outputs.publish == 'true'
- run: |
- set -eu
- repo=${{ steps.tags.outputs.repo }}; vtag=${{ steps.tags.outputs.vtag }}
- docker tag mpfever-server:ci "$repo:experimental"; docker push "$repo:experimental"
- if [ -n "$vtag" ]; then docker tag mpfever-server:ci "$repo:$vtag"; docker push "$repo:$vtag"; fi
- echo "published $repo:experimental ${vtag:+and $repo:$vtag}" >> "$GITHUB_STEP_SUMMARY"
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 891aab76..8f97e766 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -24,6 +24,10 @@ on:
- test-signing
- release-signing
default: test-signing
+ docker_server:
+ description: "Also publish the dedicated server's Docker image (x64; server/Dockerfile, docs/DOCKER-SERVER.md) to ghcr.io//mpfever-server, tagged with the version and experimental"
+ type: boolean
+ default: false
jobs:
release:
@@ -288,3 +292,68 @@ jobs:
path: release/Relay-MPFever-${{ steps.version.outputs.version }}-win-x64.zip
if-no-files-found: error
retention-days: 30
+
+ # (optional, off unless "docker_server" is ticked when the workflow is started: the dedicated server's image (server/Dockerfile), x64, on GitHub's
+ # container registry under the owner of the repository. It is built from this run's unsigned server archive (the image takes MPFever.exe, winhttp.dll and
+ # the mod from it; the signatures are for Windows), smoke-tested, then pushed as and experimental. It holds no Transport Fever 3 or Valve
+ # file: the game is imported from the user's own install and Valve's client library is fetched from Valve at the first start. The package's visibility is
+ # set on its page on GitHub)
+ docker-server:
+ if: ${{ inputs.docker_server }}
+ needs: release
+ runs-on: ubuntu-24.04
+ timeout-minutes: 60
+ permissions:
+ contents: read
+ packages: write
+ steps:
+ - uses: actions/checkout@v4
+
+ - name: Version and image name
+ id: v
+ run: |
+ echo "version=$(sed -n 's/^set "VERSION=\([^"]*\)".*/\1/p' build.bat | tr -d '\r')" >> "$GITHUB_OUTPUT"
+ echo "image=ghcr.io/${GITHUB_REPOSITORY_OWNER,,}/mpfever-server" >> "$GITHUB_OUTPUT"
+
+ - uses: actions/download-artifact@v4
+ with:
+ name: MPFever-${{ steps.v.outputs.version }}-unsigned
+ path: server/dist
+
+ - name: The server archive is the image's input
+ working-directory: server/dist
+ run: cp "MPFever-${{ steps.v.outputs.version }}-server.zip" MPFever-server.zip
+
+ - uses: docker/setup-buildx-action@v3
+
+ - name: Build the image
+ uses: docker/build-push-action@v6
+ with:
+ context: server
+ load: true
+ tags: mpfever-server:release
+ build-args: |
+ VERSION=${{ steps.v.outputs.version }}
+ VCS_REF=${{ github.sha }}
+ SOURCE_REPO=https://github.com/${{ github.repository }}
+
+ - name: Smoke tests
+ run: bash server/tests/smoke.sh mpfever-server:release
+
+ - uses: docker/login-action@v3
+ with:
+ registry: ghcr.io
+ username: ${{ github.actor }}
+ password: ${{ secrets.GITHUB_TOKEN }}
+
+ - name: Push
+ run: |
+ for t in "${{ steps.v.outputs.version }}" experimental; do
+ docker tag mpfever-server:release "${{ steps.v.outputs.image }}:$t"
+ docker push "${{ steps.v.outputs.image }}:$t"
+ done
+
+ - name: Summary
+ run: |
+ bt='`'
+ echo "- Docker image $bt${{ steps.v.outputs.image }}:${{ steps.v.outputs.version }}$bt (and $bt:experimental$bt), x64" | tee -a "$GITHUB_STEP_SUMMARY"
diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index faf6ec94..6ae2e960 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -9,7 +9,7 @@ MPFever - Changelog
(MPFEVER_WINE=1, MPFEVER_DOCK) and a stop file (MPFEVER_STOPFILE: the world is saved, then the server stops, as the console's "stop"); nothing changes on
Windows. The image (ghcr.io/ampynjord/mpfever-server, tagged with the MPFever version and "experimental") holds no game or Valve file; install-game,
login (QR code, no password), import-save and status are its administration commands. Validated end to end for short sessions with a real Windows
- client; long runs, several clients and large worlds are not yet (see the guide). CI: .github/workflows/dedicated-server.yml.
+ client; long runs, several clients and large worlds are not yet (see the guide). CI: ci.yml (jobs docker-server-checks and docker-server) and, to publish the image, release.yml (option docker_server).
- BUILD (code signing, 2026-11-19: SignPath Foundation accepted MPFever; their first step is a signature with their
self-signed test certificate, then they review the setup and import the Foundation's certificate): the Release build
workflow asks for the signing policy, test-signing by default, release-signing once the certificate is in. Archives signed
diff --git a/docs/DOCKER-SERVER.md b/docs/DOCKER-SERVER.md
index be4493bc..4f10e63b 100644
--- a/docs/DOCKER-SERVER.md
+++ b/docs/DOCKER-SERVER.md
@@ -94,8 +94,8 @@ rebuilt at any time with `install-game`). Back up `mpfever-data`.
| Disk | the "lite" install (`server/scripts/mklite.py`) | The engine reads archives at fixed offsets, so archives keep their layout: textures, audio and blobs become file holes (sparse), images stay valid but empty. Generated from the host's own copy, never distributed. |
| Display | `Xvfb` only | The game closes without an X server. Nothing is exposed: no VNC, no remote desktop. |
-The image is **versioned by the MPFever release** it carries (`0.9.1`, `0.9.1-2` for a rebuild) plus `experimental`: it is built from the latest official release's sources with the launcher
-changes of the Linux server applied, so the players' official client can join. The image holds no secret, no Transport Fever 3 file and no Valve file; the Valve client library is
+The image is **versioned by the MPFever version** it is built from (`ghcr.io//mpfever-server:`) plus `experimental`: it is built by the Release build workflow from the release's own server
+archive (run it on the release's tag), so the players' client of that version can join; the version the server and the players run must be the same. The image holds no secret, no Transport Fever 3 file and no Valve file; the Valve client library is
fetched from Valve at the first start (pinned build, hash-checked). Start (`server/scripts/entrypoint.sh run`): checks (disk, sparse support, RAM, game, session, savegame), first-start
Wine prefix, the launcher restarted when it exits (five failures within a minute stop the container with a message), `SIGTERM` writes the stop file: the world is saved, the game closed, then the container exits.
@@ -150,9 +150,14 @@ read-only container.
**Not validated yet:** runs of 30 minutes or more, memory growth over time, several clients (a second Steam account is needed, or local test clients), large worlds, enforced CPU/memory limits,
stopping while a client has vanished, the GPU variant.
-## Build and tests
+## Build, tests, publication
-`.github/workflows/dedicated-server.yml` runs the static checks (`server/tests/check.sh`: shell, Python tests, Compose, no secrets or binaries), runs Dock's unit tests, builds the package from the latest official release with the
-Docker server's launcher changes, builds the image, smoke-tests it (unprivileged, no game or Valve file inside, explicit errors on empty volumes) and publishes only when a tag
-`dedicated-server-v` is pushed or the workflow is run by hand with "publish" ticked. Locally: put a package built by `build.bat` in `server/dist/MPFever-server.zip` and
-`docker compose -f compose.yaml -f compose.build.yaml build` (`APT_MIRROR` can name another Ubuntu mirror).
+The project's two workflows cover it, like the relay's image:
+
+- `ci.yml`, on every push and pull request: **`docker-server-checks`** (`server/tests/check.sh`: shell and shellcheck, Python tests, Madeira Dock's unit tests, Compose files, no secrets, no
+ binaries) and **`docker-server`**, which builds the image from the commit's server archive (the `build` job) and smoke-tests it (`server/tests/smoke.sh`: unprivileged, no game or Valve file
+ inside, pinned runtimes, explicit errors on empty volumes). Nothing is pushed.
+- `release.yml` (Release build, started by hand): tick **`docker_server`** to also publish `ghcr.io//mpfever-server:` and `:experimental`, built from that run's unsigned server archive
+ and smoke-tested first (`docker` is the relay's image). Run it on the tag of a release to get the image of that release; the package's visibility is set on its page on GitHub.
+
+Locally: put a package built by `build.bat` in `server/dist/MPFever-server.zip` and `docker compose -f compose.yaml -f compose.build.yaml build` (`APT_MIRROR` can name another Ubuntu mirror).
diff --git a/server/tests/check.sh b/server/tests/check.sh
index b6160f7d..6201e59b 100644
--- a/server/tests/check.sh
+++ b/server/tests/check.sh
@@ -6,7 +6,7 @@ fail=0
step() { echo "== $*"; }
step "shell syntax"
-for f in scripts/*.sh tests/check.sh; do bash -n "$f" || fail=1; done
+for f in scripts/*.sh tests/check.sh tests/smoke.sh; do bash -n "$f" || fail=1; done
if command -v shellcheck >/dev/null; then step "shellcheck"; shellcheck -S warning scripts/*.sh || fail=1; fi
step "python"
diff --git a/server/tests/smoke.sh b/server/tests/smoke.sh
new file mode 100644
index 00000000..bd1a6f85
--- /dev/null
+++ b/server/tests/smoke.sh
@@ -0,0 +1,27 @@
+#!/usr/bin/env bash
+# Smoke tests of the built image (no game, no Steam): used by ci.yml and release.yml. Usage: smoke.sh
+set -eu
+img=${1:?usage: smoke.sh }
+echo "== runs unprivileged"
+test "$(docker run --rm --entrypoint id "$img" -u)" = 1001
+echo "== contains no game file, no Valve file, no secret"
+docker run --rm --entrypoint find "$img" / -xdev \( -iname 'TransportFever3.exe' -o -iname 'steamclient*.dll' -o -iname 'steam.exe' -o -iname 'steam.json' -o -iname '*.sav' \) -not -path '/proc/*' 2>/dev/null | tee /tmp/smoke-found
+test ! -s /tmp/smoke-found
+echo "== Dock, licences, package, healthcheck"
+docker run --rm --entrypoint sh "$img" -c 'test -f /opt/mpfever/dockhost.exe && test -f /opt/mpfever/licenses/madeira-dock/COPYING && test -f /opt/mpfever/pkg/MPFever.exe && test -f /opt/mpfever/pkg/winhttp.dll'
+docker inspect --format '{{.Config.Healthcheck.Test}}' "$img" | grep -q healthcheck.sh
+echo "== pinned runtimes"
+docker run --rm --entrypoint sh "$img" -c 'wine --version | grep -q "wine-11.0" && mono --version | head -1 && python3 -c "import qrcode"'
+echo "== an empty volume gives explicit messages, not a crash"
+vol=smoke-$$
+docker volume create "$vol-data" >/dev/null; docker volume create "$vol-game" >/dev/null
+trap 'docker volume rm "$vol-data" "$vol-game" >/dev/null 2>&1 || true' EXIT
+set +e
+out=$(docker run --rm -v "$vol-data":/data -v "$vol-game":/game "$img" status 2>&1); echo "$out"
+echo "$out" | grep -q "login" && echo "$out" | grep -q "install-game" || { echo "status: unexpected output"; exit 1; }
+out=$(docker run --rm -e WORLD=x -v "$vol-data":/data -v "$vol-game":/game "$img" run 2>&1); rc=$?; echo "$out"
+test $rc -eq 40 && echo "$out" | grep -q "run login" || { echo "run: expected exit 40 and a login message"; exit 1; }
+set -e
+echo "== the Vulkan layer is in place"
+docker run --rm --entrypoint sh "$img" -c 'ls -l /opt/mpfever/libVkLayer_mpf_nulldraw.so /etc/vulkan/implicit_layer.d/'
+echo "SMOKE TESTS PASSED"
From d27f93e869c0fc81a309ef39a3262ed6ee5dad3d Mon Sep 17 00:00:00 2001
From: ampynjord <82981605+ampynjord@users.noreply.github.com>
Date: Thu, 19 Nov 2026 16:19:06 +0100
Subject: [PATCH 15/47] release.yml: the docker_server input goes before
signing_policy (the project's test reads the end of the inputs block)
---
.github/workflows/release.yml | 8 ++++----
1 file changed, 4 insertions(+), 4 deletions(-)
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 8f97e766..9a17308a 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -17,6 +17,10 @@ on:
description: "Also publish the relay's Docker image (x64 and arm64) to ghcr.io//mpfever-relay-docker, tagged with the version and latest"
type: boolean
default: false
+ docker_server:
+ description: "Also publish the dedicated server's Docker image (x64; server/Dockerfile, docs/DOCKER-SERVER.md) to ghcr.io//mpfever-server, tagged with the version and experimental"
+ type: boolean
+ default: false
signing_policy:
description: "SignPath's signing policy: test-signing (SignPath's self-signed test certificate, to check the setup: NEVER publish those archives) or release-signing (SignPath Foundation's certificate, once SignPath has imported it)"
type: choice
@@ -24,10 +28,6 @@ on:
- test-signing
- release-signing
default: test-signing
- docker_server:
- description: "Also publish the dedicated server's Docker image (x64; server/Dockerfile, docs/DOCKER-SERVER.md) to ghcr.io//mpfever-server, tagged with the version and experimental"
- type: boolean
- default: false
jobs:
release:
From 5da331912eee3aff7cdafb91225dc27d9adb4bc0 Mon Sep 17 00:00:00 2001
From: ampynjord <82981605+ampynjord@users.noreply.github.com>
Date: Thu, 19 Nov 2026 16:50:41 +0100
Subject: [PATCH 16/47] docs: Docker is the only supported way to run the
server
---
docs/DOCKER-SERVER.md | 3 +++
1 file changed, 3 insertions(+)
diff --git a/docs/DOCKER-SERVER.md b/docs/DOCKER-SERVER.md
index 4f10e63b..53224818 100644
--- a/docs/DOCKER-SERVER.md
+++ b/docs/DOCKER-SERVER.md
@@ -9,6 +9,9 @@ Steam desktop. Players join it with the usual MPFever client, from Windows, exac
## Where it runs
+Docker is the only supported way: the image pins Wine, Mono and the rest, runs the server unprivileged and starts it with one command. Another OCI engine (Podman, Kubernetes) should work but is not tried;
+running the pieces directly on a Linux host (the Dockerfile is the recipe) is neither scripted nor supported.
+
"Linux" is the system inside the container. The host is any machine that runs Linux containers for x86-64:
| Host | |
From 858c5918f6b1845a737af4614fc2d2300cdf75ff Mon Sep 17 00:00:00 2001
From: ampynjord <82981605+ampynjord@users.noreply.github.com>
Date: Thu, 19 Nov 2026 17:38:46 +0100
Subject: [PATCH 17/47] Fix: settings are SRV_-prefixed (a host variable such
as Windows' PUBLIC put the server in the public list); entrypoint validates
its settings; long-run results (122 MB world, minimum limits, vanished
client) and limits in the guide; default memory 16g
---
docs/DOCKER-SERVER.md | 41 ++++++++++++++++++++++++------------
server/.env.example | 33 +++++++++++++++--------------
server/compose.build.yaml | 4 ++--
server/compose.yaml | 40 +++++++++++++++++------------------
server/scripts/entrypoint.sh | 15 ++++++++++++-
server/tests/check.sh | 10 ++++++---
6 files changed, 87 insertions(+), 56 deletions(-)
diff --git a/docs/DOCKER-SERVER.md b/docs/DOCKER-SERVER.md
index 53224818..85e5ab16 100644
--- a/docs/DOCKER-SERVER.md
+++ b/docs/DOCKER-SERVER.md
@@ -42,7 +42,7 @@ curl -fsSLO https://raw.githubusercontent.com/ampynjord/MPFever/feature/dedicate
curl -fsSL https://raw.githubusercontent.com/ampynjord/MPFever/feature/dedicated-server/server/.env.example -o .env
```
-Edit `.env` (at least `WORLD`, the savegame's name without `.sav`). Then, once:
+Edit `.env` (at least `SRV_WORLD`, the savegame's name without `.sav`). Then, once:
1. **Pull the image**: `docker compose pull`
2. **Import the game** from your own Steam library (read-only mount; the 3D data is left out, 66 GB become about 1 GB on disk):
@@ -67,19 +67,20 @@ Commands for the administrator (the service is `mpfever-server`):
## Settings
-Everything is in `.env` and takes effect with `docker compose up -d`, no rebuild. Only `WORLD` is required.
+Everything is in `.env` and takes effect with `docker compose up -d`, no rebuild. Only `SRV_WORLD` is required. The `SRV_` prefix keeps the names apart from the variables of the machine
+the command runs on: a shell variable wins over `.env` (Windows defines `PUBLIC`, which once listed a server publicly by mistake).
| Variable | Default | |
|---|---|---|
-| `WORLD` | | the savegame to host (name without `.sav`) |
-| `SERVER_NAME`, `MOTD` | `MPFever Server`, empty | name and welcome message |
-| `PORT` | `28090` | TCP port |
-| `PASSWORD`, `MAX_PLAYERS` | empty, `8` | |
-| `COMPANY_MODE` | `shared` | `shared` or `separate` (one company per player) |
-| `START_SPEED`, `PAUSE_WHEN_EMPTY`, `PLAYER_SPEED_CONTROL` | `1`, `false`, `true` | |
-| `AUTOSAVE_MINUTES`, `BACKUPS` | `10`, `10` | autosave and copies kept in `srv/backups` |
-| `PUBLIC`, `PUBLIC_ADDRESS` | `false`, empty | list the server in MPFever's public list |
-| `MEM_LIMIT`, `CPUS` | `14g`, `2` | container limits (measured need: about 11 GB and 0.7 core for a small world) |
+| `SRV_WORLD` | | the savegame to host (name without `.sav`) |
+| `SRV_SERVER_NAME`, `SRV_MOTD` | `MPFever Server`, empty | name and welcome message |
+| `SRV_PORT` | `28090` | TCP port |
+| `SRV_PASSWORD`, `SRV_MAX_PLAYERS` | empty, `8` | |
+| `SRV_COMPANY_MODE` | `shared` | `shared` or `separate` (one company per player) |
+| `SRV_START_SPEED`, `SRV_PAUSE_WHEN_EMPTY`, `SRV_PLAYER_SPEED_CONTROL` | `1`, `false`, `true` | |
+| `SRV_AUTOSAVE_MINUTES`, `SRV_BACKUPS` | `10`, `10` | autosave and copies kept in `srv/backups` |
+| `SRV_PUBLIC`, `SRV_PUBLIC_ADDRESS` | `false`, empty | list the server in MPFever's public list |
+| `SRV_MEM_LIMIT`, `SRV_CPUS` | `16g`, `2` | container limits: about 12 GB and 1 CPU for the small world (minimum), 16 GB and 2 CPUs for a world of 120 MB; the CPU also sets how fast it starts and resynchronises |
| `MPFEVER_IMAGE` | the published image | another image or a version tag (rollback) |
They are written to the server's `mpfever_server.properties` at every start (the game's other server options of SERVER.txt are the launcher's own).
@@ -149,9 +150,21 @@ Small world, no GPU, one real Windows client:
Run end to end on the built image with volumes created empty, a real account and a real Windows client: `install-game`, the QR `login`, the token hand-over to Dock (Steamworks without a Steam
desktop), first start, `import-save`, world load, a client joining and staying identical, `docker compose stop` (about 10 s, world saved), restart restoring the saved world, the healthcheck, the
-read-only container.
-**Not validated yet:** runs of 30 minutes or more, memory growth over time, several clients (a second Steam account is needed, or local test clients), large worlds, enforced CPU/memory limits,
-stopping while a client has vanished, the GPU variant.
+read-only container. Then a longer run:
+
+| Run | Result |
+|---|---|
+| A real world of 122 MB (1.6 times the small one), 16 GB and 2 CPUs, 40 minutes, no client at the end | 0 desynchronisations, 0 errors, no out-of-memory kill. Game memory (PSS) climbs from 11.2 GB to 12.5 GB in the first 18 minutes of simulation, then stays flat (12.54 GB): a warm-up, not a leak. About 1.1 CPU while it simulates, game speed about x1.0 outside saves and resynchronisations. Container 14.9 GB including 2.7 GB of reclaimable cache: **16 GB is the minimum for this size**, 14 GB (the default) is not enough |
+| The small world, **12 GB and 1 CPU** (the minimum limits) | runs: container peak 11.6 GB of 12 GB, no out-of-memory kill, 0 desynchronisations. Start takes 5 min 17 s (2 min 40 with 2 CPUs); a client's resynchronisation 285 s (96 to 140 s with 2 CPUs) |
+| `docker compose stop` while a client has vanished (killed abruptly) | 71 s, exit code 0, the world saved: the stop waits up to about 60 s for the lost client, inside the 90 s script and 120 s Compose timeouts |
+
+**Known limits found by these runs**
+- **Worlds that use mods:** the server has no way to install a world's mods yet. A real 595 MB world using 15 mod.io mods was refused ("Missing mods: the session ends"). A client whose own game had personal mods stayed stuck on
+ "loading" for 10 minutes on the 122 MB world (the server resumed without it after 616 s). Importing mods is the next piece of work.
+- **Public list and Steam join:** with `SRV_PUBLIC=true` (or a stray host variable, see Settings) the server is announced to MPFever's public list with its Steam ID, and anyone can join through Steam; a
+ stranger did so during the first long run. Keep `SRV_PUBLIC=false` and set `SRV_PASSWORD` for a private server.
+
+**Not validated yet:** several clients at once (local test clients, or a second Steam account), the GPU variant, worlds with mods, runs of several hours.
## Build, tests, publication
diff --git a/server/.env.example b/server/.env.example
index ced7ca21..5b996e12 100644
--- a/server/.env.example
+++ b/server/.env.example
@@ -1,22 +1,23 @@
-# Copy to .env. Everything but WORLD has a default. Changing a value never needs a rebuild: docker compose up -d
+# Copy to .env. Everything but SRV_WORLD has a default. (The SRV_ prefix keeps these names apart from the variables of the machine the command runs on:
+# a variable of the shell wins over .env, and Windows already defines PUBLIC.) Changing a value never needs a rebuild: docker compose up -d
# The savegame to host: its name without .sav, imported with `import-save` (docs/DOCKER-SERVER.md).
-WORLD=myworld
-SERVER_NAME=MPFever Server
+SRV_WORLD=myworld
+SRV_SERVER_NAME=MPFever Server
# TCP port players connect to (forward it on your router for the Internet).
-PORT=28090
-PASSWORD=
-MAX_PLAYERS=8
+SRV_PORT=28090
+SRV_PASSWORD=
+SRV_MAX_PLAYERS=8
# shared (one company for all) or separate (one per player)
-COMPANY_MODE=shared
-START_SPEED=1
-PAUSE_WHEN_EMPTY=false
-AUTOSAVE_MINUTES=10
-BACKUPS=10
+SRV_COMPANY_MODE=shared
+SRV_START_SPEED=1
+SRV_PAUSE_WHEN_EMPTY=false
+SRV_AUTOSAVE_MINUTES=10
+SRV_BACKUPS=10
# List the server in MPFever's public list
-PUBLIC=false
-MOTD=
-# Resource limits. Measured for a small world: about 11 GB of RAM and 0.7 core.
-MEM_LIMIT=14g
-CPUS=2
+SRV_PUBLIC=false
+SRV_MOTD=
+# Resource limits. Small world: 12 GB and 1 CPU is the minimum (slow to start); a world of 120 MB needs 16 GB and 2 CPUs.
+SRV_MEM_LIMIT=16g
+SRV_CPUS=2
# Another image or version (rollback): MPFEVER_IMAGE=ghcr.io/ampynjord/mpfever-server:
#MPFEVER_IMAGE=
diff --git a/server/compose.build.yaml b/server/compose.build.yaml
index 612f6655..59d1bde8 100644
--- a/server/compose.build.yaml
+++ b/server/compose.build.yaml
@@ -5,5 +5,5 @@ services:
build:
context: .
args:
- VERSION: ${VERSION:-local}
- APT_MIRROR: ${APT_MIRROR:-} # e.g. http://fr.archive.ubuntu.com/ubuntu when archive.ubuntu.com is unreachable
+ VERSION: ${SRV_BUILD_VERSION:-local}
+ APT_MIRROR: ${SRV_APT_MIRROR:-} # e.g. http://fr.archive.ubuntu.com/ubuntu when archive.ubuntu.com is unreachable
diff --git a/server/compose.yaml b/server/compose.yaml
index f2621591..700291de 100644
--- a/server/compose.yaml
+++ b/server/compose.yaml
@@ -4,32 +4,32 @@ name: mpfever-server
services:
mpfever-server:
image: ${MPFEVER_IMAGE:-ghcr.io/ampynjord/mpfever-server:experimental}
- container_name: ${CONTAINER_NAME:-mpfever-server}
+ container_name: ${SRV_CONTAINER_NAME:-mpfever-server}
restart: unless-stopped
init: true
stop_grace_period: 120s # the world is saved and the game closed on `docker compose stop`
ports:
- - "${PORT:-28090}:${PORT:-28090}"
+ - "${SRV_PORT:-28090}:${SRV_PORT:-28090}"
environment:
- WORLD: ${WORLD:?set WORLD in .env (the savegame to host)}
- SERVER_NAME: ${SERVER_NAME:-MPFever Server}
- PORT: ${PORT:-28090}
- PASSWORD: ${PASSWORD:-}
- MAX_PLAYERS: ${MAX_PLAYERS:-8}
- COMPANY_MODE: ${COMPANY_MODE:-shared}
- START_SPEED: ${START_SPEED:-1}
- PAUSE_WHEN_EMPTY: ${PAUSE_WHEN_EMPTY:-false}
- PLAYER_SPEED_CONTROL: ${PLAYER_SPEED_CONTROL:-true}
- AUTOSAVE_MINUTES: ${AUTOSAVE_MINUTES:-10}
- BACKUPS: ${BACKUPS:-10}
- PUBLIC: ${PUBLIC:-false}
- PUBLIC_ADDRESS: ${PUBLIC_ADDRESS:-}
- MOTD: ${MOTD:-}
+ WORLD: ${SRV_WORLD:?set SRV_WORLD in .env (the savegame to host)}
+ SERVER_NAME: ${SRV_SERVER_NAME:-MPFever Server}
+ PORT: ${SRV_PORT:-28090}
+ PASSWORD: ${SRV_PASSWORD:-}
+ MAX_PLAYERS: ${SRV_MAX_PLAYERS:-8}
+ COMPANY_MODE: ${SRV_COMPANY_MODE:-shared}
+ START_SPEED: ${SRV_START_SPEED:-1}
+ PAUSE_WHEN_EMPTY: ${SRV_PAUSE_WHEN_EMPTY:-false}
+ PLAYER_SPEED_CONTROL: ${SRV_PLAYER_SPEED_CONTROL:-true}
+ AUTOSAVE_MINUTES: ${SRV_AUTOSAVE_MINUTES:-10}
+ BACKUPS: ${SRV_BACKUPS:-10}
+ PUBLIC: ${SRV_PUBLIC:-false}
+ PUBLIC_ADDRESS: ${SRV_PUBLIC_ADDRESS:-}
+ MOTD: ${SRV_MOTD:-}
volumes:
- data:/data # Wine prefix, Valve client, Steam session (secrets/), saves, launcher and its logs and backups
- game:/game # the "lite" game install (about 1 GB on disk)
- mem_limit: ${MEM_LIMIT:-14g}
- cpus: ${CPUS:-2}
+ mem_limit: ${SRV_MEM_LIMIT:-16g}
+ cpus: ${SRV_CPUS:-2}
read_only: true
tmpfs:
- /tmp:size=512m
@@ -42,6 +42,6 @@ services:
volumes:
data:
- name: ${DATA_VOLUME:-mpfever-data}
+ name: ${SRV_DATA_VOLUME:-mpfever-data}
game:
- name: ${GAME_VOLUME:-mpfever-game}
+ name: ${SRV_GAME_VOLUME:-mpfever-game}
diff --git a/server/scripts/entrypoint.sh b/server/scripts/entrypoint.sh
index 7cec59fc..210f14c0 100644
--- a/server/scripts/entrypoint.sh
+++ b/server/scripts/entrypoint.sh
@@ -57,6 +57,18 @@ account_id() { python3 -c 'import json,sys; print(int(json.load(open(sys.argv[1]
save_dir() { echo "$STEAM_DIR/userdata/$(account_id)/$APPID/local/save"; }
local_dir() { echo "$STEAM_DIR/userdata/$(account_id)/$APPID/local"; }
+# the server settings come from .env through Compose: refuse a value that is not meant (a stray variable of the host once turned the public list on)
+need_choice() { local n=$1 v=$2 a; shift 2; for a in "$@"; do [ "$v" = "$a" ] && return 0; done; die "SRV_$n must be one of: $* (got '$v')" 2; }
+need_int() { [[ "$2" =~ ^[0-9]+$ ]] || die "SRV_$1 must be a number (got '$2')" 2; }
+check_settings() {
+ need_choice PUBLIC "${PUBLIC:-false}" true false
+ need_choice PAUSE_WHEN_EMPTY "${PAUSE_WHEN_EMPTY:-false}" true false
+ need_choice PLAYER_SPEED_CONTROL "${PLAYER_SPEED_CONTROL:-true}" true false
+ need_choice COMPANY_MODE "${COMPANY_MODE:-shared}" shared separate
+ need_choice START_SPEED "${START_SPEED:-1}" 1 2 4
+ need_int PORT "${PORT:-28090}"; need_int MAX_PLAYERS "${MAX_PLAYERS:-8}"; need_int AUTOSAVE_MINUTES "${AUTOSAVE_MINUTES:-10}"; need_int BACKUPS "${BACKUPS:-10}"
+}
+
# ---------------------------------------------------------------- modes
cmd_status() {
@@ -100,7 +112,8 @@ cmd_import_save() {
cmd_run() {
ensure_dirs
- : "${WORLD:?set WORLD to the name of a savegame (without .sav)}"
+ : "${WORLD:?set SRV_WORLD to the name of a savegame (without .sav)}"
+ check_settings
[ -f "$SESSION_FILE" ] || die "no Steam session: run login first (docs/DOCKER-SERVER.md, quick start step 3)" 40
python3 "$OPT/scripts/steam_session.py" status --file "$SESSION_FILE" >/dev/null \
|| die "the Steam session has expired: run login again" 41
diff --git a/server/tests/check.sh b/server/tests/check.sh
index 6201e59b..83e10f9b 100644
--- a/server/tests/check.sh
+++ b/server/tests/check.sh
@@ -19,9 +19,13 @@ bash dock/check.sh | tail -2 || fail=1
python3 -m py_compile dock/tools/check-client-layout.py || fail=1
step "compose"
-WORLD=check docker compose -f compose.yaml config -q || fail=1
-WORLD=check docker compose -f compose.yaml -f compose.build.yaml config -q || fail=1
-WORLD=check docker compose -f compose.yaml -f compose.gpu.yaml config -q || fail=1
+SRV_WORLD=check docker compose -f compose.yaml config -q || fail=1
+SRV_WORLD=check docker compose -f compose.yaml -f compose.build.yaml config -q || fail=1
+SRV_WORLD=check docker compose -f compose.yaml -f compose.gpu.yaml config -q || fail=1
+
+step "compose reads only SRV_ and MPFEVER_ variables (a host variable such as PUBLIC must never reach the server)"
+bad=$(grep -hoE '\$\{[A-Za-z_]+' compose*.yaml | grep -vE '^\$\{(SRV_|MPFEVER_)' || true)
+[ -z "$bad" ] || { echo "unprefixed variables in compose: $bad"; fail=1; }
step "no secrets, no binaries, no proprietary files"
if git ls-files --error-unmatch . >/dev/null 2>&1; then files=$(git ls-files .); else files=$(find . -type f -not -path './dist/*' | sed 's#^\./##'); fi
From 375aea015b1d0ed88375bb56d737bc73393175e9 Mon Sep 17 00:00:00 2001
From: ampynjord <82981605+ampynjord@users.noreply.github.com>
Date: Thu, 19 Nov 2026 17:39:13 +0100
Subject: [PATCH 18/47] GPU variant: documented as not validated, not working
on Docker Desktop/WSL2
---
docs/DOCKER-SERVER.md | 3 ++-
server/compose.gpu.yaml | 3 ++-
2 files changed, 4 insertions(+), 2 deletions(-)
diff --git a/docs/DOCKER-SERVER.md b/docs/DOCKER-SERVER.md
index 85e5ab16..fa463227 100644
--- a/docs/DOCKER-SERVER.md
+++ b/docs/DOCKER-SERVER.md
@@ -164,7 +164,8 @@ read-only container. Then a longer run:
- **Public list and Steam join:** with `SRV_PUBLIC=true` (or a stray host variable, see Settings) the server is announced to MPFever's public list with its Steam ID, and anyone can join through Steam; a
stranger did so during the first long run. Keep `SRV_PUBLIC=false` and set `SRV_PASSWORD` for a private server.
-**Not validated yet:** several clients at once (local test clients, or a second Steam account), the GPU variant, worlds with mods, runs of several hours.
+**Not validated yet:** several clients at once (local test clients, or a second Steam account), worlds with mods, runs of several hours. **The GPU variant** (`compose.gpu.yaml`, Intel/AMD through `/dev/dri` on a
+Linux host) was not run; on Docker Desktop with WSL2 it cannot work as written (the container gets `/dev/dxg` and no WSL driver libraries): software rendering is the supported mode there.
## Build, tests, publication
diff --git a/server/compose.gpu.yaml b/server/compose.gpu.yaml
index 0a1113b2..9bbf8da3 100644
--- a/server/compose.gpu.yaml
+++ b/server/compose.gpu.yaml
@@ -1,4 +1,5 @@
-# Optional: use a real GPU (Intel/AMD through /dev/dri) instead of software rendering. Not validated.
+# Optional: use a real GPU (Intel/AMD through /dev/dri, Linux hosts) instead of software rendering. NOT validated. On Docker Desktop with WSL2 it cannot work as is:
+# the container then gets /dev/dxg (no /dev/dri) and none of the WSL driver libraries; software rendering (the default) is the supported mode there.
# docker compose -f compose.yaml -f compose.gpu.yaml up -d
services:
mpfever-server:
From f26c0cdf54e21e4ca03e9a521a5876f3f7098dc8 Mon Sep 17 00:00:00 2001
From: ampynjord <82981605+ampynjord@users.noreply.github.com>
Date: Thu, 19 Nov 2026 17:55:15 +0100
Subject: [PATCH 19/47] Docker server administration and logs: JSON log lines
(launcher and scripts), mpfever-admin (console commands from outside through
a command folder), autoupdate=notify (new release announced, never installed)
---
docs/CHANGELOG.txt | 4 +-
docs/DOCKER-SERVER.md | 30 +++++++++++++++
launcher/Core.cs | 28 +++++++++++++-
launcher/MainForm.cs | 13 ++++++-
launcher/Server.cs | 26 +++++++++++++
launcher/Updater.cs | 4 +-
server/.env.example | 4 ++
server/Dockerfile | 3 +-
server/compose.yaml | 2 +
server/scripts/admin.py | 71 +++++++++++++++++++++++++++++++++++
server/scripts/entrypoint.sh | 9 ++++-
server/scripts/lib.sh | 16 ++++++--
server/scripts/mpfever-admin | 2 +
server/tests/check.sh | 2 +-
server/tests/test_admin.py | 73 ++++++++++++++++++++++++++++++++++++
15 files changed, 277 insertions(+), 10 deletions(-)
create mode 100644 server/scripts/admin.py
create mode 100644 server/scripts/mpfever-admin
create mode 100644 server/tests/test_admin.py
diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index 6ae2e960..f83106e2 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -9,7 +9,9 @@ MPFever - Changelog
(MPFEVER_WINE=1, MPFEVER_DOCK) and a stop file (MPFEVER_STOPFILE: the world is saved, then the server stops, as the console's "stop"); nothing changes on
Windows. The image (ghcr.io/ampynjord/mpfever-server, tagged with the MPFever version and "experimental") holds no game or Valve file; install-game,
login (QR code, no password), import-save and status are its administration commands. Validated end to end for short sessions with a real Windows
- client; long runs, several clients and large worlds are not yet (see the guide). CI: ci.yml (jobs docker-server-checks and docker-server) and, to publish the image, release.yml (option docker_server).
+ client; long runs, several clients and large worlds are not yet (see the guide). For the Docker server the launcher also has MPFEVER_LOG_JSON=1 (one JSON object
+ per line in its log file: ts, level, component, msg), MPFEVER_CMDDIR (one file per console command: `mpfever-admin` runs the commands of the server window from
+ outside) and autoupdate=notify (a new release is announced in the log, never installed). CI: ci.yml (jobs docker-server-checks and docker-server) and, to publish the image, release.yml (option docker_server).
- BUILD (code signing, 2026-11-19: SignPath Foundation accepted MPFever; their first step is a signature with their
self-signed test certificate, then they review the setup and import the Foundation's certificate): the Release build
workflow asks for the signing policy, test-signing by default, release-signing once the certificate is in. Archives signed
diff --git a/docs/DOCKER-SERVER.md b/docs/DOCKER-SERVER.md
index fa463227..91e7172d 100644
--- a/docs/DOCKER-SERVER.md
+++ b/docs/DOCKER-SERVER.md
@@ -61,6 +61,7 @@ Commands for the administrator (the service is `mpfever-server`):
|---|---|
| `docker compose ps` / `logs -f` | state, health, log |
| `docker compose run --rm mpfever-server status` | what is missing (game, Steam session, savegame, sparse files, disk) |
+| `docker compose exec mpfever-server mpfever-admin ` | a console command of the server (`help`, `status`, `say`, `kick`, `save`, ...) |
| `docker compose exec mpfever-server /opt/mpfever/scripts/measure.sh` | memory (container, processes), CPU over 30 s, synchronisation |
| `docker compose run --rm mpfever-server login` | sign in again when the Steam session expires (about 7 months) |
| `docker compose run --rm -v "...:/in:ro" mpfever-server import-save /in/.sav` | add or replace a savegame |
@@ -80,6 +81,8 @@ the command runs on: a shell variable wins over `.env` (Windows defines `PUBLIC`
| `SRV_START_SPEED`, `SRV_PAUSE_WHEN_EMPTY`, `SRV_PLAYER_SPEED_CONTROL` | `1`, `false`, `true` | |
| `SRV_AUTOSAVE_MINUTES`, `SRV_BACKUPS` | `10`, `10` | autosave and copies kept in `srv/backups` |
| `SRV_PUBLIC`, `SRV_PUBLIC_ADDRESS` | `false`, empty | list the server in MPFever's public list |
+| `SRV_LOG_FORMAT` | `json` | `json` (one JSON object per line) or `text` |
+| `SRV_UPDATE_CHECK` | `notify` | `notify` (new MPFever release announced in the log, never installed) or `off` |
| `SRV_MEM_LIMIT`, `SRV_CPUS` | `16g`, `2` | container limits: about 12 GB and 1 CPU for the small world (minimum), 16 GB and 2 CPUs for a world of 120 MB; the CPU also sets how fast it starts and resynchronises |
| `MPFEVER_IMAGE` | the published image | another image or a version tag (rollback) |
@@ -103,6 +106,33 @@ archive (run it on the release's tag), so the players' client of that version ca
fetched from Valve at the first start (pinned build, hash-checked). Start (`server/scripts/entrypoint.sh run`): checks (disk, sparse support, RAM, game, session, savegame), first-start
Wine prefix, the launcher restarted when it exits (five failures within a minute stop the container with a message), `SIGTERM` writes the stop file: the world is saved, the game closed, then the container exits.
+## Administering the server
+
+The launcher of the image is the server's brain (`MPFever.exe --server`, the same program as the Windows dedicated server): hosting, synchronisation, saves, the console. The container only wraps it (Wine, Steam through Dock, scripts).
+The console commands of the server window work from outside with **`mpfever-admin`**:
+
+```
+docker compose exec mpfever-server mpfever-admin help # the list of commands
+docker compose exec mpfever-server mpfever-admin status # players, speed, synchronisation, last save
+docker compose exec mpfever-server mpfever-admin say "Restart in 5 minutes"
+docker compose exec mpfever-server mpfever-admin kick
+docker compose exec mpfever-server mpfever-admin save
+```
+
+It hands the command to the launcher (a file in `/data/run/cmd`), waits for it to run and prints what the server logged for it. Everything the Windows server's console does is reachable this way (see the server's `SERVER.txt`).
+An administration web page is planned (off by default); it will use the same channel.
+
+## Logs
+
+`docker compose logs` shows every component on one stream, **one JSON object per line**: `{"ts":"2026-11-19T15:46:34.409Z","level":"info","component":"launcher","msg":"WinClient#1 joined the session"}`
+(`ts` in UTC; `level` `debug`, `info`, `warn` or `error`; `component` `entrypoint` for this container's scripts, `launcher` for MPFever). `SRV_LOG_FORMAT=text` gives plain lines instead. The files are in the data volume
+(`srv/logs/launcher-*.log`, `srv/launcher.out`, Dock's `srv/dock.log`); the Docker log rotates (20 MB, 5 files). Any JSON log collector (Loki, Elasticsearch, `jq`) reads the stream as it is.
+
+## Updates
+
+The server looks for a new MPFever release every 30 minutes (`SRV_UPDATE_CHECK=notify`, the default; `off` stops the check) and **announces it once in the log** (`level` `warn`: "MPFever 0.9.2 is published; this server does not install it"). It never installs it by itself:
+the image is updated (`docker compose pull && docker compose up -d`), so the version of the launcher, the module, the mod and Dock stay one tested set. Players need the client of the server's version.
+
## Steam sign-in
`login` uses Steam's own authentication service (the QR flow of the Steam mobile app) and keeps a **refresh token** in `secrets/steam.json` of the data volume (mode 0600). At every game
diff --git a/launcher/Core.cs b/launcher/Core.cs
index 2cc8e638..36ff4eab 100644
--- a/launcher/Core.cs
+++ b/launcher/Core.cs
@@ -258,10 +258,36 @@ public static void Init(string dir)
public static void Err(string s) => Write(s, LogLevel.Error);
public static void Dim(string s) => Write(s, LogLevel.Muted);
+ /// MPFEVER_LOG_JSON=1 (the Docker server): each line of the log file is one JSON object {"ts","level","component","msg"} (UTC time; level debug, info, warn
+ /// or error) instead of "HH:mm:ss.fff text"; the lines shown in a window are unchanged.
+ static readonly bool Json = Environment.GetEnvironmentVariable("MPFEVER_LOG_JSON") == "1";
+
+ static string JsonEscape(string s)
+ {
+ var b = new System.Text.StringBuilder();
+ foreach (var c in s ?? "")
+ {
+ if (c == '"') b.Append("\\\"");
+ else if (c == '\\') b.Append("\\\\");
+ else if (c == '\n') b.Append("\\n");
+ else if (c == '\r') b.Append("\\r");
+ else if (c == '\t') b.Append("\\t");
+ else if (c < ' ') b.Append("\\u" + ((int)c).ToString("x4"));
+ else b.Append(c);
+ }
+ return b.ToString();
+ }
+
public static void Write(string s, LogLevel level)
{
var l = DateTime.Now.ToString("HH:mm:ss.fff") + " " + s;
- lock (Gate) { try { if (file != null) File.AppendAllText(file, l + Environment.NewLine); } catch { } }
+ var fileLine = l;
+ if (Json)
+ {
+ var lv = level == LogLevel.Warning ? "warn" : level == LogLevel.Error ? "error" : level == LogLevel.Muted ? "debug" : "info";
+ fileLine = "{\"ts\":\"" + DateTime.UtcNow.ToString("yyyy-MM-dd'T'HH:mm:ss.fff'Z'") + "\",\"level\":\"" + lv + "\",\"component\":\"launcher\",\"msg\":\"" + JsonEscape(s) + "\"}";
+ }
+ lock (Gate) { try { if (file != null) File.AppendAllText(file, fileLine + Environment.NewLine); } catch { } }
Line?.Invoke(l);
Entry?.Invoke(l, level);
}
diff --git a/launcher/MainForm.cs b/launcher/MainForm.cs
index c575e7d9..9fcd4949 100644
--- a/launcher/MainForm.cs
+++ b/launcher/MainForm.cs
@@ -1041,12 +1041,13 @@ void CheckUpdateThenInit()
/// A release published on GitHub while this launcher is open (checked every 30 minutes): installed when the
/// game closes (a player's launcher), or by a dedicated server once nobody is connected (see ServerTick).
volatile UpdateInfo pendingUpdate;
+ string notifiedVersion;
DateTime gameStartedAt = DateTime.Now;
System.Threading.Timer updateWatch;
void StartUpdateWatch()
{
- if (updateWatch != null || autotest || Dev || !Updater.Enabled || !Updater.InReleaseFolder) return;
+ if (updateWatch != null || autotest || Dev || (!Updater.Enabled && !Updater.Notify) || !Updater.InReleaseFolder) return;
var period = TimeSpan.FromMinutes(Updater.RecheckMinutes);
updateWatch = new System.Threading.Timer(_ =>
{
@@ -1056,6 +1057,16 @@ void StartUpdateWatch()
if (u == null) return;
var known = pendingUpdate;
if (known != null && Updater.CompareVersions(Updater.ParseVersion(u.Version), Updater.ParseVersion(known.Version)) <= 0) return;
+ if (Updater.Notify)
+ {
+ // (autoupdate=notify: announced once per release, never installed: the administrator updates the image)
+ if (notifiedVersion != u.Version)
+ {
+ notifiedVersion = u.Version;
+ Log.Warn(F("MPFever {0} est publié ; ce serveur ne l'installe pas (autoupdate=notify) : mettez l'image à jour.", "MPFever {0} is published; this server does not install it (autoupdate=notify): update the image.", u.Version));
+ }
+ return;
+ }
pendingUpdate = u;
if (ServerMode && !serverStarted)
{
diff --git a/launcher/Server.cs b/launcher/Server.cs
index 68ce28c8..2df3ceea 100644
--- a/launcher/Server.cs
+++ b/launcher/Server.cs
@@ -740,6 +740,32 @@ void ServerTick()
return;
}
}
+ // (Linux server, server/) administration from outside: MPFEVER_CMDDIR holds one file per console command (*.cmd, its text is the command line, as
+ // typed under the log of the server window); each is run as that console command, then .done is written. `mpfever-admin` of the image does it.
+ if (GameInstall.IsLinux)
+ {
+ var cmdDir = Environment.GetEnvironmentVariable("MPFEVER_CMDDIR");
+ if (!string.IsNullOrEmpty(cmdDir) && Directory.Exists(cmdDir))
+ {
+ string[] files = new string[0];
+ try { files = Directory.GetFiles(cmdDir, "*.cmd"); Array.Sort(files, StringComparer.Ordinal); } catch { }
+ foreach (var cf in files)
+ {
+ string cmdLine;
+ try { cmdLine = File.ReadAllText(cf).Trim(); File.Delete(cf); } catch { continue; }
+ var doneFile = Path.ChangeExtension(cf, ".done");
+ try
+ {
+ BeginInvoke((Action)(() =>
+ {
+ try { ServerCommand(cmdLine); }
+ finally { try { File.WriteAllText(doneFile, DateTime.UtcNow.ToString("o")); } catch { } }
+ }));
+ }
+ catch { }
+ }
+ }
+ }
bool st, paused; int sp;
lock (sessionGate) { st = started; paused = pauseAt.HasValue; sp = speed; }
if (!st)
diff --git a/launcher/Updater.cs b/launcher/Updater.cs
index 425e4410..1252f6ac 100644
--- a/launcher/Updater.cs
+++ b/launcher/Updater.cs
@@ -51,8 +51,10 @@ static class Updater
/// autoupdate in mpfever_settings.txt: 1 (default) installs a new release by itself, "ask" offers it in a
/// window first, 0 turns the check off.
static string Setting => MainForm.LoadSettings().TryGetValue("autoupdate", out var v) ? v.Trim().ToLowerInvariant() : "1";
- public static bool Enabled => Setting != "0";
+ public static bool Enabled => Setting != "0" && Setting != "notify";
public static bool Ask => Setting == "ask";
+ /// autoupdate=notify (the Docker server): the release is looked for and announced in the log, never installed (the image is updated instead).
+ public static bool Notify => Setting == "notify";
/// MPFever.exe runs from an unpacked release (mod\mpfever_1 next to it), not from a build folder.
public static bool InReleaseFolder => File.Exists(Path.Combine(AppDir, "mod", "mpfever_1", "mod.json"));
diff --git a/server/.env.example b/server/.env.example
index 5b996e12..2ed2e3e5 100644
--- a/server/.env.example
+++ b/server/.env.example
@@ -16,6 +16,10 @@ SRV_BACKUPS=10
# List the server in MPFever's public list
SRV_PUBLIC=false
SRV_MOTD=
+# Logs on stdout (docker logs): json (one JSON object per line: ts, level, component, msg) or text
+SRV_LOG_FORMAT=json
+# New MPFever release: notify (announced in the log, never installed: update the image) or off (no check)
+SRV_UPDATE_CHECK=notify
# Resource limits. Small world: 12 GB and 1 CPU is the minimum (slow to start); a world of 120 MB needs 16 GB and 2 CPUs.
SRV_MEM_LIMIT=16g
SRV_CPUS=2
diff --git a/server/Dockerfile b/server/Dockerfile
index bdc63358..1b53c33e 100644
--- a/server/Dockerfile
+++ b/server/Dockerfile
@@ -62,7 +62,8 @@ COPY --from=vklayer /libVkLayer_mpf_nulldraw.so /opt/mpfever/libVkLayer_mpf_null
COPY vklayer/VkLayer_mpf_nulldraw.json /etc/vulkan/implicit_layer.d/VkLayer_mpf_nulldraw.json
COPY scripts/ /opt/mpfever/scripts/
COPY config/ /opt/mpfever/config/
-RUN sed -i 's/\r$//' /opt/mpfever/scripts/*.sh && chmod 755 /opt/mpfever/scripts/*.sh
+RUN sed -i 's/\r$//' /opt/mpfever/scripts/*.sh /opt/mpfever/scripts/mpfever-admin && chmod 755 /opt/mpfever/scripts/*.sh /opt/mpfever/scripts/mpfever-admin \
+ && ln -s /opt/mpfever/scripts/mpfever-admin /usr/local/bin/mpfever-admin
ARG VCS_REF=unknown
ARG SOURCE_REPO=https://github.com/dkdknight/MPFever
diff --git a/server/compose.yaml b/server/compose.yaml
index 700291de..14b61d72 100644
--- a/server/compose.yaml
+++ b/server/compose.yaml
@@ -25,6 +25,8 @@ services:
PUBLIC: ${SRV_PUBLIC:-false}
PUBLIC_ADDRESS: ${SRV_PUBLIC_ADDRESS:-}
MOTD: ${SRV_MOTD:-}
+ LOG_FORMAT: ${SRV_LOG_FORMAT:-json}
+ UPDATE_CHECK: ${SRV_UPDATE_CHECK:-notify}
volumes:
- data:/data # Wine prefix, Valve client, Steam session (secrets/), saves, launcher and its logs and backups
- game:/game # the "lite" game install (about 1 GB on disk)
diff --git a/server/scripts/admin.py b/server/scripts/admin.py
new file mode 100644
index 00000000..db20eac2
--- /dev/null
+++ b/server/scripts/admin.py
@@ -0,0 +1,71 @@
+#!/usr/bin/env python3
+"""mpfever-admin: runs a console command of the MPFever server (the ones typed under the log of the server window) and prints what the server logged for it.
+
+ docker compose exec mpfever-server mpfever-admin help
+ docker compose exec mpfever-server mpfever-admin status
+ docker compose exec mpfever-server mpfever-admin say "Restart in 5 minutes"
+ docker compose exec mpfever-server mpfever-admin kick
+ docker compose exec mpfever-server mpfever-admin save
+
+The command is handed to the launcher through a file in the command folder (MPFEVER_CMDDIR); the launcher runs it and writes .done. Exit status: 0 done, 1 the server did not answer."""
+import glob, json, os, sys, time
+
+CMDDIR = os.environ.get("MPFEVER_CMDDIR", "/data/run/cmd")
+LOGDIR = os.environ.get("MPFEVER_LOGDIR", "/data/srv/logs")
+TIMEOUT = float(os.environ.get("MPFEVER_ADMIN_TIMEOUT", "60"))
+
+
+def render(line):
+ """One launcher log line as plain text: the message of a JSON line, or the line as it is."""
+ line = line.rstrip("\n")
+ if line.startswith("{"):
+ try:
+ o = json.loads(line)
+ return ("%s %s" % (o.get("level", "info").upper(), o.get("msg", ""))).strip() if o.get("level") in ("warn", "error") else o.get("msg", "")
+ except ValueError:
+ return line
+ return line.split(" ", 1)[1] if len(line) > 13 and line[2] == ":" and line[5] == ":" else line
+
+
+def newest_log():
+ files = glob.glob(os.path.join(LOGDIR, "launcher-*.log"))
+ return max(files, key=os.path.getmtime) if files else None
+
+
+def run(command, out=sys.stdout):
+ if not command.strip():
+ print(__doc__.split("\n\n")[0], file=sys.stderr)
+ return 1
+ os.makedirs(CMDDIR, exist_ok=True)
+ log = newest_log()
+ start = os.path.getsize(log) if log else 0
+ name = "%d-%d" % (time.time() * 1000, os.getpid())
+ tmp, cmd, done = (os.path.join(CMDDIR, name + e) for e in (".tmp", ".cmd", ".done"))
+ with open(tmp, "w") as f:
+ f.write(command)
+ os.replace(tmp, cmd) # the launcher only reads finished files
+ deadline = time.time() + TIMEOUT
+ while time.time() < deadline and not os.path.exists(done):
+ time.sleep(0.2)
+ if not os.path.exists(done):
+ try:
+ os.remove(cmd)
+ except OSError:
+ pass
+ print("the server did not answer within %d s (is the world running? `docker compose logs`)" % TIMEOUT, file=sys.stderr)
+ return 1
+ os.remove(done)
+ time.sleep(0.5) # the lines the command logged
+ log = newest_log() or log
+ if log:
+ with open(log, "r", errors="replace") as f:
+ f.seek(start)
+ for line in f.read().splitlines():
+ text = render(line)
+ if text:
+ print(text, file=out)
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(run(" ".join(sys.argv[1:])))
diff --git a/server/scripts/entrypoint.sh b/server/scripts/entrypoint.sh
index 210f14c0..571e4e17 100644
--- a/server/scripts/entrypoint.sh
+++ b/server/scripts/entrypoint.sh
@@ -66,6 +66,8 @@ check_settings() {
need_choice PLAYER_SPEED_CONTROL "${PLAYER_SPEED_CONTROL:-true}" true false
need_choice COMPANY_MODE "${COMPANY_MODE:-shared}" shared separate
need_choice START_SPEED "${START_SPEED:-1}" 1 2 4
+ need_choice LOG_FORMAT "${LOG_FORMAT:-json}" json text
+ need_choice UPDATE_CHECK "${UPDATE_CHECK:-notify}" notify off
need_int PORT "${PORT:-28090}"; need_int MAX_PLAYERS "${MAX_PLAYERS:-8}"; need_int AUTOSAVE_MINUTES "${AUTOSAVE_MINUTES:-10}"; need_int BACKUPS "${BACKUPS:-10}"
}
@@ -130,7 +132,9 @@ cmd_run() {
# the launcher package of this image version, and the server settings from the environment (the file is rewritten at every start)
cp -a "$OPT/pkg/." "$SRV/"
cd "$SRV" || die "cannot enter $SRV" 10
- printf 'servermode=headless\nautoupdate=0\n' > mpfever_settings.txt
+ # autoupdate=notify: the launcher looks for a new MPFever release and announces it in the log, never installs it (the image is updated); 0: no check
+ [ "${UPDATE_CHECK:-notify}" = notify ] && au=notify || au=0
+ printf 'servermode=headless\nautoupdate=%s\n' "$au" > mpfever_settings.txt
{
echo "server-name=${SERVER_NAME:-MPFever Server}"
echo "world=$WORLD"
@@ -160,6 +164,9 @@ cmd_run() {
export MADEIRA_STEAM_HOST_LOG=$SRV/dock.log
export MPFEVER_DOCK='Z:\opt\mpfever\dockhost.exe'
export MPFEVER_WINE=1 MPFEVER_STEAMPATH="$STEAM_DIR" MPFEVER_JOINREVIEW=0 MPFEVER_STOPFILE=$STOPFILE
+ export MPFEVER_CMDDIR=$RUN/cmd; mkdir -p "$MPFEVER_CMDDIR"; rm -f "$MPFEVER_CMDDIR"/* # the commands of `mpfever-admin`
+ # logs: the launcher writes the same JSON lines as this script (SRV_LOG_FORMAT=text: plain lines)
+ if [ "${LOG_FORMAT:-json}" = json ]; then export MPFEVER_LOG_JSON=1; else unset MPFEVER_LOG_JSON; fi
# no 3D output: software Vulkan with a layer that makes every draw and copy a no-op and gives back the GPU memory nobody reads;
# MPF_VKNULL=0 (docker compose: GPU=1) leaves a real GPU alone
export MPF_VKNULL=${MPF_VKNULL:-1} MPF_VKNULL_MODE=all MPF_VKNULL_TRIM=${MPF_VKNULL_TRIM:-1}
diff --git a/server/scripts/lib.sh b/server/scripts/lib.sh
index 53d5bc46..f5a7f209 100644
--- a/server/scripts/lib.sh
+++ b/server/scripts/lib.sh
@@ -16,9 +16,19 @@ CLIENT_URL=https://client-update.akamai.steamstatic.com/bins_win32.zip.23e34a6d4
CLIENT_ZIP_SHA256=8b712b2a3412a9066b7725f4e1c5cef9a7ca5b187b6585a5b92d25d09df0ba62
CLIENT_DLL_SHA256=71b391fe9f3e2006cbc81a5c75eef3eb4186012deabfdb2c8b7e8d4850ecf640
-log() { echo "$(date -u +%H:%M:%S) [mpfever-server] $*"; }
-warn() { echo "$(date -u +%H:%M:%S) [mpfever-server] WARNING: $*" >&2; }
-die() { echo "$(date -u +%H:%M:%S) [mpfever-server] ERROR: $1" >&2; exit "${2:-1}"; }
+# Logs: one JSON object per line on stdout/stderr, {"ts","level","component","msg"}, the same shape as the launcher's (SRV_LOG_FORMAT=text, set in .env: "HH:MM:SS LEVEL message").
+emit() {
+ local level=$1; shift
+ if [ "${LOG_FORMAT:-json}" = json ]; then
+ local m; m=$(printf '%s' "$*" | sed -e 's/\\/\\\\/g' -e 's/"/\\"/g')
+ printf '{"ts":"%s","level":"%s","component":"entrypoint","msg":"%s"}\n' "$(date -u +%Y-%m-%dT%H:%M:%S.%3NZ)" "$level" "$m"
+ else
+ printf '%s %-5s %s\n' "$(date -u +%H:%M:%S)" "$(echo "$level" | tr a-z A-Z)" "$*"
+ fi
+}
+log() { emit info "$*"; }
+warn() { emit warn "$*" >&2; }
+die() { emit error "$1" >&2; exit "${2:-1}"; }
sha256_of() { sha256sum "$1" 2>/dev/null | cut -d' ' -f1; }
diff --git a/server/scripts/mpfever-admin b/server/scripts/mpfever-admin
new file mode 100644
index 00000000..b6464416
--- /dev/null
+++ b/server/scripts/mpfever-admin
@@ -0,0 +1,2 @@
+#!/bin/sh
+exec python3 /opt/mpfever/scripts/admin.py "$@"
diff --git a/server/tests/check.sh b/server/tests/check.sh
index 83e10f9b..ec74edf3 100644
--- a/server/tests/check.sh
+++ b/server/tests/check.sh
@@ -11,7 +11,7 @@ if command -v shellcheck >/dev/null; then step "shellcheck"; shellcheck -S warni
step "python"
python3 -m py_compile scripts/*.py || fail=1
-python3 -m unittest -q tests.test_steam_session 2>&1 | tail -3 || fail=1
+python3 -m unittest -q tests.test_steam_session tests.test_admin 2>&1 | tail -3 || fail=1
python3 tests/selftest_lite.py | tail -2 || fail=1
step "madeira dock (unit tests, tools)"
diff --git a/server/tests/test_admin.py b/server/tests/test_admin.py
new file mode 100644
index 00000000..c6729c81
--- /dev/null
+++ b/server/tests/test_admin.py
@@ -0,0 +1,73 @@
+"""Checks of scripts/admin.py and of the JSON log line of lib.sh that need no server: rendering of the launcher's log lines, and a command round trip with a fake launcher."""
+import json, os, subprocess, sys, tempfile, threading, time, unittest
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+sys.path.insert(0, os.path.join(HERE, "..", "scripts"))
+import admin
+
+
+class Render(unittest.TestCase):
+ def test_json_info_is_the_message(self):
+ self.assertEqual(admin.render(json.dumps({"ts": "x", "level": "info", "component": "launcher", "msg": "Speed: x1"})), "Speed: x1")
+
+ def test_json_warn_and_error_are_marked(self):
+ self.assertEqual(admin.render(json.dumps({"level": "warn", "msg": "slow"})), "WARN slow")
+ self.assertEqual(admin.render(json.dumps({"level": "error", "msg": "boom"})), "ERROR boom")
+
+ def test_text_line_loses_its_time(self):
+ self.assertEqual(admin.render("12:41:52.791 === The server stops ==="), "=== The server stops ===")
+
+ def test_unparsable_json_is_kept(self):
+ self.assertEqual(admin.render("{broken"), "{broken")
+
+
+class RoundTrip(unittest.TestCase):
+ def test_command_is_executed_and_its_lines_printed(self):
+ with tempfile.TemporaryDirectory() as d:
+ cmds, logs = os.path.join(d, "cmd"), os.path.join(d, "logs")
+ os.makedirs(cmds); os.makedirs(logs)
+ log = os.path.join(logs, "launcher-1.log")
+ open(log, "w").write(json.dumps({"level": "info", "msg": "old line"}) + "\n")
+ admin.CMDDIR, admin.LOGDIR = cmds, logs
+
+ def launcher(): # a fake launcher: runs the command, logs a line, writes .done
+ for _ in range(100):
+ for f in os.listdir(cmds):
+ if f.endswith(".cmd"):
+ text = open(os.path.join(cmds, f)).read()
+ os.remove(os.path.join(cmds, f))
+ open(log, "a").write(json.dumps({"level": "info", "msg": "> " + text}) + "\n" + json.dumps({"level": "info", "msg": "Players: none"}) + "\n")
+ open(os.path.join(cmds, f[:-4] + ".done"), "w").write("ok")
+ return
+ time.sleep(0.05)
+ t = threading.Thread(target=launcher); t.start()
+ import io
+ out = io.StringIO()
+ rc = admin.run("status", out)
+ t.join()
+ self.assertEqual(rc, 0)
+ self.assertEqual(out.getvalue().splitlines(), ["> status", "Players: none"])
+
+ def test_no_answer_fails(self):
+ with tempfile.TemporaryDirectory() as d:
+ admin.CMDDIR, admin.LOGDIR, admin.TIMEOUT = os.path.join(d, "c"), os.path.join(d, "l"), 0.5
+ self.assertEqual(admin.run("status"), 1)
+
+
+@unittest.skipUnless(os.name == "posix", "bash script")
+class LibLog(unittest.TestCase):
+ def sh(self, fmt):
+ env = dict(os.environ, LOG_FORMAT=fmt)
+ return subprocess.run(["bash", "-c", '. "$1"; log "a \\"quoted\\" path C:\\\\x"', "_", os.path.join(HERE, "..", "scripts", "lib.sh")], capture_output=True, text=True, env=env)
+
+ def test_json_line_is_valid_json(self):
+ o = json.loads(self.sh("json").stdout)
+ self.assertEqual((o["level"], o["component"]), ("info", "entrypoint"))
+ self.assertIn('"quoted"', o["msg"])
+
+ def test_text_line(self):
+ self.assertRegex(self.sh("text").stdout, r"^\d\d:\d\d:\d\d INFO a ")
+
+
+if __name__ == "__main__":
+ unittest.main()
From 231e0125e5375342d8dc0a2cf8f1360b1f165250 Mon Sep 17 00:00:00 2001
From: ampynjord <82981605+ampynjord@users.noreply.github.com>
Date: Thu, 19 Nov 2026 17:58:18 +0100
Subject: [PATCH 20/47] Update notice of the notify mode: an English log line
(no translation needed)
---
launcher/MainForm.cs | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/launcher/MainForm.cs b/launcher/MainForm.cs
index 9fcd4949..c8cd784d 100644
--- a/launcher/MainForm.cs
+++ b/launcher/MainForm.cs
@@ -1063,7 +1063,7 @@ void StartUpdateWatch()
if (notifiedVersion != u.Version)
{
notifiedVersion = u.Version;
- Log.Warn(F("MPFever {0} est publié ; ce serveur ne l'installe pas (autoupdate=notify) : mettez l'image à jour.", "MPFever {0} is published; this server does not install it (autoupdate=notify): update the image.", u.Version));
+ Log.Warn("MPFever " + u.Version + " is published; this server does not install it (autoupdate=notify): update the image."); // (an administrator's log line, English only)
}
return;
}
From a96516893bbaab73ba13775907dc51bcfc160948 Mon Sep 17 00:00:00 2001
From: ampynjord <82981605+ampynjord@users.noreply.github.com>
Date: Thu, 19 Nov 2026 19:50:20 +0100
Subject: [PATCH 21/47] Docker server mods: mod.io installer (mods
login/list/sync/status), sparse copy for the game, full copy kept apart, game
library registration (state.json, local subscription record), sync at start
(SRV_MODS_SYNC)
---
.github/workflows/ci.yml | 2 +-
server/.env.example | 2 +
server/Dockerfile | 2 +-
server/compose.yaml | 1 +
server/scripts/entrypoint.sh | 25 ++-
server/scripts/mods.py | 394 +++++++++++++++++++++++++++++++++++
server/tests/check.sh | 2 +-
server/tests/test_mods.py | 176 ++++++++++++++++
8 files changed, 600 insertions(+), 4 deletions(-)
create mode 100644 server/scripts/mods.py
create mode 100644 server/tests/test_mods.py
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index d7621487..cb3cdf95 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -139,7 +139,7 @@ jobs:
- uses: actions/checkout@v4
- name: Tools
- run: sudo apt-get update -qq && sudo apt-get install -y -qq shellcheck
+ run: sudo apt-get update -qq && sudo apt-get install -y -qq shellcheck python3-zstandard
- name: Static checks
run: bash server/tests/check.sh
diff --git a/server/.env.example b/server/.env.example
index 2ed2e3e5..1808d1e9 100644
--- a/server/.env.example
+++ b/server/.env.example
@@ -20,6 +20,8 @@ SRV_MOTD=
SRV_LOG_FORMAT=json
# New MPFever release: notify (announced in the log, never installed: update the image) or off (no check)
SRV_UPDATE_CHECK=notify
+# Mods: auto (with a mod.io key from `mods login`, the world's mods are installed or updated at every start) or off
+SRV_MODS_SYNC=auto
# Resource limits. Small world: 12 GB and 1 CPU is the minimum (slow to start); a world of 120 MB needs 16 GB and 2 CPUs.
SRV_MEM_LIMIT=16g
SRV_CPUS=2
diff --git a/server/Dockerfile b/server/Dockerfile
index 1b53c33e..1c3cf6ce 100644
--- a/server/Dockerfile
+++ b/server/Dockerfile
@@ -37,7 +37,7 @@ RUN dpkg --add-architecture i386 \
&& apt-get update -qq \
&& apt-get install -y -qq --no-install-recommends ca-certificates curl wget gnupg2 procps xvfb xauth \
libvulkan1 mesa-vulkan-drivers libgl1 libasound2t64 libgnutls30t64 libfreetype6 fonts-dejavu-core \
- python3-minimal python3-qrcode mono-runtime libmono-system-windows-forms4.0-cil libmono-system-drawing4.0-cil \
+ python3-minimal python3-qrcode python3-zstandard mono-runtime libmono-system-windows-forms4.0-cil libmono-system-drawing4.0-cil \
libmono-system-core4.0-cil libmono-system-io-compression4.0-cil libmono-system-io-compression-filesystem4.0-cil \
libmono-security4.0-cil ca-certificates-mono libgdiplus \
&& mkdir -pm755 /etc/apt/keyrings \
diff --git a/server/compose.yaml b/server/compose.yaml
index 14b61d72..9b716b6b 100644
--- a/server/compose.yaml
+++ b/server/compose.yaml
@@ -27,6 +27,7 @@ services:
MOTD: ${SRV_MOTD:-}
LOG_FORMAT: ${SRV_LOG_FORMAT:-json}
UPDATE_CHECK: ${SRV_UPDATE_CHECK:-notify}
+ MODS_SYNC: ${SRV_MODS_SYNC:-auto}
volumes:
- data:/data # Wine prefix, Valve client, Steam session (secrets/), saves, launcher and its logs and backups
- game:/game # the "lite" game install (about 1 GB on disk)
diff --git a/server/scripts/entrypoint.sh b/server/scripts/entrypoint.sh
index 571e4e17..0820008b 100644
--- a/server/scripts/entrypoint.sh
+++ b/server/scripts/entrypoint.sh
@@ -4,6 +4,7 @@
# login sign in to Steam once with a QR code (no password, no GUI); the session is remembered
# install-game build the lite game install from your own Steam library folder (mounted read-only)
# import-save .. copy savegame files into the server account's save folder
+# mods login|list|sync|status the mods of the worlds, from mod.io with your own API key (see mods.py)
# status check everything the server needs and print what is missing
# shell a shell in the container
set -u
@@ -68,6 +69,7 @@ check_settings() {
need_choice START_SPEED "${START_SPEED:-1}" 1 2 4
need_choice LOG_FORMAT "${LOG_FORMAT:-json}" json text
need_choice UPDATE_CHECK "${UPDATE_CHECK:-notify}" notify off
+ need_choice MODS_SYNC "${MODS_SYNC:-auto}" auto off
need_int PORT "${PORT:-28090}"; need_int MAX_PLAYERS "${MAX_PLAYERS:-8}"; need_int AUTOSAVE_MINUTES "${AUTOSAVE_MINUTES:-10}"; need_int BACKUPS "${BACKUPS:-10}"
}
@@ -105,6 +107,20 @@ cmd_install_game() {
log "game installed ($(du -sh --apparent-size "$GAME" | cut -f1) apparent, $(du -sh "$GAME" | cut -f1) on disk)"
}
+cmd_mods() {
+ ensure_dirs
+ local sub=${1:-status}; [ $# -gt 0 ] && shift
+ case "$sub" in
+ login|status|setup-root) exec python3 "$OPT/scripts/mods.py" "$sub" "$@" ;;
+ list|sync)
+ local w=${1:-${WORLD:-}}; [ -n "$w" ] || die "usage: mods $sub " 2
+ [ -f "$SESSION_FILE" ] || die "sign in first (login): the save folder depends on the Steam account" 40
+ [ $# -gt 0 ] && shift
+ exec python3 "$OPT/scripts/mods.py" "$sub" "$(save_dir)/$w.sav" "$@" ;;
+ *) die "mods: login | list | sync [--check] | status" 2 ;;
+ esac
+}
+
cmd_import_save() {
[ $# -gt 0 ] || die "usage: import-save [more files of the same save]" 2
[ -f "$SESSION_FILE" ] || die "sign in first (login): the save folder depends on the Steam account" 40
@@ -128,6 +144,12 @@ cmd_run() {
# the game's settings: a minimal profile (lowest graphics) the first time; MPFever activates its mod in it
mkdir -p "$(local_dir)/mods" "$(save_dir)" # where the game and MPFever look for the mod and the saves (a new profile has none of them)
[ -f "$(local_dir)/settings.lua" ] || cp "$OPT/config/settings.lua" "$(local_dir)/settings.lua"
+ # the world's mods: the launcher and the game both look for mod.io mods in /data/modio; with a mod.io key (mods login) the world's mods are installed or updated first
+ python3 "$OPT/scripts/mods.py" setup-root
+ if [ "${MODS_SYNC:-auto}" = auto ] && [ -f "$SECRETS/modio.json" ]; then
+ log "mods: installing or updating the world's mods from mod.io"
+ python3 "$OPT/scripts/mods.py" sync "$(save_dir)/$WORLD.sav" || warn "mods: not every mod could be updated (the installed versions are used)"
+ fi
# the launcher package of this image version, and the server settings from the environment (the file is rewritten at every start)
cp -a "$OPT/pkg/." "$SRV/"
@@ -208,7 +230,8 @@ case "$MODE" in
login) cmd_login ;;
install-game) cmd_install_game "$@" ;;
import-save) cmd_import_save "$@" ;;
+ mods) cmd_mods "$@" ;;
status) cmd_status ;;
shell) exec bash ;;
- *) die "unknown mode '$MODE' (run, login, install-game, import-save, status, shell)" 2 ;;
+ *) die "unknown mode '$MODE' (run, login, install-game, import-save, mods, status, shell)" 2 ;;
esac
diff --git a/server/scripts/mods.py b/server/scripts/mods.py
new file mode 100644
index 00000000..553a8a88
--- /dev/null
+++ b/server/scripts/mods.py
@@ -0,0 +1,394 @@
+#!/usr/bin/env python3
+"""mods: the mods of the worlds the server hosts. They come from mod.io (the game's Mod Hub), with the administrator's own API key.
+
+ mods login store the mod.io API path and key (typed here, kept 0600 in the data volume, never in the image)
+ mods list the mods a savegame needs (id, origin, mod.io number, name)
+ mods sync [--check] install or update the savegame's mod.io mods (--check: only say what would change)
+ mods status the mods installed on the server, with their version
+ mods setup-root tell the launcher and the game where the mods are (called at every start)
+
+Each mod is kept twice: the full version as mod.io publishes it (/mods/full//: what the server sends to a joining player) and the version the game loads
+(/modio//mods//): the same files, sizes and scripts, but the data a headless server never uses (textures, sounds) left out (see mklite.py).
+Only the mod.io API (the administrator's key) is contacted."""
+import argparse, getpass, hashlib, html, json, os, shutil, struct, sys, tempfile, time, urllib.error, urllib.request, zipfile
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+import mklite
+
+GAME_ID = 10640 # Transport Fever 3 on mod.io
+WINE_ROOT = "C:\\modio" # LITE as the game (Wine) sees it
+DATA = os.environ.get("DATA", "/data")
+CONF = os.path.join(DATA, "secrets", "modio.json")
+FULL = os.path.join(DATA, "mods", "full")
+LITE = os.path.join(DATA, "modio")
+UA = "MPFever-server/1.0 (+https://github.com/dkdknight/MPFever)" # mod.io (Cloudflare) refuses the default Python agent
+
+
+# ---------------------------------------------------------------- the savegame's mod list (SaveInfo.ModsOf of the launcher)
+
+def mods_of(d):
+ """The mods a savegame lists, from its first bytes decompressed: [(id, origin, mod.io number or '', name)], or None. A count (uint32), then per mod five strings
+ (uint32 length, UTF-8: id, origin, hub id, name, url) and an int32 severity of 0 to 2; the list is the first place of the first 64 KiB where a whole list holds."""
+ n = min(len(d), 65536)
+ for off in range(0, max(n - 3, 0)):
+ count = struct.unpack_from(" 4096:
+ continue
+ p, out, ok = off + 4, [], True
+ for _ in range(count):
+ f = []
+ for k in range(5):
+ if p + 4 > len(d):
+ ok = False; break
+ ln = struct.unpack_from(" 4096 or p + 4 + ln > len(d):
+ ok = False; break
+ try:
+ f.append(d[p + 4:p + 4 + ln].decode("utf-8", "strict" if k < 3 else "replace"))
+ except UnicodeDecodeError:
+ ok = False; break
+ p += 4 + ln
+ if not ok or p + 4 > len(d):
+ ok = False; break
+ sev = struct.unpack_from(" 2 or not f[0] or any(ord(c) < 32 for c in f[0] + f[1]) or not hub_ok:
+ ok = False; break
+ out.append((f[0], f[1], f[2] if f[2].isdigit() else "", f[3] or f[0]))
+ if ok:
+ return out
+ return None
+
+
+def save_mods(path):
+ import zstandard
+ with open(path, "rb") as fh:
+ head = zstandard.ZstdDecompressor().stream_reader(fh).read(1 << 20)
+ return mods_of(head)
+
+
+# ---------------------------------------------------------------- mod.io
+
+def load_conf():
+ try:
+ with open(CONF) as f:
+ c = json.load(f)
+ if c.get("host") and c.get("api_key"):
+ return c
+ except (OSError, ValueError):
+ pass
+ return None
+
+
+PACE = 1.2 # seconds between two API calls (mod.io allows 60 a minute to a key)
+_last = [0.0]
+
+
+def api(conf, path, query=""):
+ url = "%s%s?api_key=%s%s" % (conf["host"].rstrip("/"), path, conf["api_key"], ("&" + query) if query else "")
+ req = urllib.request.Request(url, headers={"User-Agent": UA, "Accept": "application/json"})
+ for attempt in range(6):
+ wait = _last[0] + PACE - time.time()
+ if wait > 0:
+ time.sleep(wait)
+ _last[0] = time.time()
+ try:
+ with urllib.request.urlopen(req, timeout=30) as r:
+ return json.loads(r.read())
+ except urllib.error.HTTPError as e:
+ if e.code != 429 or attempt == 5:
+ raise
+ try:
+ delay = int(e.headers.get("Retry-After") or e.headers.get("X-RateLimit-RetryAfter") or 30)
+ except ValueError:
+ delay = 30
+ time.sleep(min(max(delay, 1), 120)) # mod.io's rate limit: wait as it says, then ask again
+
+
+def live_file(conf, mod_id):
+ """(mod, file) of the Windows build a mod.io mod currently publishes."""
+ m = api(conf, "/games/%d/mods/%s" % (GAME_ID, mod_id))
+ live = next((p["modfile_live"] for p in m.get("platforms", []) if p.get("platform") == "windows"), None) or (m.get("modfile") or {}).get("id")
+ if not live:
+ raise RuntimeError("mod %s publishes no Windows file" % mod_id)
+ return m, api(conf, "/games/%d/mods/%s/files/%s" % (GAME_ID, mod_id, live))
+
+
+def download(url, dest, md5):
+ req = urllib.request.Request(url, headers={"User-Agent": UA})
+ h = hashlib.md5()
+ with urllib.request.urlopen(req, timeout=120) as r, open(dest, "wb") as f:
+ while True:
+ b = r.read(1 << 20)
+ if not b:
+ break
+ h.update(b); f.write(b)
+ if h.hexdigest() != md5:
+ raise RuntimeError("download of %s does not match its published hash" % os.path.basename(dest))
+
+
+def extract_all(z, dest, warn=print):
+ """Extracts an archive; an entry that does not stay in the folder is refused. Some mods are published with a wrong CRC on a few entries (the data inflates fine and the whole
+ file matches mod.io's hash): such an entry is kept as published, with a warning, as the game's own installer does."""
+ root = os.path.realpath(dest)
+ for info in z.infolist():
+ name = info.filename.replace("\\", "/")
+ target = os.path.realpath(os.path.join(dest, name))
+ if name.startswith("/") or (target != root and not target.startswith(root + os.sep)):
+ raise RuntimeError("unsafe path in the mod's archive: %s" % info.filename)
+ if info.is_dir():
+ os.makedirs(target, exist_ok=True)
+ continue
+ os.makedirs(os.path.dirname(target), exist_ok=True)
+ try:
+ with z.open(info) as src, open(target, "wb") as out:
+ shutil.copyfileobj(src, out)
+ except zipfile.BadZipFile as e:
+ if "CRC" not in str(e):
+ raise
+ crc, info.CRC = info.CRC, None # no reference to compare with: the data as it inflates
+ try:
+ with z.open(info) as src, open(target, "wb") as out:
+ shutil.copyfileobj(src, out)
+ finally:
+ info.CRC = crc
+ warn("wrong CRC in the published archive for %s (kept as published)" % info.filename)
+
+
+def installed(mod_id):
+ try:
+ with open(os.path.join(FULL, str(mod_id), ".modio.json")) as f:
+ return json.load(f)
+ except (OSError, ValueError):
+ return None
+
+
+def lite_tree(src, dst):
+ """The same tree with what a headless server never uses left out (mklite.py): every file keeps its size."""
+ stats = dict(hole=0, copied=0, written=0, plans=0)
+ for root, _dirs, files in os.walk(src):
+ out = os.path.join(dst, os.path.relpath(root, src))
+ os.makedirs(out, exist_ok=True)
+ for name in files:
+ mklite.process_loose(os.path.join(root, name), os.path.join(out, name), stats)
+ return stats
+
+
+# what the game's own state file keeps of a mod's profile (it does not start with the other fields of mod.io's answer)
+PROFILE_KEYS = ("community_options", "date_added", "date_live", "date_updated", "dependencies", "description", "description_plaintext", "id", "logo", "maturity_option", "media",
+ "metadata_blob", "metadata_kvp", "modfile", "name", "profile_url", "stats", "status", "submitted_by", "summary", "tags", "visible")
+
+
+def no_nulls(o):
+ """The game's library reads every text field as text: a null where mod.io gave none stops it at start."""
+ if isinstance(o, dict):
+ return {k: no_nulls(v) for k, v in o.items()}
+ if isinstance(o, list):
+ return [no_nulls(v) for v in o]
+ return "" if o is None else o
+
+
+def register(m, f, lite_dir):
+ """The game's mod.io library keeps the list of installed mods in //metadata/state.json and knows no mod that is not in it: this adds or replaces this mod's entry
+ (the profile as mod.io published it, the folder as the game sees it)."""
+ path = os.path.join(LITE, str(GAME_ID), "metadata", "state.json")
+ try:
+ with open(path, encoding="utf-8") as fh:
+ state = json.load(fh)
+ except (OSError, ValueError):
+ state = {}
+ mods_list = [e for e in state.get("Mods", []) if e.get("ID") != m["id"]]
+ size = sum(os.path.getsize(os.path.join(r, n)) for r, _d, names in os.walk(lite_dir) for n in names)
+ seen_by_wine = WINE_ROOT + lite_dir[len(LITE):].replace("/", "\\")
+ profile = no_nulls({k: m[k] for k in PROFILE_KEYS if k in m})
+ profile["modfile"] = no_nulls(f) # (the file that is live for Windows: the profile's own "modfile" is empty when files are per platform)
+ mods_list.append({"ID": m["id"], "NeverRetryCategory": 0, "NeverRetryCode": 0, "PathOnDisk": seen_by_wine, "Profile": profile, "SizeOnDisk": size, "State": 1,
+ "SubscriptionCount": [(m.get("stats") or {}).get("subscribers_total", 1)]})
+ mods_list.sort(key=lambda e: e["ID"])
+ os.makedirs(os.path.dirname(path), exist_ok=True)
+ with open(path + ".tmp", "w", encoding="utf-8") as fh:
+ json.dump({"Mods": mods_list, "version": 1}, fh)
+ os.replace(path + ".tmp", path)
+
+
+def install(conf, mod_id, force=False, check=False, log=print):
+ """Installs or updates one mod.io mod; returns 'new', 'updated', 'current' (or 'would-install' / 'would-update' with check)."""
+ m, f = live_file(conf, mod_id)
+ have = installed(mod_id)
+ if have and have.get("file_id") == f["id"] and not force:
+ if not check:
+ register(m, f, os.path.join(LITE, str(GAME_ID), "mods", str(mod_id))) # (also refreshes the profile)
+ return "current"
+ kind = "update" if have else "install"
+ if check:
+ return "would-" + kind
+ log("%s %s (%s, %.1f MB)" % ("updating" if have else "installing", html.unescape(m["name"]), f.get("version") or "?", f["filesize"] / 1e6))
+ work = tempfile.mkdtemp(prefix="mod-", dir=os.path.join(DATA, "mods") if os.path.isdir(os.path.join(DATA, "mods")) else None)
+ try:
+ zpath = os.path.join(work, "mod.zip")
+ download(f["download"]["binary_url"], zpath, f["filehash"]["md5"])
+ full_new = os.path.join(work, "full")
+ with zipfile.ZipFile(zpath) as z:
+ extract_all(z, full_new, lambda msg: log("warning: " + msg))
+ meta = {"mod_id": int(mod_id), "name": m.get("name_id") or m.get("name"), "title": html.unescape(m.get("name") or ""), "file_id": f["id"], "md5": f["filehash"]["md5"],
+ "version": f.get("version"), "date_updated": f.get("date_added"), "installed": int(time.time())}
+ with open(os.path.join(full_new, ".modio.json"), "w") as fh:
+ json.dump(meta, fh)
+ lite_new = os.path.join(work, "lite")
+ lite_tree(full_new, lite_new)
+ os.remove(os.path.join(lite_new, ".modio.json"))
+ full_dir, lite_dir = os.path.join(FULL, str(mod_id)), os.path.join(LITE, str(GAME_ID), "mods", str(mod_id))
+ for target, new in ((full_dir, full_new), (lite_dir, lite_new)):
+ os.makedirs(os.path.dirname(target), exist_ok=True)
+ if os.path.isdir(target):
+ shutil.rmtree(target)
+ shutil.move(new, target)
+ register(m, f, lite_dir)
+ return "updated" if have else "new"
+ finally:
+ shutil.rmtree(work, ignore_errors=True)
+
+
+# ---------------------------------------------------------------- commands
+
+def cmd_login(a):
+ host = a.host or input("mod.io API path (mod.io/me/access, like https://u-123456.modapi.io/v1): ").strip()
+ key = os.environ.get("MODIO_API_KEY") or (sys.stdin.readline().strip() if not sys.stdin.isatty() else getpass.getpass("mod.io API key (not shown): ").strip())
+ if not host.startswith("https://") or len(key) < 16:
+ print("the API path must start with https:// and the key must be the 32 characters of mod.io/me/access", file=sys.stderr)
+ return 2
+ conf = {"host": host, "api_key": key}
+ try:
+ name = api(conf, "/games/%d" % GAME_ID).get("name")
+ except urllib.error.URLError as e:
+ print("mod.io refused this path and key: %s" % e, file=sys.stderr)
+ return 1
+ os.makedirs(os.path.dirname(CONF), mode=0o700, exist_ok=True)
+ fd = os.open(CONF + ".tmp", os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
+ with os.fdopen(fd, "w") as f:
+ json.dump(conf, f)
+ os.replace(CONF + ".tmp", CONF)
+ print("mod.io access works (%s). Saved." % name)
+ return 0
+
+
+def modio_mods(path):
+ lst = save_mods(path)
+ if lst is None:
+ raise RuntimeError("cannot read the mod list of %s" % path)
+ return lst
+
+
+def cmd_list(a):
+ for mid, origin, hub, name in modio_mods(a.save):
+ print("%-8s %-14s %-9s %s" % (origin, mid[:14], hub or "-", name))
+ return 0
+
+
+def subscribe():
+ """The game's mod.io library lists as installed only the mods its signed-in user is subscribed to (/AppData/Local/mod.io///user.json). A server has no mod.io
+ account to sign in with, so it gets a local user record subscribed to every mod installed here: the library then reports them, and nothing leaves the machine."""
+ try:
+ with open(os.path.join(LITE, str(GAME_ID), "metadata", "state.json"), encoding="utf-8") as fh:
+ ids = sorted(int(e["ID"]) for e in json.load(fh).get("Mods", []))
+ except (OSError, ValueError):
+ return 0
+ wine = os.environ.get("WINEPREFIX", os.path.join(DATA, "wine"))
+ users = os.path.join(wine, "drive_c", "users")
+ steam = os.path.join(wine, "drive_c", "Program Files (x86)", "Steam", "userdata")
+ accounts = sorted(d for d in (os.listdir(steam) if os.path.isdir(steam) else []) if d.isdigit() and d != "0")
+ n = 0
+ for u in (sorted(os.listdir(users)) if os.path.isdir(users) else []):
+ base = os.path.join(users, u, "AppData", "Local", "mod.io", str(GAME_ID))
+ if u == "Public" or not os.path.isdir(os.path.dirname(base)):
+ continue
+ existing = sorted(d for d in (os.listdir(base) if os.path.isdir(base) else []) if d.isdigit())
+ for acc in accounts or existing:
+ os.makedirs(os.path.join(base, acc), exist_ok=True)
+ blank = {"filename": "", "original": "", "thumb_100x100": "", "thumb_50x50": ""}
+ record = {"Avatar": blank, "DeferredUnsubscribes": [], "OAuth": {"expiry": 4102444800, "status": 0, "token": "offline"},
+ "Profile": {"avatar": blank, "date_online": 0, "display_name_portal": "mpfever-server", "id": 1, "profile_url": "https://mod.io", "username": "mpfever-server"},
+ "subscriptions": ids, "version": 1}
+ with open(os.path.join(base, acc, "user.json"), "w", encoding="utf-8") as fh:
+ json.dump(record, fh)
+ n += 1
+ return n
+
+
+def cmd_sync(a):
+ conf = load_conf()
+ if not conf:
+ print("no mod.io access yet: run mods login", file=sys.stderr)
+ return 3
+ want = [(mid, hub, name) for mid, origin, hub, name in modio_mods(a.save) if origin == "mod.io" and hub]
+ rc, counts = 0, {}
+ for mid, hub, name in want:
+ try:
+ r = install(conf, hub, check=a.check)
+ except (urllib.error.URLError, RuntimeError, OSError, zipfile.BadZipFile) as e:
+ print("FAILED %s (%s): %s" % (name, hub, e), file=sys.stderr)
+ rc = 1
+ continue
+ counts[r] = counts.get(r, 0) + 1
+ if r != "current":
+ print("%s: %s" % (r, name))
+ if not a.check:
+ subscribe()
+ print("mods of the world: %d from mod.io (%s)" % (len(want), ", ".join("%d %s" % (v, k) for k, v in sorted(counts.items())) or "none"))
+ return rc
+
+
+def cmd_status(a):
+ if not os.path.isdir(FULL):
+ print("no mod installed")
+ return 0
+ for d in sorted(os.listdir(FULL)):
+ meta = installed(d) or {}
+ print("%-9s %-34s v%-6s file %s" % (d, (meta.get("title") or meta.get("name") or "?")[:34], meta.get("version") or "?", meta.get("file_id") or "?"))
+ return 0
+
+
+def cmd_setup_root(a):
+ """The launcher (Mono) and the game (Wine) both read %LOCALAPPDATA%/mod.io/globalsettings.json: RootLocalStoragePath is where they find the mods."""
+ home = os.environ.get("HOME", DATA)
+ wine = os.environ.get("WINEPREFIX", os.path.join(DATA, "wine"))
+ users = os.path.join(wine, "drive_c", "users")
+ targets = [(os.path.join(os.environ.get("XDG_DATA_HOME", os.path.join(home, ".local", "share")), "mod.io", "globalsettings.json"), LITE)]
+ if os.path.isdir(users):
+ for u in sorted(os.listdir(users)):
+ if u not in ("Public",) and os.path.isdir(os.path.join(users, u)):
+ targets.append((os.path.join(users, u, "AppData", "Local", "mod.io", "globalsettings.json"), WINE_ROOT))
+ os.makedirs(LITE, exist_ok=True)
+ link = os.path.join(wine, "drive_c", "modio") # the game's mod.io library cannot use a Z: folder that exists (Wine error 4390): the folder is reached through C:
+ if os.path.isdir(os.path.dirname(link)):
+ if os.path.islink(link) and os.readlink(link) != LITE:
+ os.remove(link)
+ if not os.path.lexists(link):
+ os.symlink(LITE, link)
+ for path, root in targets:
+ os.makedirs(os.path.dirname(path), exist_ok=True)
+ with open(path, "w") as f:
+ json.dump({"RootLocalStoragePath": root}, f)
+ subscribe()
+ return 0
+
+
+def main(argv=None):
+ ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
+ sub = ap.add_subparsers(dest="cmd", required=True)
+ p = sub.add_parser("login"); p.add_argument("--host")
+ p = sub.add_parser("list"); p.add_argument("save")
+ p = sub.add_parser("sync"); p.add_argument("save"); p.add_argument("--check", action="store_true")
+ sub.add_parser("status")
+ sub.add_parser("setup-root")
+ a = ap.parse_args(argv)
+ try:
+ return {"login": cmd_login, "list": cmd_list, "sync": cmd_sync, "status": cmd_status, "setup-root": cmd_setup_root}[a.cmd](a)
+ except (RuntimeError, OSError) as e:
+ print("error: %s" % e, file=sys.stderr)
+ return 1
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/server/tests/check.sh b/server/tests/check.sh
index ec74edf3..a5ad1447 100644
--- a/server/tests/check.sh
+++ b/server/tests/check.sh
@@ -11,7 +11,7 @@ if command -v shellcheck >/dev/null; then step "shellcheck"; shellcheck -S warni
step "python"
python3 -m py_compile scripts/*.py || fail=1
-python3 -m unittest -q tests.test_steam_session tests.test_admin 2>&1 | tail -3 || fail=1
+python3 -m unittest -q tests.test_steam_session tests.test_admin tests.test_mods 2>&1 | tail -3 || fail=1
python3 tests/selftest_lite.py | tail -2 || fail=1
step "madeira dock (unit tests, tools)"
diff --git a/server/tests/test_mods.py b/server/tests/test_mods.py
new file mode 100644
index 00000000..78b72bdb
--- /dev/null
+++ b/server/tests/test_mods.py
@@ -0,0 +1,176 @@
+"""Checks of scripts/mods.py with no network: the savegame's mod list, and an install/update/check round trip against a fake mod.io server (own API path, file, hash, download)."""
+import hashlib, http.server, io, json, os, struct, sys, tempfile, threading, unittest, zipfile
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+sys.path.insert(0, os.path.join(HERE, "..", "scripts"))
+import mods
+
+try:
+ import zstandard
+except ImportError:
+ zstandard = None
+
+
+def entry(mid, origin, hub, name):
+ s = lambda x: struct.pack(" bytes
+ live = {} # mod id -> file id
+ log = []
+
+ def log_message(self, *a):
+ pass
+
+ def send(self, obj, code=200):
+ data = json.dumps(obj).encode()
+ self.send_response(code); self.send_header("Content-Type", "application/json"); self.end_headers(); self.wfile.write(data)
+
+ def do_GET(self):
+ FakeModio.log.append(self.path.split("?")[0])
+ if "api_key=KEY" not in self.path and not self.path.startswith("/dl/"):
+ return self.send({"error": {"message": "bad key"}}, 401)
+ parts = self.path.split("?")[0].strip("/").split("/")
+ if parts[:1] == ["dl"]:
+ data = FakeModio.zips[int(parts[1])]
+ self.send_response(200); self.end_headers(); self.wfile.write(data); return
+ if parts == ["v1", "games", "10640"]:
+ return self.send({"id": 10640, "name": "Transport Fever 3"})
+ if len(parts) == 5 and parts[3] == "mods":
+ mid = int(parts[4])
+ return self.send({"id": mid, "name": "Mod %d" % mid, "name_id": "mod_%d" % mid, "platforms": [{"platform": "windows", "modfile_live": FakeModio.live[mid]}]})
+ if len(parts) == 7 and parts[5] == "files":
+ fid, data = int(parts[6]), FakeModio.zips[int(parts[6])]
+ host = "http://127.0.0.1:%d" % self.server.server_port
+ return self.send({"id": fid, "version": "1.%d" % fid, "filesize": len(data), "filehash": {"md5": hashlib.md5(data).hexdigest()}, "download": {"binary_url": host + "/dl/%d" % fid}})
+ self.send({"error": {"message": "not found"}}, 404)
+
+
+class Install(unittest.TestCase):
+ def setUp(self):
+ self.tmp = tempfile.TemporaryDirectory()
+ d = self.tmp.name
+ mods.DATA, mods.CONF, mods.PACE = d, os.path.join(d, "secrets", "modio.json"), 0
+ mods.FULL, mods.LITE = os.path.join(d, "mods", "full"), os.path.join(d, "modio")
+ os.makedirs(os.path.join(d, "mods"))
+ FakeModio.zips, FakeModio.live, FakeModio.log = {1: mod_zip()}, {777: 1}, []
+ self.srv = http.server.HTTPServer(("127.0.0.1", 0), FakeModio)
+ threading.Thread(target=self.srv.serve_forever, daemon=True).start()
+ self.conf = {"host": "http://127.0.0.1:%d/v1" % self.srv.server_port, "api_key": "KEY"}
+
+ def tearDown(self):
+ self.srv.shutdown(); self.srv.server_close(); self.tmp.cleanup()
+
+ def test_install_update_and_check(self):
+ quiet = lambda *a: None
+ self.assertEqual(mods.install(self.conf, 777, check=True), "would-install")
+ self.assertEqual(mods.install(self.conf, 777, log=quiet), "new")
+ full = os.path.join(mods.FULL, "777")
+ lite = os.path.join(mods.LITE, "10640", "mods", "777")
+ self.assertTrue(os.path.isfile(os.path.join(full, ".modio.json")))
+ self.assertFalse(os.path.exists(os.path.join(lite, ".modio.json")))
+ # the full copy is the published files, the game's copy keeps every path and size with the textures left out
+ self.assertEqual(os.path.getsize(os.path.join(full, "res/textures/big.dds")), 100000)
+ self.assertEqual(os.path.getsize(os.path.join(lite, "res/textures/big.dds")), 100000)
+ self.assertEqual(open(os.path.join(lite, "content/script.lua")).read(), "print('hi')")
+ state = json.load(open(os.path.join(mods.LITE, "10640", "metadata", "state.json")))
+ self.assertEqual([e["ID"] for e in state["Mods"]], [777])
+ self.assertEqual(state["Mods"][0]["PathOnDisk"], "C:\\modio\\10640\\mods\\777")
+ self.assertEqual(state["Mods"][0]["Profile"]["id"], 777)
+ self.assertEqual(mods.install(self.conf, 777, log=quiet), "current")
+ FakeModio.zips[2] = mod_zip(b"more"); FakeModio.live[777] = 2
+ self.assertEqual(mods.install(self.conf, 777, check=True), "would-update")
+ self.assertEqual(mods.install(self.conf, 777, log=quiet), "updated")
+ self.assertEqual(mods.installed(777)["file_id"], 2)
+ self.assertEqual(os.path.getsize(os.path.join(lite, "res/textures/big.dds")), 100004)
+
+ def test_wrong_hash_is_refused_and_nothing_is_kept(self):
+ class Bad(FakeModio):
+ pass
+ FakeModio.zips[1] = mod_zip()
+ orig = mods.download
+ mods.download = lambda url, dest, md5: orig(url, dest, "0" * 32)
+ try:
+ with self.assertRaises(RuntimeError):
+ mods.install(self.conf, 777, log=lambda *a: None)
+ finally:
+ mods.download = orig
+ self.assertFalse(os.path.exists(os.path.join(mods.FULL, "777")))
+
+ def test_entry_with_a_wrong_crc_is_kept_with_a_warning(self):
+ b = io.BytesIO()
+ with zipfile.ZipFile(b, "w", zipfile.ZIP_DEFLATED) as z:
+ z.writestr("a.lua", "x = 1")
+ z.writestr("tex/big.dds", b"D" * 5000)
+ raw = bytearray(b.getvalue())
+ directory = bytes(raw).rfind(bytes([0x50, 0x4B, 1, 2])) # the central directory record of the second entry: its CRC is 16 bytes in
+ raw[directory + 16] ^= 0xFF
+ with zipfile.ZipFile(io.BytesIO(bytes(raw))) as z: # the archive must now really fail the check
+ with self.assertRaises(zipfile.BadZipFile):
+ z.read("tex/big.dds")
+ FakeModio.zips[1] = bytes(raw)
+ warnings = []
+ with zipfile.ZipFile(io.BytesIO(bytes(raw))) as z, tempfile.TemporaryDirectory() as d:
+ mods.extract_all(z, d, warnings.append)
+ self.assertEqual(open(os.path.join(d, "tex", "big.dds"), "rb").read(), b"D" * 5000)
+ self.assertEqual(open(os.path.join(d, "a.lua")).read(), "x = 1")
+ self.assertEqual(len(warnings), 1)
+ self.assertIn("big.dds", warnings[0])
+
+ def test_unsafe_archive_is_refused(self):
+ b = io.BytesIO()
+ with zipfile.ZipFile(b, "w") as z:
+ z.writestr("../evil.lua", "x")
+ FakeModio.zips[1] = b.getvalue()
+ with self.assertRaises(RuntimeError):
+ mods.install(self.conf, 777, log=lambda *a: None)
+
+ def test_setup_root_writes_both_settings_files(self):
+ d = self.tmp.name
+ os.makedirs(os.path.join(d, "wine", "drive_c", "users", "tf3"))
+ os.environ["HOME"], os.environ["WINEPREFIX"] = d, os.path.join(d, "wine")
+ self.assertEqual(mods.cmd_setup_root(None), 0)
+ launcher = json.load(open(os.path.join(d, ".local", "share", "mod.io", "globalsettings.json")))
+ wine = json.load(open(os.path.join(d, "wine", "drive_c", "users", "tf3", "AppData", "Local", "mod.io", "globalsettings.json")))
+ self.assertEqual(launcher["RootLocalStoragePath"], mods.LITE)
+ self.assertEqual(wine["RootLocalStoragePath"], "C:\\modio")
+ self.assertEqual(os.path.realpath(os.path.join(d, "wine", "drive_c", "modio")), os.path.realpath(mods.LITE))
+
+
+if __name__ == "__main__":
+ unittest.main()
From bd896306b3cfef404a51b9c8a5994b6b72ff459d Mon Sep 17 00:00:00 2001
From: ampynjord <82981605+ampynjord@users.noreply.github.com>
Date: Thu, 19 Nov 2026 20:00:19 +0100
Subject: [PATCH 22/47] Docker server: the server offers joining players the
mod.io mods in full (MPFEVER_MODSTORE), self-test, guide section on mods,
changelog
---
docs/CHANGELOG.txt | 4 +++
docs/DOCKER-SERVER.md | 29 +++++++++++++++++--
launcher/MainForm.cs | 56 +++++++++++++++++++++++-------------
launcher/Mods.cs | 50 +++++++++++++++++++++++++++++++-
launcher/SelfTest.cs | 37 ++++++++++++++++++++++++
server/scripts/entrypoint.sh | 1 +
6 files changed, 153 insertions(+), 24 deletions(-)
diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index f83106e2..53901320 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -12,6 +12,10 @@ MPFever - Changelog
client; long runs, several clients and large worlds are not yet (see the guide). For the Docker server the launcher also has MPFEVER_LOG_JSON=1 (one JSON object
per line in its log file: ts, level, component, msg), MPFEVER_CMDDIR (one file per console command: `mpfever-admin` runs the commands of the server window from
outside) and autoupdate=notify (a new release is announced in the log, never installed). CI: ci.yml (jobs docker-server-checks and docker-server) and, to publish the image, release.yml (option docker_server).
+ - NEW (server/, mods): the Docker server installs the mod.io mods of its world (`mods login/list/sync/status`; the key is typed once and kept in the data volume only): a reduced copy for the game (files a server
+ never reads left empty, same paths and sizes) and the full copy kept apart; checked and updated at every start (SRV_MODS_SYNC). The launcher, with MPFEVER_MODSTORE (a Docker server only), offers a
+ joining player the mods it lacks in their full version, from that store; the player's MPFever shows the offer and installs them once accepted. The game's mod.io library is given what it needs to list the mods
+ (its state file and a local subscription record).
- BUILD (code signing, 2026-11-19: SignPath Foundation accepted MPFever; their first step is a signature with their
self-signed test certificate, then they review the setup and import the Foundation's certificate): the Release build
workflow asks for the signing policy, test-signing by default, release-signing once the certificate is in. Archives signed
diff --git a/docs/DOCKER-SERVER.md b/docs/DOCKER-SERVER.md
index 91e7172d..c231d472 100644
--- a/docs/DOCKER-SERVER.md
+++ b/docs/DOCKER-SERVER.md
@@ -83,6 +83,7 @@ the command runs on: a shell variable wins over `.env` (Windows defines `PUBLIC`
| `SRV_PUBLIC`, `SRV_PUBLIC_ADDRESS` | `false`, empty | list the server in MPFever's public list |
| `SRV_LOG_FORMAT` | `json` | `json` (one JSON object per line) or `text` |
| `SRV_UPDATE_CHECK` | `notify` | `notify` (new MPFever release announced in the log, never installed) or `off` |
+| `SRV_MODS_SYNC` | `auto` | `auto` (the world's mod.io mods are installed or updated at every start, when `mods login` was done) or `off` |
| `SRV_MEM_LIMIT`, `SRV_CPUS` | `16g`, `2` | container limits: about 12 GB and 1 CPU for the small world (minimum), 16 GB and 2 CPUs for a world of 120 MB; the CPU also sets how fast it starts and resynchronises |
| `MPFEVER_IMAGE` | the published image | another image or a version tag (rollback) |
@@ -122,6 +123,29 @@ docker compose exec mpfever-server mpfever-admin save
It hands the command to the launcher (a file in `/data/run/cmd`), waits for it to run and prints what the server logged for it. Everything the Windows server's console does is reachable this way (see the server's `SERVER.txt`).
An administration web page is planned (off by default); it will use the same channel.
+## Mods
+
+A world that uses mods needs them on the server and on every player's PC, in the same version. The server installs the world's **mod.io** mods itself:
+
+```
+docker compose run --rm mpfever-server mods login # once: the API path and key of mod.io.com/me/access (typed, never put in a file or the image)
+docker compose run --rm mpfever-server mods list # the mods the world's savegame uses, and where they come from
+docker compose run --rm mpfever-server mods sync # installs or updates them (the same at every server start, see below)
+docker compose run --rm mpfever-server mods status # what is installed
+```
+
+`login` checks the key against mod.io and keeps it in `secrets/modio.json` of the data volume (mode 0600). Each mod is downloaded (size and hash checked) into **two copies**: the game runs from a
+**reduced copy** (`/data/modio`: every file keeps its path and size, the textures, models, sounds and other files a headless server never reads are left empty, as in the lite game install), and the
+**full copy** stays in `/data/mods/full` for the players. Mods published to the Steam Workshop or kept on a PC are not fetched (import of a local mod is not done yet).
+
+- **At every start** (`SRV_MODS_SYNC=auto`, the default; `off` skips it): the world's mods are checked against mod.io and the newer versions installed, so mods follow the server's updates. A mod.io outage
+ never stops the server: the installed copies are used.
+- **A player who joins without a mod** is offered it by the server, at once, in the full version (the launcher's mod sending, as a host's PC does for local mods): the player's MPFever shows the offer and,
+ once accepted, installs the mod in the player's own mods folder. A mod is code, so a player who does not accept it is never sent it. A player whose copy is another version is told to update it.
+- The game's mod.io library only reports the mods its signed-in user is subscribed to. A server has no mod.io account, so `mods sync` writes a local user record subscribed to the installed mods
+ (`AppData/Local/mod.io/10640//user.json` of the Wine prefix); nothing is sent to mod.io from it. The game also cannot use an existing `Z:` folder as mod.io's root (Wine error 4390), so the
+ root is reached as `C:\modio` (a link to `/data/modio`).
+
## Logs
`docker compose logs` shows every component on one stream, **one JSON object per line**: `{"ts":"2026-11-19T15:46:34.409Z","level":"info","component":"launcher","msg":"WinClient#1 joined the session"}`
@@ -189,12 +213,11 @@ read-only container. Then a longer run:
| `docker compose stop` while a client has vanished (killed abruptly) | 71 s, exit code 0, the world saved: the stop waits up to about 60 s for the lost client, inside the 90 s script and 120 s Compose timeouts |
**Known limits found by these runs**
-- **Worlds that use mods:** the server has no way to install a world's mods yet. A real 595 MB world using 15 mod.io mods was refused ("Missing mods: the session ends"). A client whose own game had personal mods stayed stuck on
- "loading" for 10 minutes on the 122 MB world (the server resumed without it after 616 s). Importing mods is the next piece of work.
+- **Worlds that use mods:** a real 595 MB world with 15 mod.io mods runs (`mods sync`, then start: "IN SYNC", no missing mod). Not yet run: a player joining and receiving the mods (the launcher's sending path is tested at the unit level only), mods from the Steam Workshop or local ones, and the long-run memory of such a world. A client whose own game had personal mods stayed stuck on "loading" for 10 minutes on the 122 MB world (the server resumed without it after 616 s).
- **Public list and Steam join:** with `SRV_PUBLIC=true` (or a stray host variable, see Settings) the server is announced to MPFever's public list with its Steam ID, and anyone can join through Steam; a
stranger did so during the first long run. Keep `SRV_PUBLIC=false` and set `SRV_PASSWORD` for a private server.
-**Not validated yet:** several clients at once (local test clients, or a second Steam account), worlds with mods, runs of several hours. **The GPU variant** (`compose.gpu.yaml`, Intel/AMD through `/dev/dri` on a
+**Not validated yet:** several clients at once (local test clients, or a second Steam account), a player receiving the mods from the server, runs of several hours. **The GPU variant** (`compose.gpu.yaml`, Intel/AMD through `/dev/dri` on a
Linux host) was not run; on Docker Desktop with WSL2 it cannot work as written (the container gets `/dev/dxg` and no WSL driver libraries): software rendering is the supported mode there.
## Build, tests, publication
diff --git a/launcher/MainForm.cs b/launcher/MainForm.cs
index c8cd784d..4328b8c5 100644
--- a/launcher/MainForm.cs
+++ b/launcher/MainForm.cs
@@ -1881,7 +1881,7 @@ void SetHostMods(string mods, Client client, string name)
// not sent, as before (the chat at the load only)
string riskyLobby = "";
try { if (Environment.GetEnvironmentVariable("MPFEVER_MODRISKLOBBY") != "0") riskyLobby = string.Join(",", Mods.RiskyPlan(mods)); } catch { }
- try { client?.Send(Msg.Make("modcheck", name, "{[\"differs\"]=" + LuaLit.Quote(string.Join(", ", c.Differs)) + ",[\"nohub\"]=" + LuaLit.Quote(string.Join(",", noHub)) + ",[\"risky\"]=" + LuaLit.Quote(riskyLobby) + "}")); } catch { }
+ try { client?.Send(Msg.Make("modcheck", name, "{[\"differs\"]=" + LuaLit.Quote(string.Join(", ", c.Differs)) + ",[\"nohub\"]=" + LuaLit.Quote(string.Join(",", noHub)) + ",[\"missing\"]=" + LuaLit.Quote(string.Join(",", c.MissingIds)) + ",[\"risky\"]=" + LuaLit.Quote(riskyLobby) + "}")); } catch { }
MenuStatus();
}
@@ -2222,18 +2222,40 @@ string ModAskView()
+ kv.Value.Split(',').Sum(x => double.TryParse(Mods.SizeMb(x), NumberStyles.Float, CultureInfo.InvariantCulture, out var v) ? v : 0).ToString("0.0", CultureInfo.InvariantCulture)));
}
+ /// (the host) Offers a player the mods it lacks (it must accept) or says no; a server offers at once, whoever joins.
+ void OfferMods(string who, bool yes)
+ {
+ string ids; lock (modAsks) { if (!modAsks.TryGetValue(who, out ids)) return; modAsks.Remove(who); modAskDone[who] = yes ? "offered:" + ids : "refused"; }
+ var peer = relay?.Find(who);
+ if (peer == null) return;
+ if (yes)
+ {
+ double mb = ids.Split(',').Sum(x => double.TryParse(Mods.SizeMb(x), NumberStyles.Float, CultureInfo.InvariantCulture, out var v) ? v : 0);
+ relay.Send(peer, Msg.Make("modoffer", hostName, "{[\"ids\"]=" + LuaLit.Quote(ids) + ",[\"mb\"]=" + mb.ToString("0.0", CultureInfo.InvariantCulture) + "}"));
+ modSendText = F("Mods proposés à {0} : il doit accepter.", "Mods offered to {0}: they must accept.", BaseName(who));
+ if (ServerMode) Log.W("Mods offered to " + BaseName(who) + ": " + ids);
+ }
+ else
+ {
+ relay.Send(peer, Msg.Make("modoffer", hostName, "{[\"no\"]=true}"));
+ modSendText = "";
+ }
+ MenuStatus();
+ }
+
/// (the host) Each mod's folder, zipped, to one player in parts (as the savegame goes).
void SendMods(Peer peer, List ids)
{
int sent = 0;
foreach (var id in ids)
{
- var dir = Mods.Dir(id);
+ var dir = Mods.StoreDir(id) ?? (Mods.Store == "" ? Mods.Dir(id) : null);
if (dir == null) continue;
string tmp = Path.Combine(Path.GetTempPath(), "mpfever-mod-" + Guid.NewGuid().ToString("N") + ".zip");
try
{
- ZipFile.CreateFromDirectory(dir, tmp, CompressionLevel.Optimal, false);
+ if (Mods.StoreDir(id) == dir) Mods.ZipFolder(dir, tmp);
+ else ZipFile.CreateFromDirectory(dir, tmp, CompressionLevel.Optimal, false);
var bytes = File.ReadAllBytes(tmp);
int parts = (bytes.Length + ResyncChunk - 1) / ResyncChunk;
for (int i = 0; i < parts; i++)
@@ -2625,21 +2647,7 @@ void OnMenuRequest(string cmd, string arg, string name, string option = "")
string who;
lock (modAsks) who = modAsks.Keys.FirstOrDefault(k => k == arg) ?? modAsks.Keys.FirstOrDefault(k => BaseName(k) == arg);
if (who == null) return;
- string ids; lock (modAsks) { ids = modAsks[who]; modAsks.Remove(who); modAskDone[who] = option == "1" ? "offered:" + ids : "refused"; }
- var peer = relay?.Find(who);
- if (peer == null) return;
- if (option == "1")
- {
- double mb = ids.Split(',').Sum(x => double.TryParse(Mods.SizeMb(x), NumberStyles.Float, CultureInfo.InvariantCulture, out var v) ? v : 0);
- relay.Send(peer, Msg.Make("modoffer", hostName, "{[\"ids\"]=" + LuaLit.Quote(ids) + ",[\"mb\"]=" + mb.ToString("0.0", CultureInfo.InvariantCulture) + "}"));
- modSendText = F("Mods proposés à {0} : il doit accepter.", "Mods offered to {0}: they must accept.", BaseName(who));
- }
- else
- {
- relay.Send(peer, Msg.Make("modoffer", hostName, "{[\"no\"]=true}"));
- modSendText = "";
- }
- MenuStatus();
+ OfferMods(who, option == "1");
}
else if (cmd == "takemods")
{
@@ -4976,10 +4984,16 @@ void OnHostMessage(Msg m, Peer from)
var differs = h.TryGetValue("differs", out var dv) && dv is string ds ? ds : "";
lock (modIssues) { if (differs != "") modIssues[BaseName(from.Name)] = differs; else modIssues.Remove(BaseName(from.Name)); }
var nohub = h.TryGetValue("nohub", out var nv) && nv is string ns ? ns : "";
+ // (0.9.2, a Docker server) the Mod Hub's mods too, from the server's store of full copies (MPFEVER_MODSTORE): a player who lacks one is offered it
+ var storeIds = new List();
+ if (Mods.Store != "" && h.TryGetValue("missing", out var miv) && miv is string mis)
+ storeIds = mis.Split(',').Select(x => x.Trim()).Where(x => x != "" && Mods.StoreDir(x) != null).ToList();
+ if (storeIds.Count > 0) nohub = string.Join(",", nohub.Split(',').Select(x => x.Trim()).Where(x => x != "").Union(storeIds, StringComparer.OrdinalIgnoreCase));
+ bool offerAtOnce = false;
lock (modAsks)
{
// (only mods of this savegame installed here: nothing else is ever sent)
- var ids = nohub.Split(',').Select(x => x.Trim()).Where(x => x != "" && Mods.Dir(x) != null && Mods.Parse(lobbyMods).Any(e => e.Id.Equals(x, StringComparison.OrdinalIgnoreCase))).ToList();
+ var ids = nohub.Split(',').Select(x => x.Trim()).Where(x => x != "" && (Mods.StoreDir(x) != null || (Mods.Store == "" && Mods.Dir(x) != null)) && Mods.Parse(lobbyMods).Any(e => e.Id.Equals(x, StringComparison.OrdinalIgnoreCase))).ToList();
// (0.6.7) a missing mod this PC cannot send is said, never dropped silently (the host saw nothing on 2026-11-01)
var unsendable = nohub.Split(',').Select(x => x.Trim()).Where(x => x != "" && !ids.Contains(x)).ToList();
if (unsendable.Count > 0)
@@ -4988,7 +5002,8 @@ void OnHostMessage(Msg m, Peer from)
if (ids.Count > 0 && !modAskDone.ContainsKey(from.Name))
{
modAsks[from.Name] = string.Join(",", ids);
- Log.Warn(F("{0} n'a pas {1} mod(s) qu'aucun Mod Hub n'a : {2}. Vous pouvez les lui envoyer depuis la page Multijoueur.", "{0} lacks {1} mod(s) no Mod Hub has: {2}. You can send them from the Multiplayer page.", BaseName(from.Name), ids.Count, string.Join(", ", ids)));
+ if (ServerMode && Mods.Store != "") offerAtOnce = true;
+ else Log.Warn(F("{0} n'a pas {1} mod(s) qu'aucun Mod Hub n'a : {2}. Vous pouvez les lui envoyer depuis la page Multijoueur.", "{0} lacks {1} mod(s) no Mod Hub has: {2}. You can send them from the Multiplayer page.", BaseName(from.Name), ids.Count, string.Join(", ", ids)));
}
else if (ids.Count == 0) modAsks.Remove(from.Name);
}
@@ -4998,6 +5013,7 @@ void OnHostMessage(Msg m, Peer from)
OnPlayerRiskyMods(BaseName(from.Name), risky);
BroadcastLobby();
MenuStatus();
+ if (offerAtOnce) OfferMods(from.Name, true);
}
break;
diff --git a/launcher/Mods.cs b/launcher/Mods.cs
index c8756572..0ccaa3ce 100644
--- a/launcher/Mods.cs
+++ b/launcher/Mods.cs
@@ -2,6 +2,7 @@
using System.Collections.Generic;
using System.Globalization;
using System.IO;
+using System.IO.Compression;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
@@ -323,6 +324,53 @@ public static string Dir(string id)
}
}
+ /// (a Docker server, MPFEVER_MODSTORE) The folder that keeps each mod.io mod of the server in its full version (the game runs from a copy without what a server never uses).
+ /// "" when this PC keeps none: then nothing of the Mod Hub is ever sent.
+ public static string Store => (Environment.GetEnvironmentVariable("MPFEVER_MODSTORE") ?? "").Trim();
+
+ static Dictionary storeDirs; static DateTime storeAt;
+ static readonly Regex NoteName = new Regex("\"name\"\\s*:\\s*\"([^\"]+)\"");
+
+ /// The full copy of a mod in the store (its folder holds a .modio.json that names the mod), or null.
+ public static string StoreDir(string id)
+ {
+ if (Store == "" || !Directory.Exists(Store)) return null;
+ lock (Known)
+ {
+ if (storeDirs == null || (DateTime.UtcNow - storeAt).TotalSeconds > 30)
+ {
+ var map = new Dictionary(StringComparer.OrdinalIgnoreCase);
+ try
+ {
+ foreach (var d in Directory.GetDirectories(Store))
+ {
+ try
+ {
+ var m = NoteName.Match(File.ReadAllText(Path.Combine(d, ".modio.json")));
+ if (m.Success) map[m.Groups[1].Value] = d;
+ }
+ catch { }
+ }
+ }
+ catch { }
+ storeDirs = map; storeAt = DateTime.UtcNow;
+ }
+ return id != null && storeDirs.TryGetValue(id, out var v) ? v : null;
+ }
+ }
+
+ /// A mod's folder zipped for a player: the files as they are, without the store's own note (.modio.json), so the player's copy is the published one.
+ public static void ZipFolder(string dir, string zipPath)
+ {
+ using (var z = ZipFile.Open(zipPath, ZipArchiveMode.Create))
+ foreach (var f in Directory.GetFiles(dir, "*", SearchOption.AllDirectories))
+ {
+ var rel = f.Substring(dir.Length).TrimStart('\\', '/').Replace('\\', '/');
+ if (rel == ".modio.json") continue;
+ z.CreateEntryFromFile(f, rel, CompressionLevel.Optimal);
+ }
+ }
+
/// The installed mods are looked for again at the next question (a mod was just installed).
public static void Rescan() { lock (Known) dirs = null; }
@@ -692,7 +740,7 @@ static Tuple Info(string id)
/// The size of an installed mod's folder in MB (one decimal), "" when it is not installed here.
public static string SizeMb(string id)
{
- var d = Dir(id);
+ var d = StoreDir(id) ?? Dir(id);
if (d == null) return "";
lock (sizeCache)
{
diff --git a/launcher/SelfTest.cs b/launcher/SelfTest.cs
index 353af8d9..1270bab6 100644
--- a/launcher/SelfTest.cs
+++ b/launcher/SelfTest.cs
@@ -62,6 +62,7 @@ public static int Run()
ok &= RunDiag();
ok &= RunIssue111();
ok &= RunSession067();
+ ok &= RunModStore();
ok &= RunDlcs();
ok &= RunSaveMods();
ok &= RunServerConfig();
@@ -1652,6 +1653,42 @@ static bool RunDiag()
return ok;
}
+ /// (0.9.2) A Docker server keeps each mod.io mod in full beside the reduced copy the game runs from: found by the mod's name, sent without its own note.
+ static bool RunModStore()
+ {
+ bool ok = true;
+ void Check(bool cond, string what) { Log.W((cond ? " ok " : " FAIL ") + what); ok &= cond; }
+ var root = Path.Combine(Path.GetTempPath(), "mpf-store-" + Guid.NewGuid().ToString("N"));
+ var old = Environment.GetEnvironmentVariable("MPFEVER_MODSTORE");
+ try
+ {
+ var dir = Path.Combine(root, "6440137");
+ Directory.CreateDirectory(Path.Combine(dir, "res"));
+ File.WriteAllText(Path.Combine(dir, ".modio.json"), "{\"mod_id\": 6440137, \"name\": \"apasz_zigzag\"}");
+ File.WriteAllText(Path.Combine(dir, "mod.lua"), "x");
+ File.WriteAllBytes(Path.Combine(dir, "res", "big.dds"), new byte[5000]);
+ Environment.SetEnvironmentVariable("MPFEVER_MODSTORE", root);
+ Check(Mods.Store == root, "mod store: the folder comes from MPFEVER_MODSTORE");
+ Check(Mods.StoreDir("apasz_zigzag") == dir, "mod store: a mod is found by its name");
+ Check(Mods.StoreDir("unknown_mod") == null, "mod store: an unknown mod is not found");
+ var zip = Path.Combine(root, "t.zip");
+ Mods.ZipFolder(dir, zip);
+ using (var z = System.IO.Compression.ZipFile.OpenRead(zip))
+ {
+ var names = z.Entries.Select(e => e.FullName).OrderBy(x => x).ToList();
+ Check(string.Join(",", names) == "mod.lua,res/big.dds", "mod store: the zip holds the files, not the store's own note (" + string.Join(",", names) + ")");
+ }
+ Environment.SetEnvironmentVariable("MPFEVER_MODSTORE", "");
+ Check(Mods.Store == "" && Mods.StoreDir("apasz_zigzag") == null, "mod store: none set, none used");
+ }
+ finally
+ {
+ Environment.SetEnvironmentVariable("MPFEVER_MODSTORE", old);
+ try { Directory.Delete(root, true); } catch { }
+ }
+ return ok;
+ }
+
/// (0.6.7) The session of 2026-11-01: a local mod (StagingArea) is the host's to send, found in staging_area; Real
/// Track Cant judged incompatible, the game's No costs made compatible.
static bool RunSession067()
diff --git a/server/scripts/entrypoint.sh b/server/scripts/entrypoint.sh
index 0820008b..bf79b299 100644
--- a/server/scripts/entrypoint.sh
+++ b/server/scripts/entrypoint.sh
@@ -189,6 +189,7 @@ cmd_run() {
export MPFEVER_CMDDIR=$RUN/cmd; mkdir -p "$MPFEVER_CMDDIR"; rm -f "$MPFEVER_CMDDIR"/* # the commands of `mpfever-admin`
# logs: the launcher writes the same JSON lines as this script (SRV_LOG_FORMAT=text: plain lines)
if [ "${LOG_FORMAT:-json}" = json ]; then export MPFEVER_LOG_JSON=1; else unset MPFEVER_LOG_JSON; fi
+ export MPFEVER_MODSTORE=$DATA/mods/full # the mod.io mods in full: the launcher offers them to the players who join (the game itself runs from the reduced copies of /data/modio)
# no 3D output: software Vulkan with a layer that makes every draw and copy a no-op and gives back the GPU memory nobody reads;
# MPF_VKNULL=0 (docker compose: GPU=1) leaves a real GPU alone
export MPF_VKNULL=${MPF_VKNULL:-1} MPF_VKNULL_MODE=all MPF_VKNULL_TRIM=${MPF_VKNULL_TRIM:-1}
From 15f9c8f2653748150617a0da1751578e6e8a34f8 Mon Sep 17 00:00:00 2001
From: ampynjord <82981605+ampynjord@users.noreply.github.com>
Date: Thu, 19 Nov 2026 20:13:57 +0100
Subject: [PATCH 23/47] Docker server logs: the game's and Dock's own logs join
the stream (components game and dock, SRV_GAME_LOG)
---
server/.env.example | 2 +
server/compose.yaml | 1 +
server/scripts/entrypoint.sh | 10 +++-
server/scripts/logship.py | 113 +++++++++++++++++++++++++++++++++++
server/tests/check.sh | 2 +-
server/tests/test_logship.py | 86 ++++++++++++++++++++++++++
6 files changed, 212 insertions(+), 2 deletions(-)
create mode 100644 server/scripts/logship.py
create mode 100644 server/tests/test_logship.py
diff --git a/server/.env.example b/server/.env.example
index 1808d1e9..8c32e8b0 100644
--- a/server/.env.example
+++ b/server/.env.example
@@ -22,6 +22,8 @@ SRV_LOG_FORMAT=json
SRV_UPDATE_CHECK=notify
# Mods: auto (with a mod.io key from `mods login`, the world's mods are installed or updated at every start) or off
SRV_MODS_SYNC=auto
+# The game's and Dock's own logs in the same stream: off, error, warn (default), info or debug
+SRV_GAME_LOG=warn
# Resource limits. Small world: 12 GB and 1 CPU is the minimum (slow to start); a world of 120 MB needs 16 GB and 2 CPUs.
SRV_MEM_LIMIT=16g
SRV_CPUS=2
diff --git a/server/compose.yaml b/server/compose.yaml
index 9b716b6b..beeabf0b 100644
--- a/server/compose.yaml
+++ b/server/compose.yaml
@@ -28,6 +28,7 @@ services:
LOG_FORMAT: ${SRV_LOG_FORMAT:-json}
UPDATE_CHECK: ${SRV_UPDATE_CHECK:-notify}
MODS_SYNC: ${SRV_MODS_SYNC:-auto}
+ GAME_LOG: ${SRV_GAME_LOG:-warn}
volumes:
- data:/data # Wine prefix, Valve client, Steam session (secrets/), saves, launcher and its logs and backups
- game:/game # the "lite" game install (about 1 GB on disk)
diff --git a/server/scripts/entrypoint.sh b/server/scripts/entrypoint.sh
index bf79b299..bd32852c 100644
--- a/server/scripts/entrypoint.sh
+++ b/server/scripts/entrypoint.sh
@@ -70,6 +70,7 @@ check_settings() {
need_choice LOG_FORMAT "${LOG_FORMAT:-json}" json text
need_choice UPDATE_CHECK "${UPDATE_CHECK:-notify}" notify off
need_choice MODS_SYNC "${MODS_SYNC:-auto}" auto off
+ need_choice GAME_LOG "${GAME_LOG:-warn}" off error warn info debug
need_int PORT "${PORT:-28090}"; need_int MAX_PLAYERS "${MAX_PLAYERS:-8}"; need_int AUTOSAVE_MINUTES "${AUTOSAVE_MINUTES:-10}"; need_int BACKUPS "${BACKUPS:-10}"
}
@@ -199,6 +200,13 @@ cmd_run() {
Xvfb :1 -screen 0 1024x768x24 -nolisten tcp >/dev/null 2>&1 & XVFB=$!
sleep 2
+ # the game's and Dock's own logs join the stream (SRV_GAME_LOG: off, error, warn (default), info or debug): components "game" and "dock"
+ SHIPPERS=()
+ if [ "${GAME_LOG:-warn}" != off ]; then
+ python3 "$OPT/scripts/logship.py" game "$(local_dir)/crash_dump/stdout.txt" "${GAME_LOG:-warn}" & SHIPPERS+=($!)
+ python3 "$OPT/scripts/logship.py" dock "$SRV/dock.log" "${GAME_LOG:-warn}" & SHIPPERS+=($!)
+ fi
+
STOPPING=0; LAUNCHER=0
on_term() {
STOPPING=1; log "stop requested: saving the world and closing the game"
@@ -222,7 +230,7 @@ cmd_run() {
[ "$quick" -lt 5 ] || { kill "$FEEDER" "$XVFB" 2>/dev/null; die "the launcher stopped 5 times within a minute (last status $rc): see $SRV/launcher.out and $SRV/dock.log" 50; }
log "the launcher stopped (status $rc): starting it again in 10 s"; sleep 10
done
- kill "$FEEDER" "$XVFB" 2>/dev/null; wineserver -k 2>/dev/null
+ kill "$FEEDER" "$XVFB" "${SHIPPERS[@]}" 2>/dev/null; wineserver -k 2>/dev/null
log "stopped"
}
diff --git a/server/scripts/logship.py b/server/scripts/logship.py
new file mode 100644
index 00000000..4966062b
--- /dev/null
+++ b/server/scripts/logship.py
@@ -0,0 +1,113 @@
+#!/usr/bin/env python3
+"""logship: follows a log file of the game or of Dock and writes its lines to this process's output in the server's own log shape, so `docker logs` holds one stream.
+
+ logship.py game /path/stdout.txt warn # the game's log ([time - LEVEL - thread - module] message); only warn and above
+ logship.py dock /path/dock.log debug # Dock's log ([steam-host] ...); everything
+
+Levels: debug < info < warn < error; `off` ships nothing. The file may be replaced or emptied (the game starts again): it is followed from its start then.
+One line out per line in: {"ts","level","component","msg"} (LOG_FORMAT=text: `HH:MM:SS LEVEL component msg`)."""
+import json, os, re, sys, time
+
+LEVELS = {"debug": 0, "info": 1, "warn": 2, "error": 3}
+GAME_LINE = re.compile(r"^\[(\d{4}-\d\d-\d\d) (\d\d:\d\d:\d\d)Z - (\w+)\s*- ([^-]*?)\s*- ([^\]]*?)\s*\]\s?(.*)$")
+GAME_LEVEL = {"VERBOSE": "debug", "DEBUG": "debug", "MESSAGE": "info", "INFO": "info", "WARNING": "warn", "ERROR": "error", "FATAL": "error"}
+BAD_WORDS = re.compile(r"\b(error|failed|fail|fatal|cannot|denied|refused)\b", re.I)
+
+
+def now():
+ return time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime()) + ".%03dZ" % (int(time.time() * 1000) % 1000)
+
+
+class Shaper:
+ """Turns the lines of one file into (ts, level, component, msg); a line that continues the one before it (a stack, a detail) keeps that line's level."""
+
+ def __init__(self, kind):
+ self.kind, self.level, self.ts = kind, "debug", None
+
+ def shape(self, line):
+ line = line.rstrip("\r\n")
+ if not line.strip():
+ return None
+ if self.kind == "game":
+ m = GAME_LINE.match(line)
+ if m:
+ self.level = GAME_LEVEL.get(m.group(3).upper(), "info")
+ self.ts = "%sT%s.000Z" % (m.group(1), m.group(2))
+ return self.ts, self.level, "game", m.group(6).strip() or "(" + m.group(5) + ")"
+ if line.startswith("[MPFEVER"): # the MPFever mod's own lines, no time stamp
+ self.level, self.ts = "info", None
+ return now(), "info", "game", line
+ return self.ts or now(), self.level, "game", line.strip() # a continuation
+ level = "warn" if BAD_WORDS.search(line) else "debug"
+ return now(), level, "dock", line.strip()
+
+
+def emit(rec, fmt, out):
+ ts, level, comp, msg = rec
+ if fmt == "text":
+ out.write("%s %-5s %s: %s\n" % (ts[11:19], level.upper(), comp, msg))
+ else:
+ out.write(json.dumps({"ts": ts, "level": level, "component": comp, "msg": msg}, ensure_ascii=False) + "\n")
+ out.flush()
+
+
+def same_start(path, head):
+ try:
+ with open(path, "rb") as f:
+ return f.read(len(head)) == head
+ except OSError:
+ return True
+
+
+def follow(path, shaper, minimum, fmt, out, stop=lambda: False, poll=0.5, skip_existing=False):
+ """Reads the file from its start and on (skip_existing: from its end, what an earlier run wrote is not shipped again); reopened when it is replaced or shortened."""
+ pos, ino, buf, head = 0, None, "", b""
+ if skip_existing:
+ try:
+ st = os.stat(path)
+ pos, ino = st.st_size, st.st_ino
+ with open(path, "rb") as f:
+ head = f.read(64)
+ except OSError:
+ pass
+ while not stop():
+ try:
+ st = os.stat(path)
+ except OSError:
+ time.sleep(poll)
+ continue
+ if ino != st.st_ino or st.st_size < pos or (head and not same_start(path, head)):
+ pos, ino, buf, head = 0, st.st_ino, "", b"" # replaced, emptied, or written again from its start (the game starts again)
+ if st.st_size > pos:
+ with open(path, "r", encoding="utf-8", errors="replace", newline="") as f:
+ f.seek(pos)
+ data = f.read()
+ pos = f.tell()
+ buf += data
+ if not head:
+ with open(path, "rb") as f:
+ head = f.read(64)
+ *lines, buf = buf.split("\n")
+ for line in lines:
+ rec = shaper.shape(line)
+ if rec and LEVELS[rec[1]] >= minimum:
+ emit(rec, fmt, out)
+ else:
+ time.sleep(poll)
+
+
+def main(argv):
+ if len(argv) != 4 or argv[1] not in ("game", "dock") or argv[3] not in list(LEVELS) + ["off"]:
+ print(__doc__.split("\n\n")[0], file=sys.stderr)
+ return 2
+ if argv[3] == "off":
+ return 0
+ follow(argv[2], Shaper(argv[1]), LEVELS[argv[3]], os.environ.get("LOG_FORMAT", "json"), sys.stdout, skip_existing=True)
+ return 0
+
+
+if __name__ == "__main__":
+ try:
+ sys.exit(main(sys.argv))
+ except KeyboardInterrupt:
+ sys.exit(0)
diff --git a/server/tests/check.sh b/server/tests/check.sh
index a5ad1447..5d2bbdb6 100644
--- a/server/tests/check.sh
+++ b/server/tests/check.sh
@@ -11,7 +11,7 @@ if command -v shellcheck >/dev/null; then step "shellcheck"; shellcheck -S warni
step "python"
python3 -m py_compile scripts/*.py || fail=1
-python3 -m unittest -q tests.test_steam_session tests.test_admin tests.test_mods 2>&1 | tail -3 || fail=1
+python3 -m unittest -q tests.test_steam_session tests.test_admin tests.test_mods tests.test_logship 2>&1 | tail -3 || fail=1
python3 tests/selftest_lite.py | tail -2 || fail=1
step "madeira dock (unit tests, tools)"
diff --git a/server/tests/test_logship.py b/server/tests/test_logship.py
new file mode 100644
index 00000000..6897041d
--- /dev/null
+++ b/server/tests/test_logship.py
@@ -0,0 +1,86 @@
+"""Checks of scripts/logship.py: the game's and Dock's lines become the server's log lines, filtered by level, and a replaced file is followed again."""
+import io, json, os, sys, tempfile, threading, time, unittest
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+sys.path.insert(0, os.path.join(HERE, "..", "scripts"))
+import logship
+
+WARN = "[2026-11-19 18:10:04Z - WARNING - ModioAsyncThread - Main ] Could not verify user authentication: Invalid user"
+INFO = "[2026-11-19 18:10:08Z - MESSAGE - Main Thread - Main ] Main menu is ready"
+VERB = "[2026-11-19 18:10:09Z - VERBOSE - Main - ModRep ] Found 15 mods"
+ERR = "[2026-11-19 17:53:17Z - ERROR - Main - Modio ]+ Could not initialize Modio"
+
+
+class Shape(unittest.TestCase):
+ def test_game_levels_and_time(self):
+ s = logship.Shaper("game")
+ self.assertEqual(s.shape(WARN), ("2026-11-19T18:10:04.000Z", "warn", "game", "Could not verify user authentication: Invalid user"))
+ self.assertEqual(s.shape(INFO)[1:], ("info", "game", "Main menu is ready"))
+ self.assertEqual(s.shape(VERB)[1], "debug")
+ self.assertEqual(s.shape(ERR)[1], "error")
+
+ def test_a_continuation_keeps_the_level_of_its_line(self):
+ s = logship.Shaper("game")
+ s.shape(ERR)
+ rec = s.shape(" + Location: gamelib/src/modhub/ModioModHubBackend.cpp(1911)")
+ self.assertEqual((rec[1], rec[2], rec[3]), ("error", "game", "+ Location: gamelib/src/modhub/ModioModHubBackend.cpp(1911)"))
+
+ def test_mpfever_mod_lines_are_info(self):
+ rec = logship.Shaper("game").shape("[MPFEVER-AUTO] loading savegame 'bigworld'")
+ self.assertEqual((rec[1], rec[3]), ("info", "[MPFEVER-AUTO] loading savegame 'bigworld'"))
+
+ def test_dock_lines(self):
+ s = logship.Shaper("dock")
+ self.assertEqual(s.shape("[steam-host] ml1830 engine005-present=1")[1:3], ("debug", "dock"))
+ self.assertEqual(s.shape("[steam-host] login failed: denied")[1], "warn")
+ self.assertIsNone(s.shape(" "))
+
+
+class Follow(unittest.TestCase):
+ def run_follow(self, minimum, fmt, steps):
+ with tempfile.TemporaryDirectory() as d:
+ path, out, done = os.path.join(d, "stdout.txt"), io.StringIO(), []
+ t = threading.Thread(target=logship.follow, args=(path, logship.Shaper("game"), minimum, fmt, out, lambda: bool(done), 0.02))
+ t.start()
+ for text, mode in steps:
+ with open(path, mode) as f:
+ f.write(text)
+ time.sleep(0.3)
+ done.append(1)
+ t.join()
+ return [l for l in out.getvalue().splitlines() if l]
+
+ def test_only_warnings_and_above(self):
+ lines = self.run_follow(logship.LEVELS["warn"], "json", [("\n".join([VERB, INFO, WARN, ERR]) + "\n", "w")])
+ got = [json.loads(l) for l in lines]
+ self.assertEqual([g["level"] for g in got], ["warn", "error"])
+ self.assertEqual(got[0]["component"], "game")
+
+ def test_a_file_that_starts_again_is_followed_from_its_start(self):
+ lines = self.run_follow(logship.LEVELS["debug"], "json", [(INFO + "\n", "w"), (WARN + "\n", "w")])
+ self.assertEqual([json.loads(l)["msg"] for l in lines], ["Main menu is ready", "Could not verify user authentication: Invalid user"])
+
+ def test_a_half_written_line_waits(self):
+ lines = self.run_follow(logship.LEVELS["debug"], "json", [(INFO[:30], "w"), (INFO[30:] + "\n", "a")])
+ self.assertEqual([json.loads(l)["msg"] for l in lines], ["Main menu is ready"])
+
+ def test_what_an_earlier_run_wrote_is_not_shipped_again(self):
+ with tempfile.TemporaryDirectory() as d:
+ path, out, done = os.path.join(d, "stdout.txt"), io.StringIO(), []
+ open(path, "w").write(INFO + "\n")
+ t = threading.Thread(target=logship.follow, args=(path, logship.Shaper("game"), 0, "json", out, lambda: bool(done), 0.02, True))
+ t.start()
+ time.sleep(0.2)
+ open(path, "a").write(WARN + "\n")
+ time.sleep(0.3)
+ done.append(1)
+ t.join()
+ self.assertEqual([json.loads(l)["level"] for l in out.getvalue().splitlines()], ["warn"])
+
+ def test_text_format(self):
+ lines = self.run_follow(logship.LEVELS["info"], "text", [(INFO + "\n", "w")])
+ self.assertEqual(lines, ["18:10:08 INFO game: Main menu is ready"])
+
+
+if __name__ == "__main__":
+ unittest.main()
From c0421f6e405daa27b10d4f2708500f3bbe28f7da Mon Sep 17 00:00:00 2001
From: ampynjord <82981605+ampynjord@users.noreply.github.com>
Date: Thu, 19 Nov 2026 20:14:33 +0100
Subject: [PATCH 24/47] Docker server mods: import of local mods from the
administrator's PC (mods import), mods list shows what is missing
---
server/scripts/entrypoint.sh | 7 +++-
server/scripts/mods.py | 77 ++++++++++++++++++++++++++++++++++--
server/tests/test_mods.py | 18 +++++++++
3 files changed, 98 insertions(+), 4 deletions(-)
diff --git a/server/scripts/entrypoint.sh b/server/scripts/entrypoint.sh
index bd32852c..727e2f63 100644
--- a/server/scripts/entrypoint.sh
+++ b/server/scripts/entrypoint.sh
@@ -118,7 +118,12 @@ cmd_mods() {
[ -f "$SESSION_FILE" ] || die "sign in first (login): the save folder depends on the Steam account" 40
[ $# -gt 0 ] && shift
exec python3 "$OPT/scripts/mods.py" "$sub" "$(save_dir)/$w.sav" "$@" ;;
- *) die "mods: login | list | sync [--check] | status" 2 ;;
+ import)
+ [ $# -gt 0 ] || die "usage: mods import (mount your mods folder: docker compose run --rm -v :/import:ro mpfever-server mods import /import)" 2
+ [ -f "$SESSION_FILE" ] || die "sign in first (login): the game's mods folder depends on the Steam account" 40
+ mkdir -p "$(local_dir)/mods"
+ exec python3 "$OPT/scripts/mods.py" import "$1" --dest "$(local_dir)/mods" ;;
+ *) die "mods: login | list | sync [--check] | import | status" 2 ;;
esac
}
diff --git a/server/scripts/mods.py b/server/scripts/mods.py
index 553a8a88..a33fe229 100644
--- a/server/scripts/mods.py
+++ b/server/scripts/mods.py
@@ -10,11 +10,12 @@
Each mod is kept twice: the full version as mod.io publishes it (