Compare commits

...
Author SHA1 Message Date
ДмитрийandClaude Opus 5.5 2e6fcceb05 CI: drop the launcher bridge test (the bridge was removed)
tools/test_launcher_bridge.py tested crates/coa-core/src/launcher_bridge.py,
which the Rust launcher replaced; check.yml and release.yml still ran it, so
the release build failed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 16:48:17 +05:00
ДмитрийandClaude Opus 5.5 abcc816581 Stop: ask the world again when a shutdown request is lost
A console shutdown request is sometimes lost, and the world then keeps
running until the stop times out. While the world still runs and its
console still answers after 15 s, the launcher asks again (twice at most);
asking twice is harmless. Verified on a disposable repack with the first
World::ShutdownServ call suppressed in a debugger: the second request
stopped the world.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 16:07:54 +05:00
ДмитрийandClaude Opus 5.5 8353b791fb The Manager no longer edits Scripts/manage.py
Repacks ship no .bat files, and the Manager starts servers with
coa-core::launcher, so the realm-profile patch it wrote into manage.py
served no one. It is no longer applied (realm creation, realm switching and
start).

Recognising the edits older Managers made (realm patch, bridge import fix)
moves into legacy_launcher, so updates and file checks still treat such a
file as unmodified. Nothing there writes a file.

manage.py itself stays complete in the repack: Managers up to 0.9.10 run it
through their bridge and patch its text, so it cannot become a thin wrapper
until those Managers are no longer supported.

Verified: coa-core unit tests; examples/manager_launcher_e2e on a disposable
repack (manage.py unchanged after a start with a realm profile).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 13:07:41 +05:00
ДмитрийandClaude Opus 5.5 b81227b0ea Bug-report relay in Rust (coa-launcher relay-worker)
launcher::relay does what BugReport/relay.py and manage.py relay-worker do,
with the same spool: the <key>.status files the world reads, the journal
relay.sqlite3 (deliveries, settings), relay.lock (byte 0) and the
relay-ready record. Service answers map to the same states and retry times;
a post interrupted mid-flight stays uncertain and is never resent.

When coa-launcher.exe supervises a world it runs the relay itself; the
Python supervisor still runs relay.py.

Verified:
- examples/relay_equivalence: the same reports and scripted service answers
  through relay.py and the Rust relay give identical statuses, journal rows
  (including retry times) and posts, and each continues the other's journal.
- examples/manager_launcher_e2e on a disposable repack: supervisor and relay
  are coa-launcher.exe, start/stop interoperates with manage.py.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 12:00:40 +05:00
ДмитрийandClaude Opus 5.5 a9fb982ab0 Console shutdown request reads the reply before closing
send_without_answer closed the socket right after writing "server shutdown".
With the reply still unread, Windows resets the connection, and the world
can drop the command: a world supervised by coa-launcher.exe ignored the
shutdown and the stop timed out after 90 seconds. The reply is now read up
to the next prompt, the end of the connection or 10 seconds.

The E2E also checks which supervisor runs the world and that manage.py
stops a world the Manager started.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 09:38:59 +05:00
ДмитрийandClaude Opus 5.5 a822bfc99b Manager starts and stops servers through the Rust launcher
driver::run now calls coa-core::launcher::ops::run in-process instead of
running Scripts/manage.py through launcher_bridge.py. Failures carry a typed
code (Error::Service) instead of being guessed from stderr text.

Moved into the launcher: realm profiles (realm id, name and databases from
Settings/realm-profile.json), extra worlds sharing the main database,
the shared world startup deadline and console readiness check, the owned-world
check on shutdown, force-stop-all, and an environment block without
AC_REALM_SERVER_PORT for update validation.

The world supervisor is Scripts/coa-launcher.exe when the repack ships it,
otherwise manage.py watch-world. Extra worlds get an unmodified manage.py.
The realm patch of manage.py stays for the repack's own .bat files.

Verified with examples/manager_launcher_e2e on a disposable repack.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 08:45:08 +05:00
ДмитрийandClaude Opus 5.5 1211de5a77 launcher (Rust): services inherit only their log and NUL; MySQL errors carry the server's text
std::process::Command lets a Windows child inherit every inheritable handle of the parent: a
MySQL started by the launcher kept the caller's files and pipes open (found by the SQUID test,
whose log stayed locked). Services now start through CreateProcessW with
PROC_THREAD_ATTRIBUTE_HANDLE_LIST = [log, NUL], as Python's subprocess does. The MySQL client's
outputs are read while it runs (a full pipe stopped it) and its last error line is reported.

E2E on a disposable repack: launcher_e2e PASS again; squid_equivalence PASS: Rust and
squid_playerbots.py leave identical journals, acore_playerbots tables (row counts) and
playerbots.conf (4106 lines), and a second run of either changes nothing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 07:48:04 +05:00
ДмитрийandClaude Opus 5.5 ee36692db7 launcher (Rust): services, world supervisor, SQUID provisioning, coa-launcher.exe
- services: exclusive-bind port check, readiness by listener row or the server side of a
  loopback connection, MySQL client, start MySQL/auth, stop-all (world through its console,
  database last), status.
- world: start-world through a supervisor process (coa-launcher watch-world) that keeps the
  bug-report relay (still BugReport/relay.py via the repack's Python) alive; detailed logging.
- squid: squid_playerbots.py in Rust with the same journals (coa_squid_migrations,
  coa_squid_pending, coa_bots_installed).
- coa-launcher.exe: the manage.py commands and error texts (the Manager reads them).
- Services no longer inherit the launcher's stdin/stdout/stderr: a server holding the
  output pipe kept whoever read the launcher's output waiting.

E2E (examples/launcher_e2e, disposable stable repack on free ports): coa-launcher start-all ->
manage.py sees and stops it; manage.py start-all -> coa-launcher sees and stops it; a second
Rust-only cycle leaves nothing running.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 07:29:55 +05:00
ДмитрийandClaude Opus 5.5 ee43522019 launcher (Rust): settings, state records, control lock, prepare
First part of moving Scripts/manage.py into coa-core (plan §17, PY-1). Same formats on disk as
manage.py so both can run on one server: .state records, the byte-0 control lock msvcrt.locking
takes, configuration.json. prepare renders byte-for-byte what manage.py renders (checked against
the real script, COA_MANAGE_PY). State files are flushed to disk before they replace the old ones,
and a damaged record counts as no process instead of failing every later start.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 06:58:16 +05:00
github-actions[bot] b4dc30b84a Update published Manager changelog 2026-11-08 10:21:07 +00:00
Дмитрий 73a6cca753 Integrate the qualified November release sources [skip ci] 2026-11-08 15:09:20 +05:00
Corfirean 705bee7d56 Merge verified Custom Races download recovery [skip ci]
Recover interrupted Custom Races patch downloads
2026-11-08 01:44:09 +05:00
Corfirean 5aa9b32283 Merge release cold-cache preparation fix [skip ci]
release: build the frontend before the tests
2026-11-08 01:44:05 +05:00
Дмитрий 711f378ae8 Bind translated release notes to the exact candidate sources [skip ci] 2026-11-08 01:23:56 +05:00
Corfirean c29d56e2b3 Register local installer preparation workflow [skip ci] 2026-11-08 01:21:16 +05:00
Дмитрий d63e85bb18 Prepare Manager 0.9.10 with reviewed notes and signing of local installers [skip ci] 2026-11-08 01:20:32 +05:00
Дмитрий c513649beb Merge remote-tracking branch 'origin/fix/recover-client-patch-downloads' into release/20261108-manager 2026-11-08 01:09:43 +05:00
ДмитрийandClaude Opus 5.5 2224afd2ea release: build the frontend before the tests
tauri::generate_context! needs ../dist. The tests run before tauri-action builds the frontend, so a
run without a warm target cache cannot compile the app (seen on preview/modules-v2, run 42224568581).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 19:47:11 +05:00
github-actions[bot] 3a5558f388 Update published Manager changelog 2026-11-04 11:39:56 +00:00
Дмитрий 173248efbe Prepare Manager 0.9.9 with isolated login validation and translated release notes 2026-11-03 19:44:03 +05:00
Дмитрий 5697a1d36e Merge commit '076fba1' into release/20261103-manager 2026-11-03 19:41:07 +05:00
github-actions[bot] bc62ae206f Update published Manager changelog 2026-11-01 11:00:31 +00:00
Дмитрий 076fba185c Remove duplicate Dungeon Clear dependency translation key 2026-11-01 14:23:37 +05:00
Дмитрий 23cbb108ad Prepare Manager 0.9.8 with isolated validation and SQUID module controls 2026-10-31 20:00:11 +05:00
Дмитрий 1a1976d9ad Recover interrupted Custom Races patch downloads 2026-10-31 07:55:15 +05:00
github-actions[bot] dc3fcab7e1 Update published Manager changelog 2026-10-30 21:38:45 +00:00
Corfirean ba5816e3ae Merge pull request #191 from Corfirean/fix/reviewed-server-notes-20261030
Check all upcoming server-note translations before freezing the Manager
2026-10-30 20:57:37 +05:00
Дмитрий 56faaa3a2a Qualify translations against the exact upcoming server notes including SQUID 2.8.2 2026-10-30 20:32:31 +05:00
Corfirean 35084dbce8 Merge pull request #190 from Corfirean/fix/update-release-history-target-20261030
Show notes for the available update despite a fresh older history cache
2026-10-30 15:29:35 +05:00
Дмитрий 7e7216979a Refresh release notes for the offered update instead of reusing incomplete history 2026-10-30 15:08:29 +05:00
github-actions[bot] 7c0c4cda1f Update published Manager changelog 2026-10-30 09:47:37 +00:00
Corfirean 642da8fdc1 Merge pull request #189 from Corfirean/fix/stabilization-20261030
Stabilize server updates, shutdown, accounts and client settings
2026-10-30 14:12:59 +05:00
Дмитрий 30d2f56997 Stabilize server lifecycle, client settings and release qualification 2026-10-30 14:04:18 +05:00
Дмитрий 4d1a6e0b21 Retain experimental Portable Characters notice for Manager 0.9.4 2026-10-29 20:51:31 +05:00
github-actions[bot] bda38b9f26 Update published Manager changelog 2026-10-29 15:31:44 +00:00
Дмитрий c004b90c54 Translate reviewed server candidate notes for Manager 0.9.4 2026-10-29 16:29:04 +05:00
Corfirean d44e00f9ad Merge pull request #177 from Corfirean/feat/settings-update-history
Reorganize settings, stabilize window sizing and group update actions
2026-10-29 16:15:14 +05:00
Дмитрий dad10d8a5d Integrate settings and release history for Manager 0.9.4 2026-10-29 16:10:43 +05:00
Corfirean b33821e7eb Record reviewed Manager 0.9.3 release notes 2026-10-29 10:33:27 +05:00
Corfirean 1288a84da2 Merge pull request #184 from Corfirean/fix/world-startup-deadline
Release Manager 0.9.3 with slow world startup recovery
2026-10-29 10:15:48 +05:00
Дмитрий e7b76137d1 Prepare Manager 0.9.3 and verify platform-specific realm restriction 2026-10-29 10:07:33 +05:00
Дмитрий 7bb0ea9472 Wait for slow CoA worlds before update rollback 2026-10-29 08:33:11 +05:00
Дмитрий 1dab6154c7 Record reviewed 0.9.2 notes and experimental notice 2026-10-28 23:22:07 +05:00
github-actions[bot] 06a6302732 Update published Manager changelog 2026-10-28 18:20:57 +00:00
Corfirean 65631450ff Merge pull request #181 from Corfirean/fix/manager-092-issues
Manager 0.9.2: database startup, recovery and CoA settings
2026-10-28 23:20:11 +05:00
Дмитрий 2d9c6a65bb Recover safely when rollback restores a legacy world launcher 2026-10-28 22:57:00 +05:00
Дмитрий ce83f04d9d Prepare Manager 0.9.2 with database startup and configuration fixes 2026-10-28 22:17:26 +05:00
Corfirean 81f031b30f Keep experimental notice in Manager 0.9.1 hotfix notes 2026-10-28 18:21:36 +05:00
github-actions[bot] ee3ca2c517 Update published Manager changelog 2026-10-28 13:20:54 +00:00
Corfirean 50e858dcd5 Merge pull request #179 from Corfirean/fix/update-preexisting-character-starts
Manager 0.9.1 hotfix: preserve existing character gaps during server updates
2026-10-28 18:19:47 +05:00
Дмитрий 8bbf16ed4f Prepare Manager 0.9.1 hotfix without settings redesign 2026-10-28 17:46:38 +05:00
Дмитрий 324e9810cc Compare character start gaps against a saved pre-update baseline 2026-10-28 17:40:42 +05:00
Дмитрий a8ab201d7d Document required changelog translation preparation 2026-10-28 16:39:16 +05:00
Дмитрий 733d73ef76 Keep window density stable and group update and launch actions 2026-10-28 15:42:47 +05:00
Дмитрий 5525325160 Group Manager settings and add translated release history 2026-10-28 15:26:01 +05:00
Дмитрий 1aade1dcf9 Keep experimental portable character notice in Manager 0.9.0 notes 2026-10-28 12:38:12 +05:00
Corfirean 787549237f Merge pull request #173 from Corfirean/prepare/manager-20261028
Prepare Manager 0.9.0 with integrated realm, race and scaling controls
2026-10-28 12:37:13 +05:00
github-actions[bot] 088cd05e4f Update published Manager changelog 2026-10-28 07:36:47 +00:00
147 changed files with 11499 additions and 1286 deletions

No files matched your search

+1
View File
@@ -25,4 +25,5 @@ jobs:
- run: npm ci
- run: node tools/check-i18n.mjs
- run: npm run build
- run: node --experimental-strip-types --test tools/*.test.mjs
- run: cargo test --workspace --locked
+4 -1
View File
@@ -69,8 +69,11 @@ jobs:
with:
node-version: 22
- run: npm ci
# tauri::generate_context! needs ../dist; without a warm target cache the tests do not compile without it.
- run: npm run build
- name: Tests
run: cargo test --workspace -- --test-threads=1
run: cargo test --workspace --locked -- --test-threads=1
- run: node --experimental-strip-types --test tools/*.test.mjs
- name: Build and sign (publish only when requested)
id: tauri
uses: tauri-apps/tauri-action@v0
@@ -0,0 +1,72 @@
name: sign-local-installer
on:
push:
branches: [release/20261108-manager]
workflow_dispatch:
inputs:
build_run_id:
description: Successful manager-local run in coa-server-build
required: true
permissions:
contents: read
actions: read
jobs:
sign:
if: github.event_name == 'workflow_dispatch'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- uses: actions/setup-node@v4
with:
node-version: 22
- name: Verify local build provenance
env:
GH_TOKEN: ${{ github.token }}
BUILD_RUN: ${{ inputs.build_run_id }}
run: |
python3 - <<'PY'
import json, os, subprocess
run = os.environ['BUILD_RUN']
if not run.isdigit():
raise RuntimeError('Invalid build run')
data = json.loads(subprocess.check_output(['gh', 'api', f'repos/Corfirean/coa-server-build/actions/runs/{run}']))
if data['conclusion'] != 'success' or data['path'] != '.github/workflows/manager-local.yml':
raise RuntimeError('Not a successful local Manager build')
subprocess.run(['gh', 'run', 'download', run, '-R', 'Corfirean/coa-server-build', '-n', 'unsigned-manager-windows', '-D', '_prepared-manager'], check=True)
from pathlib import Path
import hashlib
root = Path('_prepared-manager')
meta = json.loads((root / 'prepared-source.json').read_text())
version = json.loads(Path('package.json').read_text())['version']
name = meta['installer']
if Path(name).name != name or meta['source'] != os.environ['GITHUB_SHA'] or meta['version'] != version or str(meta['run']) != run:
raise RuntimeError('Installer identity differs')
if hashlib.sha256((root / name).read_bytes()).hexdigest() != meta['sha256']:
raise RuntimeError('Installer hash differs')
PY
- run: npm ci
- name: Sign exact locally compiled bytes
env:
TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }}
run: |
node --input-type=module <<'JS'
import { readFileSync, writeFileSync } from 'node:fs';
import { execFileSync } from 'node:child_process';
import { createHash } from 'node:crypto';
const root = '_prepared-manager/';
const meta = JSON.parse(readFileSync(root + 'prepared-source.json'));
execFileSync('node_modules/.bin/tauri', ['signer', 'sign', '--app-version', meta.version, root + meta.installer], {stdio: 'inherit'});
if (createHash('sha256').update(readFileSync(root + meta.installer)).digest('hex') !== meta.sha256) throw new Error('Signed bytes changed');
const signature = readFileSync(root + meta.installer + '.sig', 'utf8').trim();
const url = `https://github.com/Corfirean/coa-server-manager/releases/download/v${meta.version}/${encodeURIComponent(meta.installer)}`;
writeFileSync(root + 'latest.json', JSON.stringify({version: meta.version, notes: 'See the release notes.', pub_date: new Date().toISOString(), platforms: {'windows-x86_64': {signature, url}}}, null, 2) + '\n');
meta.signingRun = process.env.GITHUB_RUN_ID;
writeFileSync(root + 'prepared-source.json', JSON.stringify(meta, null, 2) + '\n');
JS
- uses: actions/upload-artifact@v4
with:
name: prepared-manager-windows
path: _prepared-manager/*
retention-days: 14
if-no-files-found: error
+10
View File
@@ -35,6 +35,16 @@ Every published Manager version, including a clearly marked Pre-release, belongs
CHANGELOG.md and changelog/history.json. Its GitHub release notes use the same reviewed record.
Promotion updates that entry without duplicating it; Manager and server histories remain separate.
Translated release notes are a required preparation step before freezing a new Manager source. Follow the
runbook's "Mandatory translated release notes during preparation" checklist: translate every new reviewed
Manager/server note into Russian, German, French, Spanish and Simplified Chinese in
`src/data/latest-note-translations.json`, keyed by exact canonical English text. Preserve existing translations
and released fragments. Refresh the bundled server-history snapshot from a pinned canonical commit and record
its provenance. Run `node --test tools/release-history.test.mjs`, `node tools/check-i18n.mjs` and `npm run build`;
verify each new record, all six viewer languages, English fallback and offline use. Save source/version and checks
in the handoff. Translations ship with Manager: a server-only release must record the carrying Manager version or
pending translation delivery, without forcing another Manager release or changing already signed installers.
Before preparing or publishing a Manager/server release, read the maintained
[release runbook](https://github.com/Corfirean/coa-server-build/blob/main/docs/server-release.md)
and [build agent instructions](https://github.com/Corfirean/coa-server-build/blob/main/AGENTS.md).
+98
View File
@@ -8,6 +8,104 @@ Published releases and previews. Pre-release entries do not change the stable up
Dates follow GitHub publication (UTC); legacy records retain their archived dates. Newest releases first.
## 0.9.10 — 2026-11-08
- Custom Races patch installation recovers from interrupted downloads.
[Release](https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.10) · [Source changes](https://github.com/Corfirean/coa-server-manager/compare/v0.9.9...v0.9.10)
## 0.9.9 — 2026-11-04
- Update and recovery checks use the temporary login port even with a Windows override.
[Release](https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.9) · [Source changes](https://github.com/Corfirean/coa-server-manager/compare/v0.9.8...v0.9.9)
## 0.9.8 — 2026-11-01
- Dungeon Clear can be enabled when SQUID bots are active.
- Diagnostic exports include launcher stages and lock owner records.
- Choose normal logs, errors only or no server logs in maintenance settings.
- Update checks temporarily suspend bot population and restore your configuration.
- Update validation keeps MySQL running between compatible checks.
[Release](https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.8) · [Source changes](https://github.com/Corfirean/coa-server-manager/compare/v0.9.7...v0.9.8)
## 0.9.7 — 2026-10-30
- Show available update notes even when release history is cached.
[Release](https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.7) · [Source changes](https://github.com/Corfirean/coa-server-manager/compare/v0.9.5...v0.9.7)
## 0.9.5 — 2026-10-30
- Account creation verifies a lost console reply against the requested login.
- Abandoned game relay tunnels close their local connection immediately.
- Keep disabled graphics components disabled during client updates.
- Force-stop an unresponsive world after a failed normal shutdown.
- Crash history includes reports from every world and Windows text files.
- Show the online bot count for Playerbots on the overview.
- Disable public server browsing in Settings.
- Keep deliberate stops and update shutdowns from triggering crash restart.
- Server startup waits for a responsive console before reporting success.
- Restore the existing Manager window when launching it again.
[Release](https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.5) · [Source changes](https://github.com/Corfirean/coa-server-manager/compare/v0.9.4...v0.9.5)
## 0.9.4 — 2026-10-29
**Portable Characters are experimental and may contain bugs.**
- Settings group updates, startup and maintenance with translated release history.
- Update and launch without updating share a divided button.
- Maximizing the window keeps text and controls at a comfortable size.
[Release](https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.4) · [Source changes](https://github.com/Corfirean/coa-server-manager/compare/v0.9.3...v0.9.4)
## 0.9.3 — 2026-10-29
**Portable Characters are experimental and may contain bugs.**
- Slow server startup no longer triggers an early update rollback.
[Release](https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.3) · [Source changes](https://github.com/Corfirean/coa-server-manager/compare/v0.9.2...v0.9.3)
## 0.9.2 — 2026-10-28
**Portable Characters are experimental and may contain bugs.**
- New server installation waits for slower database startup.
- Find and edit CoA options in the existing server settings.
- Simultaneous update checks share results or wait their turn.
- Recovery can stop an unfinished world startup after restoring an older launcher.
[Release](https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.2) · [Source changes](https://github.com/Corfirean/coa-server-manager/compare/v0.9.1...v0.9.2)
## 0.9.1 — 2026-10-28
**Portable Characters are experimental and may contain bugs.**
- Existing unsupported character records no longer block unrelated server updates.
[Release](https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.1) · [Source changes](https://github.com/Corfirean/coa-server-manager/compare/v0.9.0...v0.9.1)
## 0.9.0 — 2026-10-28
**Portable Characters are experimental and may contain bugs.**
- Choose Parallel or Global level scaling in module settings.
- Report Content Scaling problems directly to its repository.
- Send custom race problem reports directly to their maintainer.
- Internet sharing restores the LAN address after server restarts.
- Configure custom race availability for new characters.
- Public listing offers every realm that starts together, not just the main one.
- Public listing is a short list of realms with a window for the details.
- Configure profession and defense skill gains in server settings.
- Starting a server sets the character classes of the realm chosen on Overview.
- Start Wildcard and Warcraft Reborn together with Conquest of Azeroth.
- Control portable characters and keep Manager running in the system tray.
[Release](https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.0) · [Source changes](https://github.com/Corfirean/coa-server-manager/compare/v0.8.2...v0.9.0)
## 0.8.2 — 2026-10-27
**Portable Characters are experimental and may contain bugs.**
Generated
+30 -3
View File
@@ -586,7 +586,7 @@ dependencies = [
[[package]]
name = "coa-core"
version = "0.9.0"
version = "0.9.10"
dependencies = [
"base64 0.22.1",
"chrono",
@@ -606,6 +606,7 @@ dependencies = [
"serde_json",
"sha1",
"sha2",
"socket2",
"tar",
"tempfile",
"thiserror 2.0.21",
@@ -618,6 +619,15 @@ dependencies = [
"zstd",
]
[[package]]
name = "coa-launcher"
version = "0.9.10"
dependencies = [
"coa-core",
"serde_json",
"windows-sys 0.60.2",
]
[[package]]
name = "coa-registry-proto"
version = "0.1.0"
@@ -634,7 +644,7 @@ dependencies = [
[[package]]
name = "coa-release"
version = "0.9.0"
version = "0.9.10"
dependencies = [
"chrono",
"coa-core",
@@ -643,7 +653,7 @@ dependencies = [
[[package]]
name = "coa-server-manager"
version = "0.9.0"
version = "0.9.10"
dependencies = [
"coa-control-proto",
"coa-core",
@@ -655,6 +665,7 @@ dependencies = [
"tauri-plugin-dialog",
"tauri-plugin-opener",
"tauri-plugin-process",
"tauri-plugin-single-instance",
"tauri-plugin-updater",
"tracing",
]
@@ -4606,6 +4617,22 @@ dependencies = [
"tauri-plugin",
]
[[package]]
name = "tauri-plugin-single-instance"
version = "2.5.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "726b6da0dd5bd1344f84f4108a622c07d01923baacb5c803a605189672c5352f"
dependencies = [
"serde",
"serde_json",
"tauri",
"thiserror 2.0.21",
"tokio",
"tracing",
"windows-sys 0.61.2",
"zbus",
]
[[package]]
name = "tauri-plugin-updater"
version = "2.13.1"
+2 -2
View File
@@ -1,10 +1,10 @@
[workspace]
resolver = "2"
members = ["crates/coa-core", "crates/coa-release", "crates/coa-registry-proto", "crates/coa-control-proto", "src-tauri"]
members = ["crates/coa-core", "crates/coa-launcher", "crates/coa-release", "crates/coa-registry-proto", "crates/coa-control-proto", "src-tauri"]
exclude = ["services/coa-registry", "services/coa-registry-e2e", "services/coa-coordinator", "services/coa-relay"]
[workspace.package]
version = "0.9.0"
version = "0.9.10"
edition = "2021"
license = "AGPL-3.0-only"
@@ -0,0 +1,7 @@
---
area: manager
type: added
audience: admins
title: Find and edit CoA options in the existing server settings
---
Search includes the separate CoA configuration, including legacy mount flight. Changes go to the correct file; realm profile controls stay managed by the Manager.
@@ -0,0 +1,7 @@
---
area: manager
type: fixed
audience: admins
title: Existing unsupported character records no longer block unrelated server updates
---
Updates compare each affected character with its saved pre-update state. Unchanged older problems are reported as warnings without changing characters. Newly missing race/class data still blocks the update and triggers recovery; schema and identity checks remain enforced.
@@ -0,0 +1,7 @@
---
area: manager
type: fixed
audience: admins
title: Recovery can stop an unfinished world startup after restoring an older launcher
---
If the world console is unavailable, stop only the verified recorded world process. Keep MySQL running if ownership or shutdown cannot be confirmed.
@@ -0,0 +1,7 @@
---
area: manager
type: fixed
audience: admins
title: New server installation waits for slower database startup
---
Allow up to five minutes for MySQL to become ready. Failed installations stop their temporary database before cleaning up its files.
@@ -0,0 +1,7 @@
---
area: manager
type: changed
audience: admins
title: Settings group updates, startup and maintenance with translated release history
---
Server and Manager keep separate update controls. Read their published changes in one place, including translations of the latest releases in all six interface languages. Saved notes remain available offline. Find public realm controls under Play with friends.
@@ -0,0 +1,7 @@
---
area: manager
type: changed
audience: admins
title: Update and launch without updating share a divided button
---
Server and game client actions each use two adjacent segments of equal height. Both actions remain visible and keep their own availability checks.
@@ -0,0 +1,7 @@
---
area: manager
type: fixed
audience: admins
title: Simultaneous update checks share results or wait their turn
---
Repeated checks no longer compete with another foreground or background check in the same Manager window. Maintenance and recovery locks remain enforced.
+7
View File
@@ -0,0 +1,7 @@
---
area: manager
type: fixed
audience: admins
title: Maximizing the window keeps text and controls at a comfortable size
---
The interface no longer enlarges with window width. System display scaling and browser zoom still work, and large action buttons use more compact spacing.
@@ -0,0 +1,7 @@
---
area: manager
type: fixed
audience: admins
title: Slow server startup no longer triggers an early update rollback
---
World startup now allows up to 25 minutes with either bot system and waits for both game and console ports within one deadline. Servers that stop during startup still fail immediately.
@@ -0,0 +1,7 @@
---
area: manager
type: fixed
audience: admins
title: Account creation verifies a lost console reply against the requested login
---
Confirm the requested credentials after a lost reply, block creation during another server action, and explicitly report accounts whose administrator access could not be confirmed.
@@ -0,0 +1,7 @@
---
area: manager
type: fixed
audience: admins
title: Abandoned game relay tunnels close their local connection immediately
---
Dropping a tunnel shuts down its shared socket directly instead of relying only on a background message, releasing its local read and write connection.
@@ -0,0 +1,7 @@
---
area: manager
type: fixed
audience: admins
title: Keep disabled graphics components disabled during client updates
---
Client settings can disable DXVK and graphics enhancements. Existing launcher DISABLED files are respected.
@@ -0,0 +1,7 @@
---
area: manager
type: added
audience: admins
title: Force-stop an unresponsive world after a failed normal shutdown
---
Confirm the risk of unsaved progress before stopping verified server processes. Shared databases stay running until every owned world has stopped.
@@ -0,0 +1,7 @@
---
area: manager
type: fixed
audience: admins
title: Crash history includes reports from every world and Windows text files
---
Create and verify the crash report folder before native startup, and include reports from simultaneous worlds and files containing Windows ANSI text.
@@ -0,0 +1,7 @@
---
area: manager
type: fixed
audience: admins
title: Show the online bot count for Playerbots on the overview
---
The overview displays bot population for both supported bot systems.
@@ -0,0 +1,7 @@
---
area: manager
type: added
audience: admins
title: Disable public server browsing in Settings
---
Turn off public server browsing to block catalog list and detail requests. When browsing is enabled, load the list with Refresh.
@@ -0,0 +1,7 @@
---
area: manager
type: fixed
audience: admins
title: Keep deliberate stops and update shutdowns from triggering crash restart
---
Status checks no longer forget a stop request while the world is still shutting down. Update validation and recovery do not trigger automatic crash restarts.
@@ -0,0 +1,7 @@
---
area: manager
type: fixed
audience: admins
title: Show available update notes even when release history is cached
---
Fetch the release notes for the offered update when they are missing from the cached history, including when an update becomes available while the history is open.
@@ -0,0 +1,7 @@
---
area: manager
type: fixed
audience: admins
title: Server startup waits for a responsive console before reporting success
---
An open port no longer marks a loading world as ready. Account creation checks that the console processes commands before sending a create request.
+7
View File
@@ -0,0 +1,7 @@
---
area: manager
type: fixed
audience: admins
title: Restore the existing Manager window when launching it again
---
Choose whether closing the window exits the Manager or minimizes it to the tray. Tray actions restore the window on the UI thread.
@@ -0,0 +1,7 @@
---
area: manager
type: added
audience: admins
title: Dungeon Clear can be enabled when SQUID bots are active
---
Dungeon Clear starts disabled. Switching SQUID bots off also switches Dungeon Clear off; enabling SQUID again leaves Dungeon Clear off until you choose to enable it.
@@ -0,0 +1,7 @@
---
area: manager
type: added
audience: admins
title: Diagnostic exports include launcher stages and lock owner records
---
Support packages include recent launcher diagnostics for each realm, with sensitive fields removed. Recorded lock owners help diagnose overlapping startup and shutdown actions.
@@ -0,0 +1,7 @@
---
area: manager
type: fixed
audience: admins
title: Custom Races patch installation recovers from interrupted downloads
---
Unfinished downloads resume automatically. Invalid archives in Downloads are skipped without changing them, and damaged cached archives are downloaded again.
@@ -0,0 +1,7 @@
---
area: manager
type: added
audience: admins
title: Choose normal logs, errors only or no server logs in maintenance settings
---
The logging preset updates both the game world and login server, including their configuration templates. Previous settings are saved in configuration snapshots. Restart the server to apply the change.
@@ -0,0 +1,7 @@
---
area: manager
type: fixed
audience: admins
title: Update checks temporarily suspend bot population and restore your configuration
---
Validation preserves the selected bot system and its population limits. Original configuration files are restored after validation, including recovery from interrupted updates.
@@ -0,0 +1,7 @@
---
area: manager
type: fixed
audience: admins
title: Update validation keeps MySQL running between compatible checks
---
Database checks and the temporary server startup share one MySQL session. The server still stops before files or database snapshots are replaced or restored.
@@ -0,0 +1,6 @@
---
area: manager
type: fixed
audience: admins
title: Update and recovery checks use the temporary login port even with a Windows override
---
+192 -1
View File
@@ -123,6 +123,7 @@
"Corfirean/coa-server-manager:20261021-scaling-health-settings.md",
"Corfirean/coa-server-manager:20261021-warcraft-reborn-realm.md",
"Corfirean/coa-server-manager:20261022-custom-races-client.md",
"Corfirean/coa-server-manager:20261022-scaling-progression-modes.md",
"Corfirean/coa-server-manager:20261023-ah-bot-single-switch.md",
"Corfirean/coa-server-manager:20261023-interface-language-coverage.md",
"Corfirean/coa-server-manager:20261023-online-players-exclude-squid-bots.md",
@@ -138,7 +139,44 @@
"Corfirean/coa-server-manager:20261024-remote-refresh.md",
"Corfirean/coa-server-manager:20261025-custom-races-191.md",
"Corfirean/coa-server-manager:20261026-custom-races-192.md",
"Corfirean/coa-server-manager:20261027-merged-database-migration-order.md"
"Corfirean/coa-server-manager:20261027-content-scaling-reports.md",
"Corfirean/coa-server-manager:20261027-custom-races-reports.md",
"Corfirean/coa-server-manager:20261027-internet-lan-address.md",
"Corfirean/coa-server-manager:20261027-merged-database-migration-order.md",
"Corfirean/coa-server-manager:20261027-per-race-server-settings.md",
"Corfirean/coa-server-manager:20261027-public-list-shows-every-running-realm.md",
"Corfirean/coa-server-manager:20261027-public-listing-window.md",
"Corfirean/coa-server-manager:20261027-skill-gain-controls.md",
"Corfirean/coa-server-manager:20261027-start-checks-the-realm-class-setting.md",
"Corfirean/coa-server-manager:20261027-start-wildcard-and-reborn-with-coa.md",
"Corfirean/coa-server-manager:20261028-coa-config-search.md",
"Corfirean/coa-server-manager:20261028-existing-character-update-validation.md",
"Corfirean/coa-server-manager:20261028-legacy-world-shutdown.md",
"Corfirean/coa-server-manager:20261028-mysql-install-startup.md",
"Corfirean/coa-server-manager:20261028-portable-settings-and-tray.md",
"Corfirean/coa-server-manager:20261028-settings-release-history.md",
"Corfirean/coa-server-manager:20261028-split-update-actions.md",
"Corfirean/coa-server-manager:20261028-update-check-queue.md",
"Corfirean/coa-server-manager:20261028-window-density.md",
"Corfirean/coa-server-manager:20261029-slow-world-startup.md",
"Corfirean/coa-server-manager:20261030-account-console-confirmation.md",
"Corfirean/coa-server-manager:20261030-close-abandoned-relay-sockets.md",
"Corfirean/coa-server-manager:20261030-disabled-client-renderers.md",
"Corfirean/coa-server-manager:20261030-force-stop-unresponsive-world.md",
"Corfirean/coa-server-manager:20261030-native-crash-reports.md",
"Corfirean/coa-server-manager:20261030-playerbots-overview-count.md",
"Corfirean/coa-server-manager:20261030-public-server-browsing-control.md",
"Corfirean/coa-server-manager:20261030-stop-does-not-trigger-auto-restart.md",
"Corfirean/coa-server-manager:20261030-update-history-target-cache.md",
"Corfirean/coa-server-manager:20261030-wait-for-world-console-readiness.md",
"Corfirean/coa-server-manager:20261030-window-lifecycle.md",
"Corfirean/coa-server-manager:20261031-dungeon-clear-dependency.md",
"Corfirean/coa-server-manager:20261031-launcher-diagnostics-export.md",
"Corfirean/coa-server-manager:20261031-recover-client-patch-downloads.md",
"Corfirean/coa-server-manager:20261031-server-logging-controls.md",
"Corfirean/coa-server-manager:20261031-validation-bot-population.md",
"Corfirean/coa-server-manager:20261031-validation-mysql-reuse.md",
"Corfirean/coa-server-manager:20261103-isolated-login-port.md"
],
"releases": [
{
@@ -721,6 +759,159 @@
"experimentalFeatures": [
"portable-characters"
]
},
{
"tag": "v0.9.0",
"version": "0.9.0",
"date": "2026-10-28",
"url": "https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.0",
"notes": [
"Choose Parallel or Global level scaling in module settings",
"Report Content Scaling problems directly to its repository",
"Send custom race problem reports directly to their maintainer",
"Internet sharing restores the LAN address after server restarts",
"Configure custom race availability for new characters",
"Public listing offers every realm that starts together, not just the main one",
"Public listing is a short list of realms with a window for the details",
"Configure profession and defense skill gains in server settings",
"Starting a server sets the character classes of the realm chosen on Overview",
"Start Wildcard and Warcraft Reborn together with Conquest of Azeroth",
"Control portable characters and keep Manager running in the system tray"
],
"commit": "dc97095bd6b36d9b5111f04f0cfd88e1fb2ab1f1",
"compare": "https://github.com/Corfirean/coa-server-manager/compare/v0.8.2...v0.9.0",
"experimentalFeatures": [
"portable-characters"
]
},
{
"version": "0.9.1",
"tag": "v0.9.1",
"date": "2026-10-28",
"notes": [
"Existing unsupported character records no longer block unrelated server updates"
],
"experimentalFeatures": [
"portable-characters"
],
"url": "https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.1",
"compare": "https://github.com/Corfirean/coa-server-manager/compare/v0.9.0...v0.9.1",
"commit": "8bbf16ed4f14e9b78c680783e4be5d8c580cc06b"
},
{
"tag": "v0.9.2",
"version": "0.9.2",
"date": "2026-10-28",
"url": "https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.2",
"notes": [
"New server installation waits for slower database startup",
"Find and edit CoA options in the existing server settings",
"Simultaneous update checks share results or wait their turn",
"Recovery can stop an unfinished world startup after restoring an older launcher"
],
"commit": "2d9c6a65bbb1e296dc919e4c9e5785ed9d4a070b",
"compare": "https://github.com/Corfirean/coa-server-manager/compare/v0.9.1...v0.9.2",
"experimentalFeatures": [
"portable-characters"
]
},
{
"tag": "v0.9.3",
"version": "0.9.3",
"date": "2026-10-29",
"url": "https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.3",
"notes": [
"Slow server startup no longer triggers an early update rollback"
],
"commit": "e7b76137d1b22a7596c2b1fa05ca9d12403b99d3",
"compare": "https://github.com/Corfirean/coa-server-manager/compare/v0.9.2...v0.9.3",
"experimentalFeatures": [
"portable-characters"
]
},
{
"tag": "v0.9.4",
"version": "0.9.4",
"date": "2026-10-29",
"url": "https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.4",
"notes": [
"Settings group updates, startup and maintenance with translated release history",
"Update and launch without updating share a divided button",
"Maximizing the window keeps text and controls at a comfortable size"
],
"commit": "c004b90c54fa358b3037c56b093cf019dfcf02b8",
"compare": "https://github.com/Corfirean/coa-server-manager/compare/v0.9.3...v0.9.4",
"experimentalFeatures": [
"portable-characters"
]
},
{
"tag": "v0.9.5",
"version": "0.9.5",
"date": "2026-10-30",
"url": "https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.5",
"notes": [
"Account creation verifies a lost console reply against the requested login",
"Abandoned game relay tunnels close their local connection immediately",
"Keep disabled graphics components disabled during client updates",
"Force-stop an unresponsive world after a failed normal shutdown",
"Crash history includes reports from every world and Windows text files",
"Show the online bot count for Playerbots on the overview",
"Disable public server browsing in Settings",
"Keep deliberate stops and update shutdowns from triggering crash restart",
"Server startup waits for a responsive console before reporting success",
"Restore the existing Manager window when launching it again"
],
"commit": "642da8fdc1a0165aea74fbd1ab1b46933fc7e589",
"compare": "https://github.com/Corfirean/coa-server-manager/compare/v0.9.4...v0.9.5"
},
{
"tag": "v0.9.7",
"version": "0.9.7",
"date": "2026-10-30",
"url": "https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.7",
"notes": [
"Show available update notes even when release history is cached"
],
"commit": "ba5816e3aea471d5b870e5f0db0b03920c071ed3",
"compare": "https://github.com/Corfirean/coa-server-manager/compare/v0.9.5...v0.9.7"
},
{
"tag": "v0.9.8",
"version": "0.9.8",
"date": "2026-11-01",
"url": "https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.8",
"notes": [
"Dungeon Clear can be enabled when SQUID bots are active",
"Diagnostic exports include launcher stages and lock owner records",
"Choose normal logs, errors only or no server logs in maintenance settings",
"Update checks temporarily suspend bot population and restore your configuration",
"Update validation keeps MySQL running between compatible checks"
],
"commit": "076fba185c4d96d74f7258d6ca0cae6a4ae4a613",
"compare": "https://github.com/Corfirean/coa-server-manager/compare/v0.9.7...v0.9.8"
},
{
"tag": "v0.9.9",
"version": "0.9.9",
"date": "2026-11-04",
"url": "https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.9",
"notes": [
"Update and recovery checks use the temporary login port even with a Windows override"
],
"commit": "173248efbe24da9b4c1b5ca12fa7580fcd1e8ea7",
"compare": "https://github.com/Corfirean/coa-server-manager/compare/v0.9.8...v0.9.9"
},
{
"tag": "v0.9.10",
"version": "0.9.10",
"date": "2026-11-08",
"url": "https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.10",
"notes": [
"Custom Races patch installation recovers from interrupted downloads"
],
"commit": "711f378ae82f75d3fc64368c042889c773315c54",
"compare": "https://github.com/Corfirean/coa-server-manager/compare/v0.9.9...v0.9.10"
}
]
}
+2 -1
View File
@@ -5,6 +5,7 @@ edition.workspace = true
license.workspace = true
[dependencies]
socket2 = "0.6"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
sha2 = "0.10"
@@ -37,7 +38,7 @@ rand_core = { version = "0.6", features = ["getrandom"] }
ed25519-dalek = { version = "2", features = ["rand_core"] }
[target.'cfg(windows)'.dependencies]
windows-sys = { version = "0.60", features = ["Win32_Foundation", "Win32_Storage_FileSystem", "Win32_System_Threading", "Win32_System_SystemInformation", "Win32_System_Diagnostics_ToolHelp", "Win32_NetworkManagement_IpHelper", "Win32_Networking_WinSock", "Win32_Security_Cryptography", "Win32_UI_Shell", "Win32_System_Registry", "Win32_UI_WindowsAndMessaging"] }
windows-sys = { version = "0.60", features = ["Win32_Foundation", "Win32_Storage_FileSystem", "Win32_System_Threading", "Win32_System_Console", "Win32_System_SystemInformation", "Win32_System_Diagnostics_ToolHelp", "Win32_NetworkManagement_IpHelper", "Win32_Networking_WinSock", "Win32_Security_Cryptography", "Win32_UI_Shell", "Win32_System_Registry", "Win32_UI_WindowsAndMessaging"] }
[features]
testkit = []
@@ -0,0 +1,154 @@
use coa_core::{
db::{Account, Db},
driver::{self, Verb},
ra::Ra,
Result,
};
use std::path::PathBuf;
fn main() -> Result<()> {
let root = PathBuf::from(std::env::args().nth(1).expect("disposable fixture"));
assert!(root
.file_name()
.unwrap()
.to_string_lossy()
.starts_with("coa-update-recovery-fixture-"));
assert!(root.join("recovery-e2e-started").is_file());
let result = std::panic::catch_unwind(|| -> Result<()> {
let started = driver::run(&root, Verb::StartAll)?;
assert!(started.ok, "{}", started.output);
assert!(root.join("Core/Crashes").is_dir());
let db = Db::from_repack(&root, Account::Admin)?;
println!("Account acceptance: server started, connecting to RA");
let mut ra = Ra::connect(&root)?;
println!("Account acceptance: RA authenticated");
let name = "STABILITYACCT2";
assert_eq!(
db.query("SELECT COUNT(*) FROM acore_auth.account WHERE username='STABILITYACCT2';")?
.trim(),
"0"
);
println!("Account acceptance: sending create command");
coa_core::accounts::create(&root, name, "PrivateTest773", true)?;
println!("Account acceptance: created");
assert_eq!(db.query("SELECT COUNT(*) FROM acore_auth.account WHERE username='STABILITYACCT2' AND LENGTH(salt)=32 AND LENGTH(verifier)=32;")?.trim(), "1");
assert!(ra
.create_account(name, "PrivateTest773")
.unwrap_err()
.to_string()
.contains("already taken"));
ra.set_account_password(name, "PrivateTest774")?;
ra.set_account_access(name, 3)?;
assert_eq!(db.query("SELECT gmlevel FROM acore_auth.account_access WHERE id=(SELECT id FROM acore_auth.account WHERE username='STABILITYACCT2');")?.trim(), "3");
ra.delete_account(name)?;
assert_eq!(
db.query("SELECT COUNT(*) FROM acore_auth.account WHERE username='STABILITYACCT2';")?
.trim(),
"0"
);
lost_reply(&root, &db)?;
println!("PASS: native RA account create, SRP salt/verifier, duplicate refusal, password change, administrator access and deletion");
Ok(())
});
let stopped = driver::run(&root, Verb::StopAll)?;
assert!(stopped.ok, "{}", stopped.output);
result.map_err(|_| {
coa_core::Error::Invalid("Native account acceptance failed; fixture stopped".into())
})?
}
fn lost_reply(root: &std::path::Path, db: &Db) -> Result<()> {
use std::io::{Read, Write};
use std::net::{TcpListener, TcpStream};
let path = root.join("Settings/repack.json");
let original = std::fs::read(&path)?;
struct Restore(std::path::PathBuf, Vec<u8>);
impl Drop for Restore {
fn drop(&mut self) {
std::fs::write(&self.0, &self.1).expect("restore disposable fixture settings");
}
}
let restore = Restore(path.clone(), original.clone());
let actual = coa_core::layout::read_ports(root).ra;
for (name, forward, ready) in [
("STABLOSTREPLY", true, true),
("STABNOTCREATED", false, true),
("STABNOTREADY", false, false),
] {
assert_eq!(
db.query(&format!(
"SELECT COUNT(*) FROM acore_auth.account WHERE username='{name}';"
))?
.trim(),
"0"
);
let listener = TcpListener::bind(("127.0.0.1", 0))?;
let mut config: serde_json::Value = serde_json::from_slice(&original)?;
config["raPort"] = listener.local_addr()?.port().into();
coa_core::fsx::atomic_write_json(&path, &config)?;
let proxy = std::thread::spawn(move || {
fn until(s: &mut TcpStream, marker: &[u8]) -> Vec<u8> {
s.set_read_timeout(Some(std::time::Duration::from_secs(30)))
.unwrap();
let mut bytes = Vec::new();
let mut byte = [0];
while !bytes.ends_with(marker) {
s.read_exact(&mut byte).unwrap();
bytes.push(byte[0]);
}
bytes
}
let (mut client, _) = listener.accept().unwrap();
let mut server = TcpStream::connect(("127.0.0.1", actual)).unwrap();
for marker in [b"Username: ".as_slice(), b"Password: ".as_slice()] {
client.write_all(&until(&mut server, marker)).unwrap();
server.write_all(&until(&mut client, b"\r\n")).unwrap();
}
client.write_all(&until(&mut server, b"AC>")).unwrap();
let readiness = until(&mut client, b"\r\n");
assert_eq!(readiness, b"server info\r\n");
if !ready {
return;
}
server.write_all(&readiness).unwrap();
client.write_all(&until(&mut server, b"AC>")).unwrap();
let command = until(&mut client, b"\r\n");
if forward {
server.write_all(&command).unwrap();
let _ = until(&mut server, b"AC>");
}
});
let outcome = coa_core::accounts::create(root, name, "PrivateTest773", false);
proxy.join().unwrap();
std::fs::write(&path, &original)?;
if forward {
outcome?;
assert_eq!(
db.query(&format!(
"SELECT COUNT(*) FROM acore_auth.account WHERE username='{name}';"
))?
.trim(),
"1"
);
assert!(coa_core::accounts::create(root, name, "DifferentPass77", false).is_err());
Ra::connect(root)?.delete_account(name)?;
} else {
assert!(outcome.is_err());
if !ready {
assert!(outcome
.unwrap_err()
.to_string()
.contains("No create command was sent"));
}
assert_eq!(
db.query(&format!(
"SELECT COUNT(*) FROM acore_auth.account WHERE username='{name}';"
))?
.trim(),
"0"
);
}
}
drop(restore);
println!("PASS: a lost native console reply is reconciled by exact SRP credentials; a command that was never executed is rejected");
Ok(())
}
@@ -0,0 +1,11 @@
use coa_core::{crashes, Result};
fn main()->Result<()> {
let root=std::path::PathBuf::from(std::env::args().nth(1).expect("marked native fixture"));
assert!(root.join("recovery-e2e-started").is_file());
let reports=crashes::list(&root,30)?;
let matching:Vec<_>=reports.iter().filter(|r|r.full_log.contains("AllowableRaces")).collect();
assert!(!matching.is_empty());
assert!(matching.iter().all(|r|r.exception_code.as_deref()==Some("C0000420")));
println!("PASS: Manager discovered {} actual worldserver SQL assertion reports from Core/Crashes, including Windows ANSI text",matching.len());
Ok(())
}
@@ -0,0 +1,91 @@
use coa_core::{
db::{Account, Db},
driver::{self, Verb},
ra::Ra,
Result,
};
use std::{
path::PathBuf,
time::{Duration, Instant},
};
fn main() -> Result<()> {
let root = PathBuf::from(
std::env::args()
.nth(1)
.expect("disposable recovery fixture"),
);
assert!(root
.file_name()
.unwrap()
.to_string_lossy()
.starts_with("coa-update-recovery-fixture-"));
assert!(root.join("recovery-e2e-started").is_file());
let result = std::panic::catch_unwind(|| -> Result<()> {
let start = driver::run(&root, Verb::StartAll)?;
assert!(start.ok, "{}", start.output);
let db = Db::from_repack(&root, Account::Admin)?;
coa_core::companions::ensure_templates(&db)?;
let mut ra = Ra::connect(&root)?;
let before = coa_core::population::query(&root)?;
assert_eq!(before.bots_online, 0);
let rejected = db.query("SELECT name, at_login FROM acore_characters.characters WHERE guid=3030 AND account IN (SELECT id FROM acore_auth.account WHERE username LIKE 'COABOTHOST%');")?;
assert!(rejected.contains("Christian Shadowheart"));
assert_eq!(rejected.split_whitespace().last(), Some("1"));
println!("Repair reply: {}", ra.run("botcmd spawnbot 3030")?);
let repair_deadline = Instant::now() + Duration::from_secs(60);
loop {
let row = db.query(
"SELECT name, at_login, online FROM acore_characters.characters WHERE guid=3030;",
)?;
if row.trim().ends_with("0\t1") {
assert!(!row.contains("Christian Shadowheart"));
println!("PASS: the exact previously rejected companion was renamed by server validation and logged in");
break;
}
assert!(
Instant::now() < repair_deadline,
"previously rejected companion logged in"
);
std::thread::sleep(Duration::from_secs(1));
}
let _ = ra.despawn_all()?;
let clear_deadline = Instant::now() + Duration::from_secs(30);
while coa_core::population::query(&root)?.bots_online > 0 {
assert!(Instant::now() < clear_deadline);
std::thread::sleep(Duration::from_secs(1));
}
println!("Spawn reply: {}", ra.spawn_bots(21)?);
let deadline = Instant::now() + Duration::from_secs(180);
loop {
let pop = coa_core::population::query(&root)?;
if pop.bots_online >= 21 {
println!(
"PASS: {} companions logged in; real players={}",
pop.bots_online, pop.players_online
);
break;
}
if Instant::now() > deadline {
return Err(coa_core::Error::Invalid(format!(
"Only {} of 21 companion logins completed",
pop.bots_online
)));
}
std::thread::sleep(Duration::from_secs(2));
}
let _ = ra.cancel_spawning()?;
let _ = ra.despawn_all()?;
let deadline = Instant::now() + Duration::from_secs(30);
while coa_core::population::query(&root)?.bots_online > 0 {
assert!(Instant::now() < deadline, "companions despawned");
std::thread::sleep(Duration::from_secs(1));
}
println!("PASS: companion despawn completed");
Ok(())
});
let stopped = driver::run(&root, Verb::StopAll)?;
assert!(stopped.ok, "{}", stopped.output);
result.map_err(|_| {
coa_core::Error::Invalid("Companion native acceptance panicked; fixture stopped".into())
})?
}
@@ -0,0 +1,12 @@
use coa_core::{crashes, Result};
fn main() -> Result<()> {
let root = std::path::PathBuf::from(std::env::args().nth(1).expect("native crash evidence"));
assert!(root.join(".crash-report-evidence").is_file());
let reports = crashes::list(&root, 10)?;
assert_eq!(reports.len(), 1);
assert_eq!(reports[0].exception_code.as_deref(), Some("C0000005"));
assert_eq!(reports[0].category, "access_violation");
assert!(!reports[0].full_log.is_empty());
println!("PASS: Manager crash history discovers and classifies the actual native handler report from Core/Crashes");
Ok(())
}
@@ -0,0 +1,90 @@
use coa_core::{driver, fsx, process, Result};
#[cfg(windows)]
use std::os::windows::process::CommandExt;
use std::{
path::Path,
process::{Child, Command, Stdio},
};
struct OwnedChild(Child);
impl Drop for OwnedChild {
fn drop(&mut self) {
let _ = self.0.kill();
let _ = self.0.wait();
}
}
fn copy_tree(source: &Path, target: &Path) -> Result<()> {
std::fs::create_dir_all(target)?;
for entry in std::fs::read_dir(source)? {
let entry = entry?;
let destination = target.join(entry.file_name());
if entry.file_type()?.is_dir() {
copy_tree(&entry.path(), &destination)?;
} else {
std::fs::copy(entry.path(), destination)?;
}
}
Ok(())
}
fn spawn(path: &Path) -> OwnedChild {
let mut cmd = Command::new(path);
cmd.args(["-t", "127.0.0.1"])
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null());
#[cfg(windows)]
cmd.creation_flags(0x0800_0000);
OwnedChild(cmd.spawn().unwrap())
}
fn main() -> Result<()> {
assert!(cfg!(windows));
let source = std::path::PathBuf::from(
std::env::args()
.nth(1)
.expect("marked disposable runtime source"),
);
assert_eq!(
std::fs::read(source.join(".release-schema-fixture"))?,
b"disposable release-schema fixture"
);
let temp = tempfile::tempdir()?;
let root = temp.path();
copy_tree(&source.join("Runtime"), &root.join("Runtime"))?;
std::fs::create_dir_all(root.join("Core"))?;
std::fs::create_dir_all(root.join("Scripts"))?;
let system =
std::path::PathBuf::from(std::env::var_os("SystemRoot").unwrap()).join("System32/ping.exe");
std::fs::copy(&system, root.join("Core/worldserver.exe"))?;
std::fs::copy(&system, root.join("foreign.exe"))?;
let mut ports = Vec::new();
let mut listeners = Vec::new();
for _ in 0..4 {
let listener = std::net::TcpListener::bind("127.0.0.1:0")?;
ports.push(listener.local_addr()?.port());
listeners.push(listener);
}
let config = serde_json::json!({"mysqlPort":ports[0],"authPort":ports[1],"worldPort":ports[2],"raPort":ports[3],"raUsername":"fixture","raPassword":"fixture"});
fsx::atomic_write_json(&root.join("Settings/repack.json"), &config)?;
drop(listeners);
let mut launcher = std::fs::read_to_string(source.join("Scripts/manage.py"))?;
launcher.push_str("\nfrom contextlib import nullcontext\ndef control_lock(): return nullcontext()\ndef stop_all(config):\n assert not process('world'), 'world must stop before database'\n (ROOT/'database-stage').write_text('safe')\n");
fsx::atomic_write(&root.join("Scripts/manage.py"), launcher.as_bytes())?;
let mut foreign = spawn(&root.join("foreign.exe"));
let foreign_identity = process::identity(foreign.0.id()).unwrap();
fsx::atomic_write_json(&root.join(".state/world.json"), &foreign_identity)?;
let rejected = driver::force_stop(root)?;
assert!(!rejected.ok, "a foreign world record must be rejected");
assert!(!root.join("database-stage").exists());
assert!(foreign.0.try_wait()?.is_none());
let mut owned = spawn(&root.join("Core/worldserver.exe"));
let stopped = driver::force_stop(root)?;
assert!(stopped.ok, "{}", stopped.output);
assert!(owned.0.try_wait()?.is_some());
assert!(
foreign.0.try_wait()?.is_none(),
"foreign process was untouched"
);
assert_eq!(std::fs::read(root.join("database-stage"))?, b"safe");
println!("PASS: native Windows forced-stop rejects foreign records, recovers the exact owned world identity, stops it before the database stage, and leaves the foreign process alive");
Ok(())
}
+114
View File
@@ -0,0 +1,114 @@
//! The Rust launcher on a DISPOSABLE repack, side by side with Scripts/manage.py:
//!
//! 1. install the stable server into a new folder on unused ports;
//! 2. coa-launcher start-all, then manage.py status-json must see every service;
//! 3. manage.py stop-all stops what coa-launcher started;
//! 4. manage.py start-all, coa-launcher status-json sees it, coa-launcher stop-all stops it;
//! 5. both stop-alls leave nothing of the repack running.
//!
//! usage: launcher_e2e <new folder ending in -fixture> <coa-launcher.exe>
use std::path::Path;
use std::process::Command;
use coa_core::install::{install_base, Params};
use coa_core::registry::Registry;
fn free_port() -> u16 {
std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port()
}
fn run(exe: &Path, args: &[&str]) -> (bool, String) {
let out = Command::new(exe).args(args).output().unwrap();
let text = String::from_utf8_lossy(&out.stdout).into_owned() + &String::from_utf8_lossy(&out.stderr);
(out.status.success(), text)
}
fn launcher(root: &Path, exe: &Path, action: &str) -> (bool, String) {
let r = root.to_string_lossy().into_owned();
let t = std::time::Instant::now();
let out = run(exe, &["--root", &r, action]);
println!("[coa-launcher {action}] ok={} in {:?}\n{}", out.0, t.elapsed(), indent(&out.1));
out
}
fn manage(root: &Path, action: &str) -> (bool, String) {
let python = root.join("Runtime/python/python.exe");
let script = root.join("Scripts/manage.py").to_string_lossy().into_owned();
let t = std::time::Instant::now();
let out = run(&python, &["-B", &script, action]);
println!("[manage.py {action}] ok={} in {:?}\n{}", out.0, t.elapsed(), indent(&out.1));
out
}
fn indent(s: &str) -> String {
s.lines().map(|l| format!(" {l}")).collect::<Vec<_>>().join("\n")
}
fn status(out: &str) -> serde_json::Value {
let line = out.lines().rev().find(|l| l.trim_start().starts_with('{')).expect("a JSON status line");
serde_json::from_str(line).unwrap()
}
fn all(v: &serde_json::Value, running: bool) -> bool {
["mysql", "auth", "world", "relay"].iter().all(|k| v[*k] == running)
}
fn main() {
let a: Vec<String> = std::env::args().skip(1).collect();
let root = Path::new(&a[0]);
let exe = Path::new(&a[1]);
assert!(a[0].ends_with("-fixture"), "a folder ending in -fixture is required");
if root.join("Core/worldserver.exe").is_file() {
println!("reusing the installed fixture");
} else {
install(root);
}
test(root, exe);
}
fn install(root: &Path) {
assert!(!root.exists(), "a new folder is required");
let reg_dir = std::env::temp_dir().join("coa-launcher-e2e-registry");
let _ = std::fs::remove_dir_all(&reg_dir);
let reg = Registry::at(reg_dir.join("installs.json"));
// what the Manager installs: the stable release's installation image
let image = coa_core::install::Source::Installation(Box::new(coa_core::channels::resolve("stable").expect("stable channel")));
let installed = install_base(
&Params { source: image, dest: root.into(), trusted_key: coa_core::signing::EMBEDDED_PUBLIC_KEY, registry: &reg, cancel: Default::default() },
&|s| eprintln!(" {:>3}% {}", s.percent, s.step),
)
.expect("install");
println!("installed {}", installed.version);
let repack = root.join("Settings/repack.json");
let mut cfg: serde_json::Value = serde_json::from_slice(&std::fs::read(&repack).unwrap()).unwrap();
for k in ["mysqlPort", "authPort", "worldPort", "raPort"] {
cfg[k] = free_port().into();
}
std::fs::write(&repack, serde_json::to_vec_pretty(&cfg).unwrap()).unwrap();
}
fn test(root: &Path, exe: &Path) {
// 2. Rust starts, Python sees it
assert!(launcher(root, exe, "start-all").0, "coa-launcher start-all");
let seen = status(&manage(root, "status-json").1);
assert!(all(&seen, true), "manage.py must see the services coa-launcher started: {seen}");
// 3. Python stops what Rust started
assert!(manage(root, "stop-all").0, "manage.py stop-all");
assert!(all(&status(&launcher(root, exe, "status-json").1), false));
// 4. Python starts, Rust sees and stops it
assert!(manage(root, "start-all").0, "manage.py start-all");
let seen = status(&launcher(root, exe, "status-json").1);
assert!(all(&seen, true), "coa-launcher must see the services manage.py started: {seen}");
assert!(launcher(root, exe, "stop-all").0, "coa-launcher stop-all");
assert!(all(&status(&manage(root, "status-json").1), false));
// 5. Rust alone, a second time (start on a server it stopped)
assert!(launcher(root, exe, "start-all").0);
assert!(launcher(root, exe, "stop-all").0);
let left = coa_core::process::find_by_exe(&root.join("mysql/bin/mysqld.exe")).len()
+ coa_core::process::find_by_exe(&root.join("Core/worldserver.exe")).len()
+ coa_core::process::find_by_exe(&root.join("Core/authserver.exe")).len();
assert_eq!(left, 0, "nothing of the repack may be left running");
println!("LAUNCHER E2E PASS");
}
@@ -0,0 +1,199 @@
use base64::{engine::general_purpose::STANDARD, Engine};
use coa_core::{
backup,
db::Db,
driver::{self, Verb},
fsx,
manifest::{Kind, Migration},
package::{self, BuildOptions},
pkgsource::Source,
registry::MetaDir,
update::{self, RepackEnv},
Result,
};
use ed25519_dalek::{Signer, SigningKey};
use std::{collections::BTreeMap, path::PathBuf};
fn main() -> Result<()> {
let root = PathBuf::from(
std::env::args()
.nth(1)
.expect("qualified disposable fixture"),
);
let sql = std::fs::read(std::env::args().nth(2).expect("corrective SQL"))?;
assert_eq!(
root.file_name().unwrap(),
"coa-schema-fixture-stability-upgrade-76-85-20261030"
);
assert!(root.join(".release-schema-fixture").is_file());
assert!(!root.join("legacy-start-data-e2e-started").exists());
fsx::atomic_write(
&root.join("legacy-start-data-e2e-started"),
b"disposable regression test",
)?;
let result = std::panic::catch_unwind(|| -> Result<()> {
let meta = coa_core::registry::metadata_dir_for(&root)?;
let mut identities = String::new();
let mut custom = String::new();
backup::with_database(&root, |db| {
assert_eq!(
db.query(
"SELECT COUNT(*) FROM acore_world.playercreateinfo WHERE race IN (33,45);"
)?
.trim(),
"0"
);
let base: u32 = db
.query("SELECT MAX(guid)+100 FROM acore_characters.characters;")?
.trim()
.parse()
.unwrap();
clone_character(db, base, 33, 12, "Thinprobe")?;
clone_character(db, base + 1, 45, 30, "Leperprobe")?;
identities = db.query(&format!(
"SELECT * FROM acore_characters.characters WHERE guid IN ({base},{});",
base + 1
))?;
let missing = coa_core::character_start_check::missing(db)?;
assert!(missing
.iter()
.any(|c| c.guid == base && c.race == 33 && c.class == 12));
assert!(missing
.iter()
.any(|c| c.guid == base + 1 && c.race == 45 && c.class == 30));
db.query("INSERT INTO acore_world.playercreateinfo SELECT 33,class,map,zone,position_x+0.125,position_y,position_z,orientation FROM acore_world.playercreateinfo WHERE race=1 AND class=32;")?;
custom =
db.query("SELECT * FROM acore_world.playercreateinfo WHERE race=33 AND class=32;")?;
fsx::atomic_write(
&root.join("legacy-probe-guids.json"),
serde_json::to_string(&[base, base + 1])?.as_bytes(),
)?;
println!("PASS: reproduced missing starting data for existing race 33/class 12 and race 45/class 30 characters");
Ok(())
})?;
let source = root.join("legacy-start-data-source");
let pkg = root.join("legacy-start-data-package");
fsx::atomic_write(
&source.join("Core/legacy-start-data-proof.txt"),
b"corrective migration acceptance",
)?;
fsx::atomic_write(
&source.join("_migrations/world/stabilization_legacy_starts.sql"),
&sql,
)?;
let manifest = package::build(
&source,
&pkg,
&BuildOptions {
kind: Kind::Update,
version: "2.0.0".into(),
core_commit: None,
bots_commit: None,
built_at: "private regression acceptance".into(),
part_size: 1 << 20,
migrations: vec![Migration {
id: "stabilization_legacy_starts".into(),
db: "world".into(),
sha256: fsx::sha256_bytes(&sql),
compatible_sha256: vec![],
destructive: false,
}],
},
&|_| {},
)?;
let key = SigningKey::generate(&mut rand_core::OsRng);
fsx::atomic_write(
&pkg.join("manifest.json.sig"),
STANDARD
.encode(
key.sign(&std::fs::read(pkg.join("manifest.json"))?)
.to_bytes(),
)
.as_bytes(),
)?;
let trusted = STANDARD.encode(key.verifying_key().to_bytes());
let env = RepackEnv {
root: &root,
meta_dir: &meta,
};
let out = update::apply(
&update::Params {
root: &root,
meta_dir: &meta,
source: Source::Dir(pkg),
trusted_key: &trusted,
cancel: Default::default(),
resolutions: BTreeMap::new(),
env: &env,
fail_after_ops: None,
},
&|step, pct| println!("{pct}% {step}"),
)?;
assert_eq!(out.txn.state, update::State::Committed);
assert_eq!(
MetaDir::open(&meta)?.1.core.version.as_deref(),
Some("2.0.0")
);
backup::with_database(&root, |db| {
let guids: Vec<u32> =
serde_json::from_slice(&std::fs::read(root.join("legacy-probe-guids.json"))?)?;
assert_eq!(
db.query(&format!(
"SELECT * FROM acore_characters.characters WHERE guid IN ({},{});",
guids[0], guids[1]
))?,
identities
);
assert!(coa_core::character_start_check::missing(db)?
.iter()
.all(|c| !guids.contains(&c.guid)));
assert_eq!(
db.query("SELECT * FROM acore_world.playercreateinfo WHERE race=33 AND class=32;")?,
custom
);
assert!(coa_core::migrations::status(db, &manifest.migrations)?
.iter()
.all(|m| m.status == coa_core::migrations::Status::Applied));
let before = counts(db)?;
db.query(&format!(
"USE acore_world; {}",
String::from_utf8_lossy(&sql)
))?;
assert_eq!(counts(db)?, before);
assert_eq!(
db.query("SELECT * FROM acore_world.playercreateinfo WHERE race=33 AND class=32;")?,
custom
);
println!("PASS: signed Manager update restored legacy starts, preserved complete character rows and custom starts, and remained idempotent on a second SQL execution");
Ok(())
})?;
Ok(())
});
let stopped = driver::run(&root, Verb::StopAll)?;
assert!(stopped.ok, "{}", stopped.output);
result.map_err(|_| {
coa_core::Error::Invalid("Legacy start regression failed; fixture stopped".into())
})?
}
fn counts(db: &Db) -> Result<String> {
db.query("SELECT COUNT(*) FROM acore_world.playercreateinfo WHERE race IN (33,45); SELECT COUNT(*) FROM acore_world.playercreateinfo_item WHERE race IN (33,45); SELECT COUNT(*) FROM acore_world.playercreateinfo_action WHERE race IN (33,45); SELECT COUNT(*) FROM acore_world.player_race_stats WHERE Race IN (33,45); SELECT COUNT(*) FROM acore_world.ascension_custom_class_race WHERE race IN (33,45);")
}
fn clone_character(db: &Db, guid: u32, race: u32, class: u32, name: &str) -> Result<()> {
let columns = db.query("SHOW COLUMNS FROM acore_characters.characters;")?;
let names: Vec<_> = columns
.lines()
.map(|l| l.split('\t').next().unwrap())
.collect();
let values: Vec<String> = names
.iter()
.map(|c| match *c {
"guid" => guid.to_string(),
"name" => format!("'{name}'"),
"race" => race.to_string(),
"class" => class.to_string(),
"online" | "at_login" => "0".into(),
_ => format!("`{c}`"),
})
.collect();
db.query(&format!("INSERT INTO acore_characters.characters ({}) SELECT {} FROM acore_characters.characters WHERE class={class} LIMIT 1;",names.iter().map(|c|format!("`{c}`")).collect::<Vec<_>>().join(","),values.join(",")))?;
Ok(())
}
@@ -0,0 +1,149 @@
//! The Manager's start/stop (`driver`) on the Rust launcher, on a DISPOSABLE repack:
//!
//! 1. driver start-all: every service runs, the console answers, manage.py is not touched and sees the services;
//! 2. driver stop-all stops everything;
//! 3. manage.py start-all, then driver stop-all stops what Python started;
//! 4. a taken world port fails with the typed "port in use" code (no stderr parsing), then stop-all;
//! 5. driver start-all, then the forced stop;
//! 6. with a realm profile: the realm row gets the profile's name, manage.py is still not edited;
//! 7. nothing of the repack is left running.
//!
//! usage: manager_launcher_e2e <existing folder ending in -fixture>
use std::path::Path;
use std::process::Command;
use std::time::Instant;
use coa_core::driver::{self, Verb};
use coa_core::error::ErrorCode;
use coa_core::launcher::{services, settings::Settings, state};
fn indent(s: &str) -> String {
s.lines().map(|l| format!(" {l}")).collect::<Vec<_>>().join("\n")
}
fn drive(root: &Path, verb: Verb) -> driver::DriverOutcome {
let t = Instant::now();
let out = driver::run(root, verb).expect("driver");
println!("[driver {verb:?}] ok={} code={:?} in {:?}\n{}", out.ok, out.code, t.elapsed(), indent(&out.output));
out
}
fn manage(root: &Path, action: &str) -> (bool, String) {
let python = root.join("Runtime/python/python.exe");
let script = root.join("Scripts/manage.py").to_string_lossy().into_owned();
let t = Instant::now();
let out = Command::new(python).args(["-B", &script, action]).output().unwrap();
let text = String::from_utf8_lossy(&out.stdout).into_owned() + &String::from_utf8_lossy(&out.stderr);
println!("[manage.py {action}] ok={} in {:?}\n{}", out.status.success(), t.elapsed(), indent(&text));
(out.status.success(), text)
}
fn python_status(root: &Path) -> serde_json::Value {
let (ok, out) = manage(root, "status-json");
assert!(ok);
let line = out.lines().rev().find(|l| l.trim_start().starts_with('{')).expect("a JSON status line");
serde_json::from_str(line).unwrap()
}
fn all(v: &serde_json::Value, running: bool) -> bool {
["mysql", "auth", "world", "relay"].iter().all(|k| v[*k] == running)
}
fn nothing_running(root: &Path) -> bool {
["mysql", "auth", "world", "supervisor", "relay"].iter().all(|n| state::running(root, n).is_none())
&& ["mysql/bin/mysqld.exe", "Core/authserver.exe", "Core/worldserver.exe"]
.iter()
.all(|exe| coa_core::process::find_by_exe(&root.join(exe)).is_empty())
}
fn console(root: &Path) -> String {
let cfg = Settings::load(root, 0).unwrap();
let mut ra = coa_core::ra::Ra::connect_to(cfg.ra_port, &cfg.ra_username, &cfg.ra_password).unwrap();
ra.run("server info").unwrap()
}
fn realm_name(root: &Path) -> String {
services::mysql(root, Some("SELECT name FROM acore_auth.realmlist WHERE id=1;"), None).unwrap()
}
fn main() {
let a: Vec<String> = std::env::args().skip(1).collect();
let root = Path::new(&a[0]);
assert!(a[0].ends_with("-fixture"), "a folder ending in -fixture is required");
assert!(nothing_running(root), "the fixture must be stopped before the test");
let manage_py = root.join("Scripts/manage.py");
let original = std::fs::read(&manage_py).unwrap();
let profile = root.join("Settings/realm-profile.json");
assert!(!profile.exists(), "the fixture starts without a realm profile");
// 1
let started = drive(root, Verb::StartAll);
assert!(started.ok, "start-all");
assert!(all(&python_status(root), true), "manage.py sees what the Manager started");
let info = console(root);
println!("[console] {}", info.lines().next().unwrap_or(""));
assert_eq!(std::fs::read(&manage_py).unwrap(), original, "manage.py is not rewritten");
assert_eq!(realm_name(root), "AzerothCore", "no profile: the launcher's own realm name");
let shipped = root.join("Scripts/coa-launcher.exe");
let supervisor = state::running(root, "supervisor").expect("a supervisor");
println!("[supervisor] {}", supervisor.exe);
let expected = if shipped.is_file() { "coa-launcher.exe" } else { "python.exe" };
assert!(supervisor.exe.to_lowercase().ends_with(expected), "the world is supervised by {expected}");
let relay = state::running(root, "relay").expect("a bug-report relay");
println!("[relay] {}", relay.exe);
assert!(relay.exe.to_lowercase().ends_with(expected), "the relay is run by {expected}");
assert!(state::running(root, "relay-ready").is_some_and(|r| r.pid == relay.pid), "the relay reported ready");
// 2
assert!(drive(root, Verb::StopAll).ok, "stop-all");
assert!(nothing_running(root), "1-2 left something running");
// 2b: the repack's Python launcher stops a world the Manager started
assert!(drive(root, Verb::StartAll).ok);
assert!(manage(root, "stop-all").0, "manage.py stops what the Manager started");
assert!(nothing_running(root), "2b left something running");
// 3
assert!(manage(root, "start-all").0);
assert!(drive(root, Verb::StopAll).ok, "driver stops what manage.py started");
assert!(nothing_running(root), "3 left something running");
// 4
let cfg = Settings::load(root, 0).unwrap();
let blocker = std::net::TcpListener::bind(("127.0.0.1", cfg.world_port)).unwrap();
let refused = drive(root, Verb::StartAll);
assert!(!refused.ok);
assert_eq!(refused.code, Some(ErrorCode::PortInUse), "typed port error");
assert!(refused.output.contains(&format!("Port {}", cfg.world_port)));
drop(blocker);
assert!(drive(root, Verb::StopAll).ok);
assert!(nothing_running(root), "4 left something running");
// 5
assert!(drive(root, Verb::StartAll).ok);
let t = Instant::now();
let forced = driver::force_stop(root).expect("force stop");
println!("[driver force_stop] ok={} in {:?}\n{}", forced.ok, t.elapsed(), indent(&forced.output));
assert!(forced.ok && forced.output.contains("Force-stopped"));
assert!(nothing_running(root), "5 left something running");
// 6
std::fs::write(&profile, br#"{"active":"coa","wildcard_created":false}"#).unwrap();
let result = std::panic::catch_unwind(|| {
assert!(drive(root, Verb::StartAll).ok, "start-all with a realm profile");
assert_eq!(realm_name(root), "Conquest of Azeroth");
assert_eq!(std::fs::read(&manage_py).unwrap(), original, "manage.py is not edited for a realm profile either");
assert!(drive(root, Verb::StopAll).ok);
});
std::fs::remove_file(&profile).unwrap();
std::fs::write(&manage_py, &original).unwrap();
if result.is_err() {
let _ = driver::run(root, Verb::StopAll);
panic!("step 6 failed");
}
// 7
assert!(nothing_running(root), "something of the repack is still running");
println!("PASS: the Manager starts and stops through the Rust launcher, interoperates with manage.py, typed errors");
}
@@ -0,0 +1,170 @@
//! The Rust bug-report relay against the repack's `BugReport/relay.py`, offline (a scripted service, no network):
//!
//! 1. the same reports and the same service answers give the same `.status` files and journal rows;
//! 2. each relay continues the other's journal: what one delivered is never sent again by the other, and a post the
//! other left in progress is uncertain.
//!
//! usage: relay_equivalence <repack folder with Runtime/python and BugReport/relay.py>
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::{Arc, Mutex};
use coa_core::launcher::relay::{Failure, Relay, Service};
const REPORTS: [(&str, &str); 5] = [
("1-00000000000000a1", "COABUG1\r\nQuest broken\r\nThe NPC is gone.\r\n"),
("9-00000000000000b2", "COABUG1\nRate limited\nBody text\n"),
("3-00000000000000c3", "COABUG1\nRejected\nBody\n"),
("4-00000000000000d4", "COABUG1\nxy\nTitle too short\n"),
("5-00000000000000e5", "COABUG1\nUnknown outcome\nBody\n"),
];
/// The answers per title, in the vocabulary of both relays.
fn answer(title: &str) -> std::result::Result<u64, Failure> {
match title {
"Quest broken" => Ok(101),
"Rate limited" => Err(Failure::Limited(60)),
"Rejected" => Err(Failure::Invalid),
_ => Err(Failure::Uncertain),
}
}
const PYTHON: &str = r#"
import importlib.util, sys, json
from pathlib import Path
spec = importlib.util.spec_from_file_location("relay", sys.argv[1]); relay = importlib.util.module_from_spec(spec); spec.loader.exec_module(relay)
spool = Path(sys.argv[2]); calls = []
class Fake:
def create(self, title, body):
calls.append(title)
if title == "Quest broken": return 101
if title == "Rate limited": raise relay.DeliveryError("limited", 60)
if title == "Rejected": raise relay.DeliveryError("invalid")
raise relay.DeliveryError("uncertain")
t = [float(sys.argv[3])]
def clock():
t[0] += 3
return t[0]
r = relay.Relay(spool, Fake(), clock=clock)
for path in sorted(spool.glob("*.report")):
r.process(path)
r.close()
print(json.dumps(calls))
"#;
struct Scripted(Arc<Mutex<Vec<String>>>);
impl Service for Scripted {
fn create(&self, title: &str, _: &str) -> std::result::Result<u64, Failure> {
self.0.lock().unwrap().push(title.into());
answer(title)
}
}
fn spool(dir: &Path) -> PathBuf {
std::fs::create_dir_all(dir).unwrap();
for (key, text) in REPORTS {
std::fs::write(dir.join(format!("{key}.report")), text).unwrap();
}
dir.into()
}
fn python(repack: &Path, spool: &Path, start: f64) -> Vec<String> {
let out = Command::new(repack.join("Runtime/python/python.exe"))
.args(["-I", "-B", "-c", PYTHON])
.arg(repack.join("BugReport/relay.py"))
.arg(spool)
.arg(start.to_string())
.output()
.unwrap();
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
serde_json::from_slice(&out.stdout).unwrap()
}
/// The clock of both relays: `start`, then 3 seconds later at every reading.
fn rust(spool: &Path, start: f64) -> Vec<String> {
let calls = Arc::new(Mutex::new(Vec::new()));
let t = Mutex::new(start);
let clock = move || {
let mut v = t.lock().unwrap();
*v += 3.0;
*v
};
let relay = Relay::with_clock(spool, Scripted(calls.clone()), Box::new(clock)).unwrap();
relay.pass().unwrap();
drop(relay);
let c = calls.lock().unwrap().clone();
c
}
/// `.status` files and journal rows (without the post time).
fn snapshot(spool: &Path) -> (Vec<(String, String)>, Vec<String>) {
let mut statuses: Vec<(String, String)> = std::fs::read_dir(spool)
.unwrap()
.flatten()
.filter(|e| e.path().extension().is_some_and(|x| x == "status"))
.map(|e| (e.file_name().to_string_lossy().into_owned(), std::fs::read_to_string(e.path()).unwrap()))
.collect();
statuses.sort();
let db = rusqlite::Connection::open(spool.join("relay.sqlite3")).unwrap();
let mut q = db.prepare("SELECT key, digest, marker, state, number, next_try FROM deliveries ORDER BY key").unwrap();
let rows = q
.query_map([], |r| {
Ok(format!(
"{}|{}|{}|{}|{:?}|{}",
r.get::<_, String>(0)?,
r.get::<_, String>(1)?,
r.get::<_, String>(2)?,
r.get::<_, String>(3)?,
r.get::<_, Option<i64>>(4)?,
r.get::<_, f64>(5)?
))
})
.unwrap()
.map(Result::unwrap)
.collect();
(statuses, rows)
}
fn main() {
let repack = PathBuf::from(std::env::args().nth(1).expect("repack folder"));
let work = tempfile::tempdir().unwrap();
// 1
let (a, b) = (spool(&work.path().join("python")), spool(&work.path().join("rust")));
let py_calls = python(&repack, &a, 1000.0);
let rs_calls = rust(&b, 1000.0);
println!("python posted {py_calls:?}\nrust posted {rs_calls:?}");
assert_eq!(py_calls, rs_calls, "the same reports are posted");
let (pa, pb) = (snapshot(&a), snapshot(&b));
for s in &pa.0 {
println!(" {} = {}", s.0, s.1.trim());
}
assert_eq!(pa, pb, "the same statuses and journal");
// 2: each continues the other's journal. Before the retry times nothing is sent again; after them only the
// rate-limited report is (created, rejected and uncertain ones never are).
assert!(python(&repack, &b, 1000.0).is_empty(), "Python does not resend what Rust handled");
assert!(rust(&a, 1000.0).is_empty(), "Rust does not resend what Python handled");
// Later passes: the queued reports go out, a refused or uncertain one never again.
for start in [5000.0, 6000.0, 7000.0] {
let (p, r) = (python(&repack, &b, start), rust(&a, start));
println!("at {start}: python on rust's journal posted {p:?}, rust on python's posted {r:?}");
assert_eq!(p, r, "the same retries");
assert!(!p.iter().any(|t| t == "Quest broken" || t == "Unknown outcome"), "created and uncertain are final");
}
assert_eq!(snapshot(&a), snapshot(&b), "the same after a retry by the other relay");
for dir in [&a, &b] {
let db = rusqlite::Connection::open(dir.join("relay.sqlite3")).unwrap();
db.execute("UPDATE deliveries SET state='posting' WHERE key='9-00000000000000b2'", []).unwrap();
}
python(&repack, &b, 9000.0);
rust(&a, 9000.0);
for dir in [&a, &b] {
let db = rusqlite::Connection::open(dir.join("relay.sqlite3")).unwrap();
let state: String = db.query_row("SELECT state FROM deliveries WHERE key='9-00000000000000b2'", [], |r| r.get(0)).unwrap();
assert_eq!(state, "uncertain", "an interrupted post is not retried ({})", dir.display());
}
assert_eq!(snapshot(&a), snapshot(&b), "still the same after the crossover");
println!("PASS: relay journals, statuses and posts are the same in Python and Rust");
}
@@ -0,0 +1,103 @@
//! SQUID database provisioning in Rust gives exactly what Scripts/squid_playerbots.py gives, on a DISPOSABLE repack:
//! the same journals (coa_squid_migrations, coa_squid_pending) in every schema, the same acore_playerbots tables
//! with the same row counts, the same playerbots.conf. Each side starts from the same state (SQUID never
//! provisioned), and a second run of each must change nothing.
//!
//! usage: squid_equivalence <fixture ending in -fixture> <coa-launcher.exe>
use std::path::Path;
use std::process::Command;
use coa_core::launcher::{services, squid};
fn sql(root: &Path, q: &str) -> String {
services::mysql(root, Some(q), None).unwrap_or_else(|e| panic!("{q}: {e}"))
}
/// What provisioning leaves behind, comparable between runs.
fn snapshot(root: &Path) -> String {
let mut out = Vec::new();
for schema in ["acore_characters", "acore_world", "acore_playerbots"] {
let tables = sql(root, &format!("SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_SCHEMA='{schema}' ORDER BY TABLE_NAME;"));
for t in tables.lines() {
if schema != "acore_playerbots" && !t.starts_with("coa_squid") {
continue;
}
let n = sql(root, &format!("SELECT COUNT(*) FROM `{schema}`.`{t}`;"));
out.push(format!("{schema}.{t} rows={n}"));
if t == "coa_squid_migrations" || t == "coa_squid_pending" {
for row in sql(root, &format!("SELECT path, sha256 FROM `{schema}`.`{t}` ORDER BY path;")).lines() {
out.push(format!(" {row}"));
}
}
}
}
let conf = std::fs::read_to_string(root.join("Core/configs/modules/playerbots.conf")).unwrap();
out.push(format!("playerbots.conf:\n{}", conf.replace("\r\n", "\n")));
out.join("\n")
}
fn reset(root: &Path, conf: &[u8]) {
sql(root, "DROP DATABASE IF EXISTS acore_playerbots;");
for schema in ["acore_characters", "acore_world"] {
sql(root, &format!("DROP TABLE IF EXISTS `{schema}`.coa_squid_migrations, `{schema}`.coa_squid_pending;"));
}
std::fs::write(root.join("Core/configs/modules/playerbots.conf"), conf).unwrap();
}
fn python(root: &Path) {
let harness = root.join(".state/squid_harness.py");
std::fs::write(
&harness,
"import sys, pathlib\nroot = pathlib.Path(sys.argv[1])\nsys.path.insert(0, str(root / 'Scripts'))\nsys.argv = ['manage.py']\nimport manage\nfrom squid_playerbots import prepare_playerbots\nprepare_playerbots(manage.ROOT, manage.settings(), manage.mysql)\n",
)
.unwrap();
let out = Command::new(root.join("Runtime/python/python.exe")).arg("-B").arg(&harness).arg(root).output().unwrap();
assert!(out.status.success(), "python: {}{}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr));
print!("{}", String::from_utf8_lossy(&out.stdout));
}
fn rust(root: &Path) {
let cfg = coa_core::launcher::Settings::load(root, 0).unwrap();
squid::prepare_playerbots(root, cfg.mysql_port, &|q| services::mysql(root, Some(q), None), &|m| println!("{m}")).unwrap();
}
fn main() {
let a: Vec<String> = std::env::args().skip(1).collect();
let root = Path::new(&a[0]);
let exe = Path::new(&a[1]);
assert!(a[0].ends_with("-fixture"));
let modules = root.join("Core/configs/modules");
// SQUID on, Companions off
let companions = std::fs::read_to_string(modules.join("mod_coa_playerbots.conf")).unwrap();
std::fs::write(modules.join("mod_coa_playerbots.conf"), companions.replace("CoaBots.Enable = 1", "CoaBots.Enable = 0")).unwrap();
let squid_conf = std::fs::read_to_string(modules.join("playerbots.conf")).unwrap().replace("AiPlayerbot.Enabled = 0", "AiPlayerbot.Enabled = 1");
let r = root.to_string_lossy().into_owned();
let started = Command::new(exe).args(["--root", &r, "start-mysql"]).output().unwrap();
assert!(started.status.success(), "{}", String::from_utf8_lossy(&started.stderr));
reset(root, squid_conf.as_bytes());
let t = std::time::Instant::now();
python(root);
println!("python provisioned in {:?}", t.elapsed());
let by_python = snapshot(root);
python(root);
assert_eq!(snapshot(root), by_python, "a second Python run changed something");
reset(root, squid_conf.as_bytes());
let t = std::time::Instant::now();
rust(root);
println!("rust provisioned in {:?}", t.elapsed());
let by_rust = snapshot(root);
rust(root);
assert_eq!(snapshot(root), by_rust, "a second Rust run changed something");
if by_python != by_rust {
std::fs::write(root.join(".state/squid-python.txt"), &by_python).unwrap();
std::fs::write(root.join(".state/squid-rust.txt"), &by_rust).unwrap();
panic!("Rust and Python differ: see .state/squid-python.txt and squid-rust.txt");
}
println!("{} lines of journal/table/config state are identical", by_rust.lines().count());
let stopped = Command::new(exe).args(["--root", &r, "stop-all"]).output().unwrap();
assert!(stopped.status.success());
println!("SQUID EQUIVALENCE PASS");
}
@@ -0,0 +1,8 @@
use coa_core::{backup, schema_check, Result};
fn main()->Result<()> {
let root=std::path::PathBuf::from(std::env::args().nth(1).unwrap());
let contract=std::path::PathBuf::from(std::env::args().nth(2).unwrap());
assert!(root.join("recovery-e2e-started").is_file());
assert!(contract.join(".release-schema-fixture").is_file());
backup::with_database(&root,|db| {for p in schema_check::check(db,&contract)? {println!("{}.{}.{}: {}",p.database,p.table,p.column,p.detail);} Ok(())})
}
@@ -0,0 +1,132 @@
use base64::{engine::general_purpose::STANDARD, Engine};
use coa_core::{
backup,
driver::{self, Verb},
fsx,
manifest::{Kind, Migration},
package::{self, BuildOptions},
pkgsource::Source,
update::{self, RepackEnv},
Result,
};
use ed25519_dalek::{Signer, SigningKey};
use std::{collections::BTreeMap, path::PathBuf};
fn main() -> Result<()> {
let root = PathBuf::from(std::env::args().nth(1).unwrap());
let core = PathBuf::from(std::env::args().nth(2).unwrap());
let release = PathBuf::from(std::env::args().nth(3).unwrap());
assert!(root.join("recovery-e2e-started").is_file());
let result = std::panic::catch_unwind(|| -> Result<()> {
let meta = coa_core::registry::metadata_dir_for(&root)?;
let source = root.join("schema-sync-source-v2");
let pkg = root.join("schema-sync-package-v2");
assert!(!pkg.exists());
fsx::atomic_write(
&source.join("Core/schema-sync-proof.txt"),
b"official schema migration acceptance",
)?;
let published =
coa_core::manifest::Manifest::parse(&std::fs::read(release.join("manifest.json"))?)?;
let contract_path = PathBuf::from("C:/games/source/coa-schema-fixture-stability-upgrade-76-85-20261030/Scripts/database-schema.json");
let contract = std::fs::read(contract_path)?;
let expected = published
.files
.iter()
.find(|f| f.path == "Scripts/database-schema.json")
.unwrap();
assert_eq!(fsx::sha256_bytes(&contract), expected.sha256);
fsx::atomic_write(&source.join("Scripts/database-schema.json"), &contract)?;
let mut migrations: Vec<Migration> = Vec::new();
for id in [
"rev_1793212891571528600",
"rev_20261027_18_coa_strange_piece_of_scrap_faction_diamond",
] {
let m = published
.migrations
.iter()
.find(|m| m.id == id)
.unwrap()
.clone();
let sql = std::fs::read(
core.join(format!("data/sql/updates/pending_db_{}/{}.sql", m.db, m.id)),
)?;
assert_eq!(fsx::sha256_bytes(&sql), m.sha256);
fsx::atomic_write(
&source.join(format!("_migrations/{}/{}.sql", m.db, m.id)),
&sql,
)?;
migrations.push(m);
}
package::build(
&source,
&pkg,
&BuildOptions {
kind: Kind::Update,
version: "3.0.0".into(),
core_commit: None,
bots_commit: None,
built_at: "private native fixture schema sync".into(),
part_size: 1 << 20,
migrations,
},
&|_| {},
)?;
let key = SigningKey::generate(&mut rand_core::OsRng);
fsx::atomic_write(
&pkg.join("manifest.json.sig"),
STANDARD
.encode(
key.sign(&std::fs::read(pkg.join("manifest.json"))?)
.to_bytes(),
)
.as_bytes(),
)?;
let trusted = STANDARD.encode(key.verifying_key().to_bytes());
let env = RepackEnv {
root: &root,
meta_dir: &meta,
};
let out = update::apply(
&update::Params {
root: &root,
meta_dir: &meta,
source: Source::Dir(pkg),
trusted_key: &trusted,
cancel: Default::default(),
resolutions: BTreeMap::from([(
"Scripts/database-schema.json".into(),
update::Resolution::Replace,
)]),
env: &env,
fail_after_ops: None,
},
&|step, pct| println!("{pct}% {step}"),
)?;
assert_eq!(out.txn.state, update::State::Committed);
backup::with_database(&root, |db| {
assert_eq!(
db.query("SELECT name,at_login FROM acore_characters.characters WHERE guid=3030;")?
.trim(),
"Christian Shadowheart\t1"
);
assert_eq!(
db.query("SELECT id FROM acore_characters.manager_recovery_probe;")?
.trim(),
"42"
);
assert_eq!(
db.query("SELECT id FROM acore_world.manager_recovery_probe;")?
.trim(),
"44"
);
Ok(())
})?;
println!("PASS: the exact two published migrations brought the old fixture schema forward through the Manager updater while preserving the rejected companion and recovery probes");
Ok(())
});
let stop = driver::run(&root, Verb::StopAll)?;
assert!(stop.ok, "{}", stop.output);
result.map_err(|_| {
coa_core::Error::Invalid("Schema sync acceptance failed; fixture stopped".into())
})?
}
@@ -0,0 +1,166 @@
use base64::{engine::general_purpose::STANDARD, Engine};
use coa_core::{
backup, driver, fsx,
manifest::{Kind, Migration},
package::{self, BuildOptions},
pkgsource::Source,
registry::MetaDir,
update::{self, RepackEnv},
Result,
};
use ed25519_dalek::{Signer, SigningKey};
use std::{collections::BTreeMap, path::PathBuf};
fn main() -> Result<()> {
let root = PathBuf::from(
std::env::args()
.nth(1)
.expect("disposable recovery fixture"),
);
assert!(root
.file_name()
.unwrap()
.to_string_lossy()
.starts_with("coa-update-recovery-fixture-"));
assert!(root.join("recovery-e2e-started").is_file());
let cycles_only = std::env::args().nth(2).as_deref() == Some("--cycles-only");
if !cycles_only {
assert!(!root.join("success-e2e-started").exists());
fsx::atomic_write(
&root.join("success-e2e-started"),
b"disposable success acceptance",
)?;
}
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
if cycles_only {
restart_cycles(&root)
} else {
exercise(&root)
}
}));
assert!(
driver::run(&root, driver::Verb::StopAll)?.ok,
"fixture shutdown"
);
result.map_err(|_| {
coa_core::Error::Invalid(
"Success acceptance assertion failed; fixture services stopped".into(),
)
})?
}
fn exercise(root: &std::path::Path) -> Result<()> {
let meta = coa_core::registry::metadata_dir_for(root)?;
assert!(update::unfinished(&meta).is_none());
assert!(driver::run(root, driver::Verb::StopAll)?.ok);
let source = root.join("success-source");
let pkg = root.join("success-package");
fsx::atomic_write(
&source.join("Core/stabilization-success.txt"),
b"verified update",
)?;
let sql = b"UPDATE manager_recovery_probe SET id=44 WHERE id=43;";
fsx::atomic_write(
&source.join("_migrations/world/stabilization_success.sql"),
sql,
)?;
let manifest = package::build(
&source,
&pkg,
&BuildOptions {
kind: Kind::Update,
version: "2.0.0".into(),
core_commit: None,
bots_commit: None,
built_at: "disposable acceptance".into(),
part_size: 1 << 20,
migrations: vec![Migration {
id: "stabilization_success".into(),
db: "world".into(),
sha256: fsx::sha256_bytes(sql),
compatible_sha256: vec![],
destructive: false,
}],
},
&|_| {},
)?;
let key = SigningKey::generate(&mut rand_core::OsRng);
fsx::atomic_write(
&pkg.join("manifest.json.sig"),
STANDARD
.encode(
key.sign(&std::fs::read(pkg.join("manifest.json"))?)
.to_bytes(),
)
.as_bytes(),
)?;
let trusted = STANDARD.encode(key.verifying_key().to_bytes());
let env = RepackEnv {
root,
meta_dir: &meta,
};
let outcome = update::apply(
&update::Params {
root,
meta_dir: &meta,
source: Source::Dir(pkg),
trusted_key: &trusted,
cancel: Default::default(),
resolutions: BTreeMap::new(),
env: &env,
fail_after_ops: None,
},
&|step, pct| println!("{pct}% {step}"),
)?;
assert_eq!(outcome.txn.state, update::State::Committed);
assert_eq!(
MetaDir::open(&meta)?.1.core.version.as_deref(),
Some("2.0.0")
);
assert!(update::unfinished(&meta).is_none());
assert_eq!(
std::fs::read(root.join("Core/stabilization-success.txt"))?,
b"verified update"
);
backup::with_database(root, |db| {
assert_eq!(
db.query("SELECT id FROM acore_characters.manager_recovery_probe;")?,
"42"
);
assert_eq!(
db.query("SELECT id FROM acore_characters.manager_recovery_view;")?,
"42"
);
assert_eq!(
db.query("SELECT id FROM acore_world.manager_recovery_probe;")?,
"44"
);
assert!(coa_core::migrations::status(db, &manifest.migrations)?
.iter()
.all(|m| m.status == coa_core::migrations::Status::Applied));
Ok(())
})?;
restart_cycles(root)?;
println!("PASS: signed update committed after failed rehearsal and recovery; SQL, files, metadata and player data verified; two native restart cycles passed");
Ok(())
}
fn restart_cycles(root: &std::path::Path) -> Result<()> {
for cycle in 0..2 {
let stopped = driver::run(root, driver::Verb::StopAll)?;
assert!(
stopped.ok,
"Stop cycle {cycle}: {}",
coa_core::diag::redact(&stopped.output)
);
let started = driver::run(root, driver::Verb::StartAll)?;
assert!(started.ok, "{}", started.output);
let pop = coa_core::population::query(root)?;
println!(
"Restart cycle {cycle}: world ready, players={}, bots={}",
pop.players_online, pop.bots_online
);
}
println!("PASS: two native restart cycles finished");
Ok(())
}
+32 -11
View File
@@ -30,15 +30,27 @@ fn main() -> Result<()> {
.unwrap()
.to_string_lossy()
.starts_with("coa-update-recovery-fixture-"));
assert!(
!root.join("recovery-e2e-started").exists(),
"Use a new fixture; never reuse an owned server"
);
fsx::atomic_write(&root.join("recovery-e2e-started"), b"disposable fixture")?;
let result = exercise(&root);
let stopped = driver::run(&root, Verb::StopAll)?;
assert!(stopped.ok);
result
let resume = std::env::args().nth(2).as_deref() == Some("--verify-recovered");
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
if resume {
assert!(root.join("recovery-e2e-started").is_file());
let manifest = coa_core::manifest::Manifest::parse(&std::fs::read(
root.join("fixture-package/manifest.json"),
)?)?;
verify_recovered(&root, &manifest)
} else {
assert!(
!root.join("recovery-e2e-started").exists(),
"Use a new fixture"
);
fsx::atomic_write(&root.join("recovery-e2e-started"), b"disposable fixture")?;
exercise(&root)
}
}));
assert!(driver::run(&root, Verb::StopAll)?.ok);
result.map_err(|_| {
Error::Invalid("Recovery acceptance assertion failed; owned services were stopped".into())
})?
}
fn exercise(root: &Path) -> Result<()> {
@@ -122,9 +134,18 @@ fn exercise(root: &Path) -> Result<()> {
assert!(
error
.to_string()
.contains("private update rehearsal failed"),
.contains("files and databases were restored to the recovery point"),
"{error}"
);
verify_recovered(root, &manifest)
}
fn verify_recovered(root: &Path, manifest: &coa_core::manifest::Manifest) -> Result<()> {
let meta = coa_core::registry::metadata_dir_for(root)?;
let env = RepackEnv {
root,
meta_dir: &meta,
};
assert!(!root.join("Core/recovery-probe.txt").exists());
assert!(update::unfinished(&meta).is_none());
assert_eq!(
@@ -168,6 +189,6 @@ fn exercise(root: &Path) -> Result<()> {
Db::from_repack(root, Account::Admin)?.realm(),
coa_core::realms::Mode::Coa
);
println!("PASS: private rehearsal caught failed SQL before changing the installed world, characters, ledger, objects, files or version; complete recovery succeeded");
println!("PASS: failed SQL was rolled back; characters, world, ledger, views, triggers, routines, files and version were verified; the saved recovery point was restored again");
Ok(())
}
+67
View File
@@ -80,6 +80,60 @@ fn upper(name: &str) -> Result<String> {
Ok(name.to_ascii_uppercase())
}
pub fn create(root: &Path, name: &str, password: &str, administrator: bool) -> Result<()> {
validate_account(name, password)?;
let name = name.to_ascii_uppercase();
let db = Db::from_repack(root, Account::Admin)?;
if db
.query(&format!(
"SELECT COUNT(*) FROM acore_auth.account WHERE username='{name}';"
))?
.trim()
!= "0"
{
return Err(Error::Invalid("That account name is already taken.".into()));
}
let mut ra = Ra::connect(root)?;
ra.performance().map_err(|error| Error::Invalid(format!("The server console is not ready for account creation. No create command was sent. {error}")))?;
let confirmed = ra.create_account(&name, password);
if let Err(error) = confirmed {
let stored = db.query(&format!(
"SELECT HEX(salt), HEX(verifier) FROM acore_auth.account WHERE username='{name}';"
))?;
if !matches_credentials(&stored, &name, password) {
return Err(Error::Invalid(format!("Account creation was not confirmed. Refresh the account list before retrying. {error}")));
}
if administrator {
ra = Ra::connect(root).map_err(|error| Error::Invalid(format!("The account was created, but administrator access was not confirmed. Refresh the account list and check its access level. {error}")))?;
}
}
if administrator {
if let Err(error) = ra.make_administrator(&name) {
let access = db.query(&format!("SELECT COUNT(*) FROM acore_auth.account_access WHERE id=(SELECT id FROM acore_auth.account WHERE username='{name}') AND gmlevel=3 AND RealmID=-1;"))?;
if access.trim() != "1" {
return Err(Error::Invalid(format!("The account was created, but administrator access was not confirmed. Refresh the account list and check its access level. {error}")));
}
}
}
Ok(())
}
fn matches_credentials(stored: &str, name: &str, password: &str) -> bool {
let Some((salt, verifier)) = stored.trim().split_once('\t') else {
return false;
};
let Ok(salt) = hex::decode(salt) else {
return false;
};
let Ok(salt): std::result::Result<[u8; 32], _> = salt.try_into() else {
return false;
};
let Ok(verifier) = hex::decode(verifier) else {
return false;
};
verifier.as_slice() == crate::srp6::verifier(name, password, &salt)
}
/// Give the account a new name. Needs the world console (the new password is what makes the login work again) and an
/// account that is not logged in. The old name is put back if anything goes wrong.
pub fn rename(root: &Path, ra: &mut Ra, old: &str, new: &str, password: &str) -> Result<()> {
@@ -165,6 +219,19 @@ pub fn delete(root: &Path, ra: &mut Ra, name: &str) -> Result<()> {
mod tests {
use super::*;
#[test]
fn lost_reply_requires_the_exact_requested_credentials() {
let salt = [42; 32];
let verifier = crate::srp6::verifier("NewPlayer", "Password77", &salt);
let stored = format!("{}\t{}\n", hex::encode(salt), hex::encode(verifier));
assert!(matches_credentials(&stored, "NEWPLAYER", "password77"));
assert!(!matches_credentials(&stored, "NEWPLAYER", "wrongpass"));
assert!(!matches_credentials(&stored, "OTHERPLAYER", "Password77"));
for value in ["", "NULL\tNULL", "00\t00", "malformed"] {
assert!(!matches_credentials(value, "NewPlayer", "Password77"));
}
}
#[test]
fn rows_from_the_client_become_accounts() {
let out = "2\tALICE\t3\t0\t2026-09-30 21:04:11\t4\n5\tBOB\t0\t1\t\t0\n7\tBROKEN\n";
+220 -48
View File
@@ -1,5 +1,5 @@
//! Every setting of the world server's configuration, for people who want more than the curated list: the documented
//! settings come from `worldserver.conf.dist` (the file that ships with the server and explains each one), the current
//! settings come from `worldserver.conf.dist` and `modules/coa.conf.dist`, the current
//! values from the configuration the next start will use. Anything that holds a password, a port, an address, a folder or
//! the database connection is left out; the Manager owns those.
@@ -10,7 +10,7 @@ use std::path::Path;
use serde::Serialize;
use crate::config::parser::ConfFile;
use crate::config::{take_snapshot, targets, Scope};
use crate::config::{take_snapshot, targets, Scope, Targets};
use crate::error::{Error, Result};
use crate::fsx;
@@ -39,6 +39,14 @@ fn hidden(key: &str) -> bool {
|| k.starts_with("logindatabase.")
|| k.starts_with("worlddatabase.")
|| k.starts_with("characterdatabase.")
|| [
"coa.classmodel",
"coa.realmtype",
"coa.gamemodemask",
"coa.mapclass10towarrior",
"coa.clientbooleanconfigs",
]
.contains(&k.as_str())
|| [
"bindip",
"realmid",
@@ -121,52 +129,85 @@ fn dist_path(root: &Path) -> std::path::PathBuf {
root.join("Core/configs/worldserver.conf.dist")
}
fn sources(root: &Path) -> Result<Vec<(std::path::PathBuf, Targets)>> {
let mut result = vec![(dist_path(root), targets(root, Scope::Server)?)];
let dist = root.join("Core/configs/modules/coa.conf.dist");
if dist.is_file() {
let active = root.join("Core/configs/modules/coa.conf");
result.push((
dist,
Targets {
read: active.clone(),
writes: vec![active],
generated: None,
},
));
}
Ok(result)
}
pub fn list(root: &Path) -> Result<Vec<Item>> {
let dist = fs::read_to_string(dist_path(root)).map_err(|_| {
Error::Invalid(
"The documented settings file (worldserver.conf.dist) was not found on this server."
.into(),
)
})?;
let t = targets(root, Scope::Server)?;
let active = ConfFile::parse_bytes(&fs::read(&t.read)?)?;
Ok(parse_dist(&dist)
.into_iter()
.filter(|(k, _, _)| !hidden(k))
.map(|(key, default, doc)| {
let value = active
.get(&key)
.map(|v| v.trim().to_string())
.unwrap_or_else(|| default.clone());
let changed = value != default;
Item {
key,
value,
default,
doc,
changed,
}
})
.collect())
let mut items = Vec::new();
for (dist_path, t) in sources(root)? {
let dist = fs::read_to_string(&dist_path)?;
let active = ConfFile::parse_bytes(&if t.read.exists() {
fs::read(&t.read)?
} else {
dist.as_bytes().to_vec()
})?;
items.extend(
parse_dist(&dist)
.into_iter()
.filter(|(k, _, _)| !hidden(k))
.map(|(key, default, doc)| {
let value = active
.get(&key)
.map(|v| v.trim().to_string())
.unwrap_or_else(|| default.clone());
let changed = value != default;
Item {
key,
value,
default,
doc,
changed,
}
})
.collect::<Vec<_>>(),
);
}
Ok(items)
}
/// Change settings that exist in the documented file. A value is one line of at most 500 characters. Returns the keys
/// that actually changed; the previous files are snapshotted first (and can be restored from Settings).
pub fn save(root: &Path, meta: &Path, changes: &BTreeMap<String, String>) -> Result<Vec<String>> {
let known: BTreeMap<String, String> =
parse_dist(&fs::read_to_string(dist_path(root)).map_err(|_| {
Error::Invalid("worldserver.conf.dist was not found on this server.".into())
})?)
.into_iter()
.map(|(k, d, _)| (k, d))
.collect();
let t = targets(root, Scope::Server)?;
let _lock = crate::update::operation_lock(meta)?;
crate::update::ensure_recovered(meta)?;
let sources = sources(root)?;
let mut known = BTreeMap::new();
let mut originals: Vec<(std::path::PathBuf, Vec<u8>)> = Vec::new();
let mut confs: Vec<ConfFile> = Vec::new();
for p in &t.writes {
let bytes = fs::read(p)?;
confs.push(ConfFile::parse_bytes(&bytes)?);
originals.push((p.clone(), bytes));
let mut owners = Vec::new();
for (index, (dist, t)) in sources.iter().enumerate() {
let defaults = fs::read(dist)?;
for (key, default, _) in parse_dist(&String::from_utf8_lossy(&defaults)) {
if known.insert(key.clone(), (default, index)).is_some() {
return Err(Error::Invalid(format!(
"{key} is documented in more than one configuration file."
)));
}
}
for p in &t.writes {
let bytes = if p.exists() {
fs::read(p)?
} else {
defaults.clone()
};
confs.push(ConfFile::parse_bytes(&bytes)?);
originals.push((p.clone(), bytes));
owners.push(index);
}
}
let mut changed = Vec::new();
for (key, value) in changes {
@@ -181,10 +222,22 @@ pub fn save(root: &Path, meta: &Path, changes: &BTreeMap<String, String>) -> Res
"The value of {key} must be one line of text."
)));
}
let same = confs.iter().all(|c| match c.get(key) {
Some(v) => v.trim() == value,
None => known[key] == value,
});
let (default, owner) = &known[key];
if default.parse::<f64>().is_ok() && !value.parse::<f64>().is_ok_and(f64::is_finite)
|| key == "CoA.LegacyMountFlight" && !matches!(value, "0" | "1")
{
return Err(Error::Invalid(format!(
"The value of {key} must be a number matching its documented default."
)));
}
let same = confs
.iter()
.zip(&owners)
.filter(|(_, index)| *index == owner)
.all(|(c, _)| match c.get(key) {
Some(v) => v.trim() == value,
None => default == value,
});
if !same {
changed.push((key.clone(), value.to_string()));
}
@@ -192,20 +245,31 @@ pub fn save(root: &Path, meta: &Path, changes: &BTreeMap<String, String>) -> Res
if changed.is_empty() {
return Ok(Vec::new());
}
for c in &mut confs {
for (c, owner) in confs.iter_mut().zip(&owners) {
for (k, v) in &changed {
c.set(k, v, &["Added by CoA Server Manager"]);
if known[k].1 == *owner {
c.set(k, v, &["Added by CoA Server Manager"]);
}
}
}
let texts: Vec<String> = confs.iter().map(ConfFile::to_text).collect();
for text in &texts {
for (text, owner) in texts.iter().zip(&owners) {
let reread = ConfFile::parse(text);
for (k, v) in &changed {
if reread.get(k).map(str::trim) != Some(v.as_str()) {
if known[k].1 == *owner && reread.get(k).map(str::trim) != Some(v.as_str()) {
return Err(Error::Invalid(format!("internal check failed for {k}")));
}
}
}
let affected: std::collections::BTreeSet<_> =
changed.iter().map(|(key, _)| known[key].1).collect();
let (originals, texts): (Vec<_>, Vec<_>) = originals
.into_iter()
.zip(texts)
.zip(owners)
.filter(|(_, owner)| affected.contains(owner))
.map(|(pair, _)| pair)
.unzip();
take_snapshot(
meta,
Scope::Server,
@@ -232,6 +296,114 @@ pub fn save(root: &Path, meta: &Path, changes: &BTreeMap<String, String>) -> Res
mod tests {
use super::*;
#[test]
fn unrelated_saves_do_not_create_coa_files_and_existing_realm_values_are_preserved() {
let d = tempfile::tempdir().unwrap();
let (root, meta) = server(d.path());
let module = root.join("Core/configs/modules");
fs::create_dir_all(&module).unwrap();
fs::write(
module.join("coa.conf.dist"),
"CoA.LegacyMountFlight = 0\nCoA.ClassModel = \"coa\"\n",
)
.unwrap();
save(
&root,
&meta,
&BTreeMap::from([("Rate.Drop.Item.Rare".into(), "1.5".into())]),
)
.unwrap();
assert!(!module.join("coa.conf").exists());
fs::write(
module.join("coa.conf"),
"# Reborn realm\nCoA.ClassModel = \"wcr\"\nCustom.Preserved = 42\n",
)
.unwrap();
assert!(save(
&root,
&meta,
&BTreeMap::from([("CoA.ClassModel".into(), "\"coa\"".into())])
)
.is_err());
save(
&root,
&meta,
&BTreeMap::from([("CoA.LegacyMountFlight".into(), "1".into())]),
)
.unwrap();
let actual = fs::read_to_string(module.join("coa.conf")).unwrap();
assert!(
actual.contains("CoA.ClassModel = \"wcr\"") && actual.contains("Custom.Preserved = 42")
);
assert!(actual.contains("# Reborn realm"));
}
#[test]
fn coa_settings_are_found_saved_to_the_module_and_snapshotted_without_profile_overrides() {
let d = tempfile::tempdir().unwrap();
let (root, meta) = server(d.path());
let module = root.join("Core/configs/modules");
fs::create_dir_all(&module).unwrap();
let defaults = "[worldserver]\n# Mount flight rules\nCoA.LegacyMountFlight = 0\nCoA.ClassModel = \"coa\"\nCoA.RealmType = \"live\"\n";
fs::write(module.join("coa.conf.dist"), defaults).unwrap();
let original_world = fs::read(root.join("Core/configs/worldserver.conf")).unwrap();
let items = list(&root).unwrap();
assert!(items
.iter()
.any(|i| i.key == "CoA.LegacyMountFlight" && i.value == "0"));
assert!(!items
.iter()
.any(|i| i.key == "CoA.ClassModel" || i.key == "CoA.RealmType"));
for value in ["2", "invalid", "1\nInjected = 1"] {
assert!(save(
&root,
&meta,
&BTreeMap::from([("CoA.LegacyMountFlight".into(), value.into())])
)
.is_err());
}
assert!(!module.join("coa.conf").exists());
save(
&root,
&meta,
&BTreeMap::from([
("CoA.LegacyMountFlight".into(), "1".into()),
("Rate.Drop.Item.Rare".into(), "1.5".into()),
]),
)
.unwrap();
assert!(fs::read_to_string(module.join("coa.conf"))
.unwrap()
.contains("CoA.LegacyMountFlight = 1"));
let world = fs::read_to_string(root.join("Core/configs/worldserver.conf")).unwrap();
assert!(!world.contains("CoA.LegacyMountFlight"));
assert!(world.contains("Rate.Drop.Item.Rare = 1.5"));
assert!(!String::from_utf8(original_world)
.unwrap()
.contains("CoA.LegacyMountFlight"));
assert_eq!(
list(&root)
.unwrap()
.iter()
.find(|i| i.key == "CoA.LegacyMountFlight")
.unwrap()
.value,
"1"
);
assert!(!crate::config::list_snapshots(&meta).is_empty());
let saved = crate::config::list_snapshots(&meta).remove(0);
crate::config::restore_snapshot(&meta, &saved.id).unwrap();
assert_eq!(
list(&root)
.unwrap()
.iter()
.find(|i| i.key == "CoA.LegacyMountFlight")
.unwrap()
.value,
"0"
);
}
const DIST: &str = "[worldserver]\r\n\r\n###################\r\n# SECTION\r\n###################\r\n\r\n#\r\n# Rate.Drop.Item.Epic\r\n# Rate.Drop.Item.Rare\r\n# Description: Drop rates by quality.\r\n# Default: 1\r\n#\r\n\r\nRate.Drop.Item.Rare = 1\r\nRate.Drop.Item.Epic = 1\r\n\r\n#\r\n# LoginDatabaseInfo\r\n# Description: secret\r\n#\r\n\r\nLoginDatabaseInfo = \"127.0.0.1;3306;a;b;c\"\r\n\r\n#\r\n# Instance.ResetTimeHour\r\n# Description: Hour of the reset.\r\n# Important: Use 0-23.\r\n# Default: 4\r\n#\r\n\r\nInstance.ResetTimeHour = 4\r\n";
fn server(d: &Path) -> (std::path::PathBuf, std::path::PathBuf) {
@@ -0,0 +1,124 @@
//! Update-only comparison of existing unsupported character starts. Never repairs or deletes rows.
use crate::{db::Db, Error, Result};
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet};
use std::path::Path;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct MissingStart {
pub guid: u32,
pub race: u32,
pub class: u32,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Baseline {
pub schema: u32,
pub realms: BTreeMap<String, BTreeSet<MissingStart>>,
}
pub fn parse_missing(text: &str) -> Result<BTreeSet<MissingStart>> {
text.lines()
.map(|line| {
let values = line
.split('\t')
.map(str::parse::<u32>)
.collect::<std::result::Result<Vec<_>, _>>()
.map_err(|_| {
Error::Invalid("Cannot read existing character start identities.".into())
})?;
if values.len() != 3 {
return Err(Error::Invalid(
"Incomplete character start identity.".into(),
));
}
Ok(MissingStart {
guid: values[0],
race: values[1],
class: values[2],
})
})
.collect()
}
pub fn missing(db: &Db) -> Result<BTreeSet<MissingStart>> {
parse_missing(&db.query("SELECT c.guid,c.race,c.class FROM acore_characters.characters c LEFT JOIN acore_world.playercreateinfo p ON p.race=c.race AND p.class=c.class WHERE p.race IS NULL;")?)
}
pub fn capture(db: &Db, root: &Path) -> Result<Baseline> {
let mut realms = BTreeMap::new();
for mode in crate::realms::state(root)?.modes() {
realms.insert(
mode.name().to_owned(),
missing(&db.clone().for_realm(mode))?,
);
}
Ok(Baseline { schema: 1, realms })
}
/// Match identity and race/class, never just totals: one new failure cannot replace an old one.
pub fn introduced(
current: &BTreeSet<MissingStart>,
before: &BTreeSet<MissingStart>,
) -> BTreeSet<MissingStart> {
current.difference(before).copied().collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn old_gaps_are_not_new_character_loss() {
let before = parse_missing("1\t44\t14\n2\t44\t14\n3\t44\t14").unwrap();
assert!(introduced(&before, &before).is_empty());
assert!(introduced(&BTreeSet::new(), &before).is_empty());
let replaced = parse_missing("1\t44\t14\n2\t44\t14\n4\t44\t14").unwrap();
assert_eq!(
introduced(&replaced, &before),
parse_missing("4\t44\t14").unwrap()
);
let changed = parse_missing("1\t44\t15").unwrap();
assert_eq!(introduced(&changed, &before), changed);
assert_eq!(introduced(&before, &BTreeSet::new()), before);
}
#[test]
fn malformed_identity_is_not_silently_ignored() {
for text in ["1\t44", "bad\t44\t14", "1\t44\t14\t0", "1\t44\t-1"] {
assert!(parse_missing(text).is_err());
}
assert!(parse_missing("").unwrap().is_empty());
}
#[test]
fn reported_174_old_records_cannot_mask_one_newly_hidden_character() {
// Reproduce the report's scale without shipping another person's diagnostics or identities.
let before: BTreeSet<_> = (1..=174)
.map(|guid| MissingStart {
guid,
race: 44,
class: 14,
})
.collect();
assert!(introduced(&before, &before).is_empty());
let mut after = before.clone();
after.remove(&MissingStart {
guid: 1,
race: 44,
class: 14,
});
after.insert(MissingStart {
guid: 175,
race: 44,
class: 14,
});
assert_eq!(after.len(), before.len());
assert_eq!(
introduced(&after, &before),
BTreeSet::from([MissingStart {
guid: 175,
race: 44,
class: 14
}])
);
}
}
+134
View File
@@ -0,0 +1,134 @@
use crate::{fsx, Error, Result};
use serde::{Deserialize, Serialize};
use std::{fs, path::Path};
#[derive(Default, Serialize, Deserialize)]
pub struct Graphics {
pub dxvk_disabled: bool,
pub enhancements_disabled: bool,
}
fn preferences(client: &Path) -> Result<Option<Graphics>> {
match fs::read(client.join(".coa-manager/graphics.json")) {
Ok(bytes) => Ok(Some(serde_json::from_slice(&bytes)?)),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
Err(e) => Err(e.into()),
}
}
pub fn status(client: &Path) -> Result<Graphics> {
let saved = preferences(client)?.unwrap_or_default();
let actual = |name: &str, remembered: bool| -> Result<bool> {
let active = client.join(name).is_file();
let inactive = client.join(format!("{name}.DISABLED")).is_file();
if active && inactive {
return Err(Error::Invalid(
"Both enabled and disabled renderer files exist.".into(),
));
}
Ok(inactive || (!active && remembered))
};
Ok(Graphics {
dxvk_disabled: actual("d3d9.dll", saved.dxvk_disabled)?,
enhancements_disabled: actual("dxgi.dll", saved.enhancements_disabled)?,
})
}
pub fn disabled(client: &Path, path: &str) -> Result<bool> {
let name = path.to_ascii_lowercase();
if !matches!(name.as_str(), "d3d9.dll" | "dxgi.dll") {
return Ok(false);
}
let state = status(client)?;
Ok(if name == "d3d9.dll" {
state.dxvk_disabled
} else {
state.enhancements_disabled
})
}
pub fn set(client: &Path, name: &str, disabled: bool) -> Result<Graphics> {
if !matches!(name, "d3d9.dll" | "dxgi.dll") {
return Err(Error::Invalid("Unknown graphics setting.".into()));
}
if crate::client::is_running(client) {
return Err(Error::Invalid(
"Close the game before changing graphics settings.".into(),
));
}
let active = fsx::safe_join(client, name)?;
let inactive = fsx::safe_join(client, &format!("{name}.DISABLED"))?;
if active.exists() && inactive.exists() {
return Err(Error::Invalid("Both enabled and disabled renderer files exist. Resolve the conflict before changing graphics settings.".into()));
}
let mut state = status(client)?;
if name == "d3d9.dll" {
state.dxvk_disabled = disabled;
} else {
state.enhancements_disabled = disabled;
}
let (source, target) = if disabled {
(&active, &inactive)
} else {
(&inactive, &active)
};
// The no-clobber link also preserves an existing destination if another app changes the setting.
if source.is_file() {
if let Err(error) = fs::hard_link(source, target) {
if error.kind() == std::io::ErrorKind::AlreadyExists {
return Err(error.into());
}
let mut output = fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(target)?;
let copied = std::fs::File::open(source)
.and_then(|mut input| std::io::copy(&mut input, &mut output))
.and_then(|_| output.sync_all());
drop(output);
if let Err(error) = copied {
let _ = fs::remove_file(target);
return Err(error.into());
}
}
if let Err(error) = fs::remove_file(source) {
let _ = fs::remove_file(target);
return Err(error.into());
}
}
fsx::atomic_write_json(&client.join(".coa-manager/graphics.json"), &state)?;
Ok(state)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn toggles_preserve_bytes_and_refuse_conflicts() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
fs::write(root.join("d3d9.dll"), b"custom renderer").unwrap();
assert!(set(root, "d3d9.dll", true).unwrap().dxvk_disabled);
assert!(!root.join("d3d9.dll").exists());
assert_eq!(
fs::read(root.join("d3d9.dll.DISABLED")).unwrap(),
b"custom renderer"
);
assert!(!set(root, "d3d9.dll", false).unwrap().dxvk_disabled);
fs::write(root.join("d3d9.dll.DISABLED"), b"other").unwrap();
assert!(set(root, "d3d9.dll", false).is_err());
assert_eq!(fs::read(root.join("d3d9.dll")).unwrap(), b"custom renderer");
assert_eq!(fs::read(root.join("d3d9.dll.DISABLED")).unwrap(), b"other");
}
#[test]
fn remembers_missing_wrapper_and_imports_launcher_marker() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
assert!(set(root, "d3d9.dll", true).unwrap().dxvk_disabled);
assert!(disabled(root, "d3d9.dll").unwrap());
fs::write(root.join("dxgi.dll.DISABLED"), b"launcher disabled").unwrap();
assert!(disabled(root, "dxgi.dll").unwrap());
assert!(!disabled(root, "Data/d3d9.dll").unwrap());
}
}
+54
View File
@@ -299,6 +299,11 @@ pub fn plan(
bytes_per_sec: 0,
file: Some(f.path.clone()),
});
if crate::client_graphics::disabled(client, &f.path)? {
kept += 1;
done += f.size;
continue;
}
let path = fsx::safe_join(client, &f.path)?;
let meta = match fs::metadata(&path) {
Ok(meta) if meta.is_file() => meta,
@@ -440,6 +445,9 @@ pub fn apply(a: &Apply, on_step: &dyn Fn(Step)) -> Result<()> {
let mut todo = Vec::new();
for item in &a.plan.items {
if crate::client_graphics::disabled(a.client, &item.path)? {
continue;
}
if item.kind == Kind::Modified && a.keep_modified {
let path = fsx::safe_join(a.client, &item.path)?;
let meta = fs::metadata(&path)?;
@@ -777,6 +785,52 @@ mod tests {
);
}
#[test]
fn disabled_launcher_renderers_are_never_restored_even_with_a_stale_plan() {
let dir = tempfile::tempdir().unwrap();
let files: Vec<(&str, &[u8])> = vec![("d3d9.dll", b"dxvk"), ("dxgi.dll", b"enhancements")];
let manifest = manifest("v1", &files);
let cancel = Cancel::default();
let old_plan = plan(dir.path(), &manifest, &State::default(), &cancel, &|_| {}).unwrap();
fs::write(dir.path().join("d3d9.dll.DISABLED"), b"custom disabled").unwrap();
crate::client_graphics::set(dir.path(), "dxgi.dll", true).unwrap();
let server = Server::new(&files);
apply(
&Apply {
client: dir.path(),
manifest: &manifest,
plan: &old_plan,
keep_modified: false,
transport: &server,
objects_url: "https://x.invalid/objects",
cancel: &cancel,
},
&|_| {},
)
.unwrap();
assert!(server.requested.lock().unwrap().is_empty());
assert!(!dir.path().join("d3d9.dll").exists());
assert!(!dir.path().join("dxgi.dll").exists());
assert_eq!(
fs::read(dir.path().join("d3d9.dll.DISABLED")).unwrap(),
b"custom disabled"
);
let after = plan(
dir.path(),
&manifest,
&load_state(dir.path()).unwrap(),
&cancel,
&|_| {},
)
.unwrap();
assert!(after.items.is_empty());
crate::client_graphics::set(dir.path(), "d3d9.dll", false).unwrap();
assert_eq!(
fs::read(dir.path().join("d3d9.dll")).unwrap(),
b"custom disabled"
);
}
#[test]
fn renderer_files_configs_and_everything_not_in_the_manifest_survive_an_update_untouched() {
let d = tempfile::tempdir().unwrap();
+69 -13
View File
@@ -214,11 +214,13 @@ fn run(
struct StreamWorker {
tx: Sender<TunnelMsg>,
reset_on_drop: bool,
shutdown: Arc<TcpStream>,
}
impl Drop for StreamWorker {
fn drop(&mut self) {
if self.reset_on_drop {
let _ = self.shutdown.shutdown(std::net::Shutdown::Both);
let _ = self.tx.send(TunnelMsg::Reset { stream_id: 0 });
}
}
@@ -388,6 +390,8 @@ fn session(
};
match TcpStream::connect(("127.0.0.1", local_port)) {
Ok(tcp) => {
let tcp = Arc::new(tcp);
let shutdown = tcp.clone();
let (stream_tx, stream_rx) = channel::<TunnelMsg>();
let ws_tx = ws_out_tx.clone();
@@ -398,6 +402,7 @@ fn session(
StreamWorker {
tx: stream_tx,
reset_on_drop: true,
shutdown,
},
);
@@ -456,19 +461,20 @@ fn session(
fn spawn_local_tcp_bridge(
stream_id: u32,
mut tcp: TcpStream,
tcp: Arc<TcpStream>,
from_tunnel: Receiver<TunnelMsg>,
to_tunnel: Sender<TunnelMsg>,
) {
let _ = tcp.set_nonblocking(false);
let _ = tcp.set_nodelay(true);
let mut tcp_read = tcp.try_clone().expect("tcp clone");
let tcp_read = tcp.clone();
let to_tunnel_read = to_tunnel.clone();
// Local TCP read -> to tunnel
std::thread::Builder::new()
.name(format!("relay-stream-{stream_id}-read"))
.spawn(move || {
let mut tcp_read = tcp_read.as_ref();
let mut buf = [0u8; 16384];
loop {
match tcp_read.read(&mut buf) {
@@ -498,11 +504,12 @@ fn spawn_local_tcp_bridge(
std::thread::Builder::new()
.name(format!("relay-stream-{stream_id}-write"))
.spawn(move || {
let mut tcp_write = tcp.as_ref();
while let Ok(msg) = from_tunnel.recv() {
match msg {
TunnelMsg::Data { chunk, .. } => {
if let Ok(data) = base64::engine::general_purpose::STANDARD.decode(&chunk) {
if tcp.write_all(&data).is_err() {
if tcp_write.write_all(&data).is_err() {
break;
}
}
@@ -608,22 +615,71 @@ mod tests {
}
#[test]
fn dropping_a_tunnel_closes_its_local_tcp_stream() {
fn local_tunnel_exchanges_data_in_both_directions_before_reset() {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let tcp = TcpStream::connect(listener.local_addr().unwrap()).unwrap();
let tcp = Arc::new(TcpStream::connect(listener.local_addr().unwrap()).unwrap());
let shutdown = tcp.clone();
let (mut peer, _) = listener.accept().unwrap();
peer.set_read_timeout(Some(Duration::from_secs(3))).unwrap();
let (tx, rx) = channel();
let (out, _) = channel();
spawn_local_tcp_bridge(7, tcp, rx, out);
drop(StreamWorker {
let (out, replies) = channel();
spawn_local_tcp_bridge(8, tcp, rx, out);
let worker = StreamWorker {
tx,
reset_on_drop: true,
});
match peer.read(&mut [0u8; 1]) {
Ok(0) => {},
Err(error) if matches!(error.kind(), std::io::ErrorKind::ConnectionReset | std::io::ErrorKind::ConnectionAborted) => {},
other => panic!("The abandoned relay stream must close, got {other:?}"),
shutdown,
};
worker
.tx
.send(TunnelMsg::Data {
stream_id: 8,
chunk: base64::engine::general_purpose::STANDARD.encode(b"request"),
})
.unwrap();
let mut request = [0; 7];
peer.read_exact(&mut request).unwrap();
assert_eq!(&request, b"request");
peer.write_all(b"response").unwrap();
let mut response = Vec::new();
while response.len() < 8 {
match replies.recv_timeout(Duration::from_secs(3)).unwrap() {
TunnelMsg::Data { chunk, .. } => response.extend(
base64::engine::general_purpose::STANDARD
.decode(chunk)
.unwrap(),
),
other => panic!("Expected the local reply, got {other:?}"),
}
}
assert_eq!(response, b"response");
drop(worker);
}
#[test]
fn dropping_a_tunnel_closes_its_local_tcp_stream() {
for _ in 0..32 {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let tcp = Arc::new(TcpStream::connect(listener.local_addr().unwrap()).unwrap());
let shutdown = tcp.clone();
let (mut peer, _) = listener.accept().unwrap();
peer.set_read_timeout(Some(Duration::from_secs(3))).unwrap();
let (tx, rx) = channel();
let (out, _) = channel();
spawn_local_tcp_bridge(7, tcp, rx, out);
drop(StreamWorker {
tx,
reset_on_drop: true,
shutdown,
});
match peer.read(&mut [0u8; 1]) {
Ok(0) => {}
Err(error)
if matches!(
error.kind(),
std::io::ErrorKind::ConnectionReset | std::io::ErrorKind::ConnectionAborted
) => {}
other => panic!("The abandoned relay stream must close, got {other:?}"),
}
}
}
}
+67 -12
View File
@@ -24,17 +24,25 @@ pub struct CrashItem {
/// Lists recent crash reports from `Core/Crashes`, sorted newest first.
pub fn list(root: &Path, limit: usize) -> Result<Vec<CrashItem>> {
let dir = root.join("Core/Crashes");
let mut roots = vec![root.to_path_buf()];
roots.extend(crate::multiworld::Tree::ALL.map(|tree| crate::multiworld::tree_root(root, tree)));
let mut files: Vec<(PathBuf, SystemTime)> = Vec::new();
if let Ok(entries) = fs::read_dir(&dir) {
for entry in entries.flatten() {
let path = entry.path();
if path.is_file() && path.extension().and_then(|e| e.to_str()) == Some("txt") {
let mtime = entry
.metadata()
.and_then(|m| m.modified())
.unwrap_or(SystemTime::UNIX_EPOCH);
files.push((path, mtime));
for world_root in roots {
let entries = match fs::read_dir(world_root.join("Core/Crashes")) {
Ok(entries) => Some(entries),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
Err(e) => return Err(e.into()),
};
if let Some(entries) = entries {
for entry in entries.flatten() {
let path = entry.path();
if path.is_file() && path.extension().and_then(|e| e.to_str()) == Some("txt") {
let mtime = entry
.metadata()
.and_then(|m| m.modified())
.unwrap_or(SystemTime::UNIX_EPOCH);
files.push((path, mtime));
}
}
}
}
@@ -43,8 +51,12 @@ pub fn list(root: &Path, limit: usize) -> Result<Vec<CrashItem>> {
let mut items = Vec::new();
for (path, mtime) in files {
if let Ok(content) = fs::read_to_string(&path) {
let item = parse_crash_content(&path, mtime, &content);
if let Ok(bytes) = fs::read(&path) {
let content = String::from_utf8_lossy(&bytes);
let mut item = parse_crash_content(&path, mtime, &content);
if let Ok(relative) = path.strip_prefix(root) {
item.id = relative.to_string_lossy().replace('\\', "/");
}
items.push(item);
}
}
@@ -237,6 +249,49 @@ fn explain(
mod tests {
use super::*;
#[test]
fn discovers_native_ansi_reports_and_ignores_dump_files() {
let root = tempfile::tempdir().unwrap();
assert!(list(root.path(), 10).unwrap().is_empty());
fs::create_dir_all(root.path().join("Core/Crashes")).unwrap();
fs::write(
root.path().join("Core/Crashes/report.txt"),
b"Exception code: C0000005 \xff\r\n",
)
.unwrap();
fs::write(root.path().join("Core/Crashes/report.dmp"), b"binary").unwrap();
let reports = list(root.path(), 10).unwrap();
assert_eq!(reports.len(), 1);
assert_eq!(reports[0].exception_code.as_deref(), Some("C0000005"));
}
#[test]
fn discovers_reports_from_all_worlds_without_filename_collisions() {
let root = tempfile::tempdir().unwrap();
for relative in [
"Core/Crashes",
".realms/secondary/Core/Crashes",
".realms/reborn/Core/Crashes",
] {
fs::create_dir_all(root.path().join(relative)).unwrap();
fs::write(
root.path().join(relative).join("same.txt"),
b"Exception code: C0000005",
)
.unwrap();
}
let reports = list(root.path(), 10).unwrap();
assert_eq!(reports.len(), 3);
assert_eq!(
reports
.iter()
.map(|r| &r.id)
.collect::<std::collections::HashSet<_>>()
.len(),
3
);
}
#[test]
fn parses_assertion_report() {
let report = r#"Revision: AzerothCore rev. df5bcdf26092 2026-10-02 22:08:42 +0500 (coa-bots branch) (Win64, RelWithDebInfo, Static)
+306 -124
View File
@@ -5,7 +5,7 @@
//! into the player's WoW client directory.
use std::fs::{self, File};
use std::io::{self, Read, Write};
use std::io::{self, Read};
use std::path::{Path, PathBuf};
use serde::{Deserialize, Serialize};
@@ -153,7 +153,10 @@ pub fn sync_bot_races_config(root: &Path, allow_custom_races: bool) -> Result<()
let clean = value.trim().trim_matches(['"', '\'']);
let owned = String::from_utf8_lossy(&bytes)
.contains("CoA Custom: races new random bots never get")
&& matches!(clean, EXCLUDED_BOT_RACES_RECOMMENDED | EXCLUDED_BOT_RACES_EXPERIMENTAL);
&& matches!(
clean,
EXCLUDED_BOT_RACES_RECOMMENDED | EXCLUDED_BOT_RACES_EXPERIMENTAL
);
if !owned {
continue;
}
@@ -662,134 +665,147 @@ fn stage_root_asset(staging: &Path, relative: &str, reader: &mut impl Read) -> R
Ok(relative.to_string())
}
fn verify_archive(path: &Path, filename: &str) -> Result<()> {
let expected = match filename {
"CoA-Custom-1.9.2-Client-1.zip" => {
"a9dd51ed2d90fb048d549602f40f5429d56e2df0df5606a38781b358fa369568"
}
"CoA-Custom-1.9.2-Client-2.zip" => {
"ab084a55509ccbcc2977a06dd0c01fa879973a1892baaacaeb3ff52f3dfc750e"
}
"CoA-Custom-1.9.2-Client-3.zip" => {
"907e267f0ee7038807e626c3c1eca5e12db6c88b747137a23c5fb52eaa1a358e"
}
"CoA-Custom-1.9.2-Client-4.zip" => {
"e0bd87172af989fa50a8e2b08ba4321c72b6265047482f051a1db3b80d55bcaa"
}
"CoA-Custom-1.9.2-Client-5.zip" => {
"73364ad1b58c6342641a848a3b20a835472834f600416606be1470386774ca78"
}
fn archive_job(filename: &str, url: &str, cache: &Path) -> Result<crate::download::Job> {
let (size, sha256) = match filename {
"CoA-Custom-1.9.2-Client-1.zip" => (
1_513_021_586,
"a9dd51ed2d90fb048d549602f40f5429d56e2df0df5606a38781b358fa369568",
),
"CoA-Custom-1.9.2-Client-2.zip" => (
1_198_283_005,
"ab084a55509ccbcc2977a06dd0c01fa879973a1892baaacaeb3ff52f3dfc750e",
),
"CoA-Custom-1.9.2-Client-3.zip" => (
1_678_829_573,
"907e267f0ee7038807e626c3c1eca5e12db6c88b747137a23c5fb52eaa1a358e",
),
"CoA-Custom-1.9.2-Client-4.zip" => (
502_385_128,
"e0bd87172af989fa50a8e2b08ba4321c72b6265047482f051a1db3b80d55bcaa",
),
"CoA-Custom-1.9.2-Client-5.zip" => (
168_079_711,
"73364ad1b58c6342641a848a3b20a835472834f600416606be1470386774ca78",
),
_ => return Err(Error::Invalid("Unknown custom races archive.".into())),
};
if fsx::sha256_file(path)? != expected {
Ok(crate::download::Job {
url: url.into(),
dest: cache.join(filename),
sha256: sha256.into(),
size,
})
}
fn archive_matches(path: &Path, job: &crate::download::Job) -> bool {
path.metadata()
.is_ok_and(|m| m.is_file() && m.len() == job.size)
&& fsx::sha256_file(path).is_ok_and(|hash| hash.eq_ignore_ascii_case(&job.sha256))
}
#[cfg(test)]
fn verify_archive(path: &Path, filename: &str) -> Result<()> {
let job = archive_job(filename, "", Path::new(""))?;
if !archive_matches(path, &job) {
return Err(Error::Invalid(format!(
"Custom races archive {filename} failed verification. Remove it and try again."
"Custom races archive {filename} failed verification."
)));
}
Ok(())
}
/// Locate an archive locally in Downloads or cache, or download it from GitHub.
/// User-owned Downloads files are read-only candidates. Only the Manager's cache is repaired.
fn resolve_archive_with(
transport: &dyn crate::download::Transport,
job: &crate::download::Job,
downloads: Option<&Path>,
cancel: &Cancel,
progress: &dyn Fn(crate::download::Progress),
) -> Result<PathBuf> {
if cancel.is_set() {
return Err(Error::Invalid("Download cancelled.".into()));
}
if let Some(downloads) = downloads {
let candidate = downloads.join(job.dest.file_name().unwrap_or_default());
if archive_matches(&candidate, job) {
tracing::info!(path = %candidate.display(), "using verified archive in Downloads");
progress(crate::download::Progress {
downloaded: job.size,
total: job.size,
bytes_per_sec: 0,
});
return Ok(candidate);
}
if candidate.exists() {
tracing::warn!(path = %candidate.display(), "ignoring incomplete or unverified archive in Downloads");
}
}
let cache = job
.dest
.parent()
.ok_or_else(|| Error::Invalid("Missing archive cache directory.".into()))?;
fs::create_dir_all(cache)?;
// Different installations share this cache; never append to or replace another active download.
use fs4::fs_std::FileExt;
let lock = fs::OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(false)
.open(suffix(&job.dest, "lock"))?;
if !lock.try_lock_exclusive()? {
return Err(Error::Invalid("Another custom races download is using this archive. Wait for it to finish, then retry.".into()));
}
if job.dest.is_file() {
if archive_matches(&job.dest, job) {
progress(crate::download::Progress {
downloaded: job.size,
total: job.size,
bytes_per_sec: 0,
});
return Ok(job.dest.clone());
}
tracing::warn!(path = %job.dest.display(), "removing unverified Manager archive cache; downloading again");
fs::remove_file(&job.dest)?;
}
// The shared downloader resumes .part files and verifies the complete archive before promotion.
// A stale/corrupt prefix may only be detectable after resume: retry once from scratch in that case.
match crate::download::fetch_with(transport, job, cancel, progress) {
Err(Error::HashMismatch { .. }) if !cancel.is_set() => {
tracing::warn!(path = %job.dest.display(), "archive verification failed; retrying a clean download");
crate::download::fetch_with(transport, job, cancel, progress)?;
}
result => result?,
}
Ok(job.dest.clone())
}
/// Locate a verified archive or resume downloading it into the Manager's cache.
fn resolve_or_download_archive(
filename: &str,
url: &str,
client: &reqwest::blocking::Client,
transport: &dyn crate::download::Transport,
cancel: &Cancel,
report: &dyn Fn(&str, f32),
base_percent: f32,
percent_slice: f32,
) -> Result<PathBuf> {
// 1. Check user Downloads folder
if let Some(userprofile) = std::env::var_os("USERPROFILE") {
let downloads = PathBuf::from(userprofile).join("Downloads");
let candidate = downloads.join(filename);
if candidate.is_file() {
if let Ok(meta) = candidate.metadata() {
if meta.len() > 1000 {
tracing::info!(path = %candidate.display(), "using existing archive in Downloads");
verify_archive(&candidate, filename)?;
return Ok(candidate);
}
}
}
}
// 2. Check temp / cache directory
let cache_dir = std::env::temp_dir().join("coa-client-races");
fs::create_dir_all(&cache_dir)?;
let target = cache_dir.join(filename);
if target.is_file() {
if let Ok(meta) = target.metadata() {
if meta.len() > 1000 {
verify_archive(&target, filename)?;
return Ok(target);
}
}
}
// 3. Download from GitHub Releases
report(&format!("Downloading {filename}..."), base_percent);
let part_path = cache_dir.join(format!("{filename}.part"));
let resp = client
.get(url)
.send()
.map_err(|e| Error::NetworkUnreachable(format!("Could not reach download server: {e}")))?;
if !resp.status().is_success() {
return Err(Error::NetworkUnreachable(format!(
"Download failed with status {} for {url}",
resp.status()
)));
}
let total_bytes = resp.content_length().unwrap_or(0);
let mut downloaded = 0u64;
let mut src = resp;
let mut dst = File::create(&part_path)?;
let mut buf = [0u8; 64 * 1024];
let mut last_report = std::time::Instant::now();
loop {
if cancel.is_set() {
let _ = fs::remove_file(&part_path);
return Err(Error::Invalid("Operation cancelled.".into()));
}
let n = src
.read(&mut buf)
.map_err(|e| Error::NetworkUnreachable(format!("Download interrupted: {e}")))?;
if n == 0 {
break;
}
dst.write_all(&buf[..n])?;
downloaded += n as u64;
if last_report.elapsed() > std::time::Duration::from_millis(200) {
let ratio = if total_bytes > 0 {
(downloaded as f32 / total_bytes as f32).clamp(0.0, 1.0)
} else {
0.5
};
report(
&format!(
"Downloading {filename} ({:.1} MB)...",
downloaded as f64 / 1_048_576.0
),
base_percent + ratio * percent_slice,
);
last_report = std::time::Instant::now();
}
}
dst.flush()?;
drop(dst);
verify_archive(&part_path, filename)?;
fs::rename(&part_path, &target)?;
Ok(target)
// Report before hashing existing files: otherwise checking a large archive looks like no operation.
report(&format!("Checking {filename}..."), base_percent);
let cache = std::env::temp_dir().join("coa-client-races");
let downloads = std::env::var_os("USERPROFILE").map(|p| PathBuf::from(p).join("Downloads"));
let job = archive_job(filename, url, &cache)?;
resolve_archive_with(transport, &job, downloads.as_deref(), cancel, &|p| {
let ratio = p.downloaded as f32 / p.total.max(1) as f32;
report(
&format!(
"Downloading {filename} ({:.1} MB)...",
p.downloaded as f64 / 1_048_576.0
),
base_percent + ratio.clamp(0.0, 1.0) * percent_slice,
);
})
}
/// Download (if needed) and extract custom races client assets into the target WoW client.
@@ -818,11 +834,7 @@ pub fn install_client_patches(
fs::create_dir_all(&data_dir)?;
// 2. Resolve/download archives (0.05 .. 0.50)
let http = reqwest::blocking::Client::builder()
.user_agent(concat!("CoA-Server-Manager/", env!("CARGO_PKG_VERSION")))
.timeout(std::time::Duration::from_secs(600))
.build()
.map_err(|e| Error::Invalid(format!("Cannot prepare downloader: {e}")))?;
let http = crate::download::HttpTransport::with_total_timeout(600)?;
let mut resolved_archives = Vec::new();
let n_archives = ARCHIVES.len() as f32;
@@ -1113,7 +1125,9 @@ mod tests {
serde_json::from_str(include_str!("custom_races_hashes_1_9_1.json")).unwrap();
let files = patch_files(temp.path()).unwrap();
assert_eq!(files.len(), old.len());
assert!(files.iter().all(|file| old.get(&file.path) == Some(&file.sha256)));
assert!(files
.iter()
.all(|file| old.get(&file.path) == Some(&file.sha256)));
assert!(!files.iter().any(|file| file.path.contains("CoAQuestSafe")));
}
@@ -1571,11 +1585,179 @@ mod tests {
);
}
struct ArchiveTransport {
body: Vec<u8>,
ranges: std::sync::Mutex<Vec<u64>>,
}
impl crate::download::Transport for ArchiveTransport {
fn get(&self, _: &str, from: u64) -> std::result::Result<crate::download::Reply, String> {
self.ranges.lock().unwrap().push(from);
Ok(crate::download::Reply {
status: if from == 0 { 200 } else { 206 },
content_range: (from > 0)
.then(|| format!("bytes {from}-{}/{}", self.body.len() - 1, self.body.len())),
body: Box::new(io::Cursor::new(self.body[from as usize..].to_vec())),
})
}
}
fn archive_fixture(root: &Path) -> (crate::download::Job, ArchiveTransport) {
use sha2::{Digest, Sha256};
let body = b"verified archive bytes for recovery tests".to_vec();
let job = crate::download::Job {
url: "https://example.invalid/patch.zip".into(),
dest: root.join("cache/patch.zip"),
sha256: hex::encode(Sha256::digest(&body)),
size: body.len() as u64,
};
fs::create_dir_all(job.dest.parent().unwrap()).unwrap();
(
job,
ArchiveTransport {
body,
ranges: Default::default(),
},
)
}
#[test]
fn corrupt_downloads_are_rejected() {
let temp = tempfile::NamedTempFile::new().unwrap();
fs::write(temp.path(), b"corrupt archive").unwrap();
assert!(verify_archive(temp.path(), ARCHIVES[0].0).is_err());
fn download_uses_verified_user_archive_without_network() {
let temp = tempfile::tempdir().unwrap();
let (job, transport) = archive_fixture(temp.path());
let downloads = temp.path().join("Downloads");
fs::create_dir(&downloads).unwrap();
let archive = downloads.join("patch.zip");
fs::write(&archive, &transport.body).unwrap();
let path = resolve_archive_with(
&transport,
&job,
Some(&downloads),
&Cancel::default(),
&|_| {},
)
.unwrap();
assert_eq!(path, archive);
assert!(transport.ranges.lock().unwrap().is_empty());
assert!(!job.dest.exists());
}
#[test]
fn download_skips_bad_user_archive_and_repairs_bad_cache() {
let temp = tempfile::tempdir().unwrap();
let (job, transport) = archive_fixture(temp.path());
let downloads = temp.path().join("Downloads");
fs::create_dir(&downloads).unwrap();
let bad = vec![b'x'; transport.body.len()];
fs::write(downloads.join("patch.zip"), &bad).unwrap();
fs::write(downloads.join("patch.zip.part"), b"user browser download").unwrap();
fs::write(&job.dest, &bad).unwrap();
let path = resolve_archive_with(
&transport,
&job,
Some(&downloads),
&Cancel::default(),
&|_| {},
)
.unwrap();
assert_eq!(path, job.dest);
assert_eq!(fs::read(&path).unwrap(), transport.body);
assert_eq!(fs::read(downloads.join("patch.zip")).unwrap(), bad);
assert_eq!(
fs::read(downloads.join("patch.zip.part")).unwrap(),
b"user browser download"
);
assert_eq!(*transport.ranges.lock().unwrap(), vec![0]);
}
#[test]
fn download_resumes_leftover_part_and_verifies_complete_archive() {
let temp = tempfile::tempdir().unwrap();
let (job, transport) = archive_fixture(temp.path());
let part = suffix(&job.dest, "part");
fs::write(&part, &transport.body[..9]).unwrap();
resolve_archive_with(&transport, &job, None, &Cancel::default(), &|_| {}).unwrap();
assert_eq!(*transport.ranges.lock().unwrap(), vec![9]);
assert_eq!(fs::read(&job.dest).unwrap(), transport.body);
assert!(!part.exists());
}
#[test]
fn download_reuses_good_cache_even_when_user_archive_is_incomplete() {
let temp = tempfile::tempdir().unwrap();
let (job, transport) = archive_fixture(temp.path());
let downloads = temp.path().join("Downloads");
fs::create_dir(&downloads).unwrap();
fs::write(downloads.join("patch.zip"), b"incomplete").unwrap();
fs::write(&job.dest, &transport.body).unwrap();
let path = resolve_archive_with(
&transport,
&job,
Some(&downloads),
&Cancel::default(),
&|_| {},
)
.unwrap();
assert_eq!(path, job.dest);
assert!(transport.ranges.lock().unwrap().is_empty());
assert_eq!(
fs::read(downloads.join("patch.zip")).unwrap(),
b"incomplete"
);
}
#[test]
fn download_restarts_once_when_resumed_prefix_is_corrupt() {
let temp = tempfile::tempdir().unwrap();
let (job, transport) = archive_fixture(temp.path());
fs::write(suffix(&job.dest, "part"), b"bad").unwrap();
resolve_archive_with(&transport, &job, None, &Cancel::default(), &|_| {}).unwrap();
assert_eq!(*transport.ranges.lock().unwrap(), vec![3, 0]);
assert_eq!(fs::read(&job.dest).unwrap(), transport.body);
}
#[test]
fn download_promotes_completed_part_without_redownloading() {
let temp = tempfile::tempdir().unwrap();
let (job, transport) = archive_fixture(temp.path());
fs::write(suffix(&job.dest, "part"), &transport.body).unwrap();
resolve_archive_with(&transport, &job, None, &Cancel::default(), &|_| {}).unwrap();
assert!(transport.ranges.lock().unwrap().is_empty());
assert_eq!(fs::read(&job.dest).unwrap(), transport.body);
}
#[test]
fn download_stops_after_one_clean_retry_if_server_bytes_are_invalid() {
let temp = tempfile::tempdir().unwrap();
let (job, mut transport) = archive_fixture(temp.path());
transport.body.fill(b'x');
let result = resolve_archive_with(&transport, &job, None, &Cancel::default(), &|_| {});
assert!(matches!(result, Err(Error::HashMismatch { .. })));
assert_eq!(*transport.ranges.lock().unwrap(), vec![0, 0]);
assert!(!job.dest.exists());
assert!(!suffix(&job.dest, "part").exists());
}
#[test]
fn download_does_not_modify_an_archive_owned_by_another_download() {
use fs4::fs_std::FileExt;
let temp = tempfile::tempdir().unwrap();
let (job, transport) = archive_fixture(temp.path());
let lock = fs::OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(false)
.open(suffix(&job.dest, "lock"))
.unwrap();
lock.try_lock_exclusive().unwrap();
fs::write(suffix(&job.dest, "part"), b"active download").unwrap();
assert!(resolve_archive_with(&transport, &job, None, &Cancel::default(), &|_| {}).is_err());
assert_eq!(
fs::read(suffix(&job.dest, "part")).unwrap(),
b"active download"
);
assert!(transport.ranges.lock().unwrap().is_empty());
}
#[test]
+27
View File
@@ -718,6 +718,24 @@ pub fn export_package(
"maintenance.json",
serde_json::to_string_pretty(&maintenance)?.as_bytes(),
)?;
for (realm, prefix) in [("primary", ""), ("secondary", ".realms/secondary/"), ("reborn", ".realms/reborn/")] {
let state = root.join(format!("{prefix}.state"));
if let Ok(owner) = fs::read_to_string(state.join("control-owner.json")) {
add(&format!("launcher/{realm}/control-owner.json"), redact_json(&owner).as_bytes())?;
}
for (path, _, _) in newest_files(&state.join("diagnostics"), "jsonl", 20)
.into_iter()
.filter(|(path, _, _)| path.file_name().is_some_and(|name| name.to_string_lossy().starts_with("manage-")))
.take(5)
{
let bytes = tail(&path, 512 * 1024);
let entries: Vec<serde_json::Value> = String::from_utf8_lossy(&bytes).lines().map(|line| {
serde_json::from_str(&redact_json(line)).unwrap_or_else(|_| serde_json::Value::String(redact(line)))
}).collect();
add(&format!("launcher/{realm}/{}.json", path.file_stem().unwrap_or_default().to_string_lossy()),
serde_json::to_string_pretty(&entries)?.as_bytes())?;
}
}
// Logs. The newest update logs of the repack's own updater are added under their own names.
let mut logs: Vec<(String, PathBuf)> = vec![
@@ -1257,6 +1275,12 @@ real error
fs::create_dir_all(meta_dir.join("diagnostics")).unwrap();
fs::write(meta_dir.join("diagnostics/schema-validation-CoA-test.json"), r#"{"problems":[{"table":"creature_display_preset","column":"display_id","detail":"default mismatch"}],"password":"schema-secret"}"#).unwrap();
fs::write(meta_dir.join("diagnostics/database-recovery-test.json"), r#"{"objects":[{"database":"acore_characters","kind":"TRIGGER","name":"user_character_trigger"}],"password":"recovery-secret"}"#).unwrap();
for prefix in ["", ".realms/secondary/", ".realms/reborn/"] {
let state = root.join(format!("{prefix}.state"));
fs::create_dir_all(state.join("diagnostics")).unwrap();
fs::write(state.join("control-owner.json"), r#"{"pid":42,"action":"start-all","password":"launcher-owner-secret"}"#).unwrap();
fs::write(state.join("diagnostics/manage-test.jsonl"), "{\"event\":\"launcher-stage-test\",\"password\":\"launcher-stage-secret\"}\n{\"event\":\"wait_ready.error\",\"port\":3307}\n").unwrap();
}
let meta = InstallMeta::new(InstallKind::Imported, &root);
let report = run(&root, &meta);
let zip_path = d.path().join("diag.zip");
@@ -1289,6 +1313,9 @@ real error
assert!(all.contains("checking updates") && all.contains("1234"));
assert!(all.contains("lockFilePresent") && all.contains("does not establish"));
assert!(!all.contains("owner-secret"));
assert!(all.contains("launcher-stage-test"));
assert!(all.contains("wait_ready.error"));
assert!(!all.contains("launcher-stage-secret"));
assert_eq!(fs::read(meta_dir.join("update.lock")).unwrap(), b"");
assert!(
!all.contains("hunter2")
+123 -312
View File
@@ -1,11 +1,10 @@
//! Start/stop of a repack-shaped installation by delegating to the repack's own supervisor
//! (`Runtime\python\python.exe Scripts\manage.py <verb>`), which already implements config rendering, the
//! bug-report relay, RA graceful shutdown and readiness. Observation stays native (see `process`).
//! Start/stop of a repack-shaped installation through the repack launcher in this crate
//! ([`crate::launcher`]): config rendering, the services, the world supervisor, graceful shutdown and readiness.
//! It writes the same `.state` records as the repack's `Scripts/manage.py`, so the repack's own launcher and
//! this Manager can be used on the same folder. Observation stays native (see `process`).
use std::io::Read;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::time::{Duration, Instant};
use std::path::Path;
use std::sync::Mutex;
use serde::Serialize;
@@ -22,43 +21,15 @@ pub enum Verb {
}
impl Verb {
fn arg(self) -> &'static str {
fn action(self) -> crate::launcher::ops::Action {
use crate::launcher::ops::Action;
match self {
Verb::StartAll => "start-all",
Verb::StartMysql => "start-mysql",
Verb::StartWorld => "start-world",
Verb::StopAll => "stop-all",
Verb::StartAll => Action::StartAll,
Verb::StartMysql => Action::StartMysql,
Verb::StartWorld => Action::StartWorld,
Verb::StopAll => Action::StopAll,
}
}
fn timeout(self, root: &Path) -> Duration {
match self {
Verb::StartAll | Verb::StartWorld if squid_enabled(root) => Duration::from_secs(2700),
Verb::StartAll | Verb::StartWorld => Duration::from_secs(420),
Verb::StartMysql => Duration::from_secs(120),
Verb::StopAll => Duration::from_secs(240),
}
}
}
fn squid_enabled(root: &Path) -> bool {
let active = root.join("Core/configs/modules/playerbots.conf");
let path = if active.exists() {
active
} else {
root.join("Core/configs/modules/playerbots.conf.dist")
};
std::fs::read(path)
.ok()
.and_then(|bytes| crate::config::parser::ConfFile::parse_bytes(&bytes).ok())
.is_some_and(|config| {
config.get("AiPlayerbot.Enabled").is_none_or(|value| {
!matches!(
value.trim().trim_matches('"').to_ascii_lowercase().as_str(),
"0" | "false" | "no" | "off"
)
})
})
}
#[derive(Debug, Clone, Serialize)]
@@ -71,41 +42,14 @@ pub struct DriverOutcome {
pub output: String,
}
/// Map the launcher's own messages onto stable error codes. Unknown text stays `Unknown` (details remain visible).
pub fn translate(output: &str) -> ErrorCode {
let o = output.to_lowercase();
if o.contains("is already used") {
ErrorCode::PortInUse
} else if o.contains("another start/stop action is in progress")
|| o.contains("shutdown is still finishing")
{
ErrorCode::OperationInProgress
} else if o.contains("packaged database is missing")
|| o.contains("extract the complete repack")
{
ErrorCode::ServerFilesIncomplete
} else if o.contains("stopped during startup")
|| o.contains("is still starting")
|| o.contains("world startup failed")
{
ErrorCode::StartupFailed
} else if o.contains("invalid port") || o.contains("unresolved placeholder") {
ErrorCode::InvalidConfigValue
} else {
ErrorCode::Unknown
}
}
fn launcher(root: &Path) -> Result<(PathBuf, PathBuf)> {
let python = root.join("Runtime/python/python.exe");
let script = root.join("Scripts/manage.py");
if !python.is_file() || !script.is_file() {
fn has_launcher_settings(root: &Path) -> Result<()> {
if !root.join("Settings/repack.json").is_file() {
return Err(Error::Invalid(
"This server has no CoA Repack launcher; start/stop is not available for it yet."
.into(),
));
}
Ok((python, script))
Ok(())
}
/// Run a launcher verb to completion (blocking; call from a worker thread).
@@ -122,7 +66,69 @@ pub(crate) fn validate_update(root: &Path) -> Result<DriverOutcome> {
run_inner(root, Verb::StartAll, true)
}
pub fn force_stop(root: &Path) -> Result<DriverOutcome> {
if crate::docker::is_docker(root) {
return Err(Error::Invalid(
"Forced shutdown is only available for Windows repacks.".into(),
));
}
for tree in crate::multiworld::Tree::ALL {
let path = crate::multiworld::tree_root(root, tree);
if crate::multiworld::tree_running(root, tree)
|| !crate::process::find_by_exe(&path.join("Core/worldserver.exe")).is_empty()
{
let child = fsx::ensure_within(root, &path)?;
let out = run_inner_mode(&child, Verb::StopAll, false, true)?;
if !out.ok || crate::multiworld::tree_running(root, tree) {
return Err(Error::Invalid(format!(
"An extra world could not stop; the shared database was left running. {}",
out.output
)));
}
}
}
run_inner_mode(root, Verb::StopAll, false, true)
}
fn recover_world_for_forced_stop(root: &Path) -> Result<()> {
let worlds = crate::process::find_by_exe(&root.join("Core/worldserver.exe"));
if worlds.len() > 1 {
return Err(Error::Invalid(
"More than one world process belongs to this folder; its database was left running."
.into(),
));
}
if let Some(world) = worlds.first() {
if !crate::process::is_alive(world) {
return Err(Error::Invalid(
"The world process identity changed; retry the stop.".into(),
));
}
if crate::process::read_state_record(root, "world")
.is_none_or(|saved| !saved.same_as(world))
{
let record = root.join(".state/world.json");
let previous = root.join(".state/world-before-forced-stop-recovery.json");
if record.is_file() && !previous.exists() {
fsx::atomic_write(&previous, &std::fs::read(&record)?)?;
}
fsx::atomic_write_json(&record, world)?;
tracing::warn!(pid = world.pid, root = %root.display(), "Recovered owned world identity before an explicitly requested forced stop");
}
}
Ok(())
}
fn run_inner(root: &Path, verb: Verb, validating_update: bool) -> Result<DriverOutcome> {
run_inner_mode(root, verb, validating_update, false)
}
fn run_inner_mode(
root: &Path,
verb: Verb,
validating_update: bool,
force: bool,
) -> Result<DriverOutcome> {
let root = fsx::canonicalize_lenient(root)?;
let _update_lock = if !validating_update && matches!(verb, Verb::StartAll | Verb::StartWorld) {
Some(crate::update::operation_lock_for(
@@ -143,7 +149,7 @@ fn run_inner(root: &Path, verb: Verb, validating_update: bool) -> Result<DriverO
prepare_headless_world(&root, verb)?;
return crate::docker::run(&root, verb);
}
if verb == Verb::StopAll {
if verb == Verb::StopAll && !force {
crate::multiworld::stop(&root)?;
}
if verb == Verb::StartAll {
@@ -162,94 +168,51 @@ fn run_inner(root: &Path, verb: Verb, validating_update: bool) -> Result<DriverO
if matches!(verb, Verb::StartAll | Verb::StartWorld) {
crate::modules::ensure_bot_exclusivity(&root)?;
}
let (python, script) = launcher(&root)?;
has_launcher_settings(&root)?;
prepare_headless_world(&root, verb)?;
let original = std::fs::read_to_string(&script)?;
let patched = patch_launcher_imports(&original)?;
if original != patched {
fsx::atomic_write(&script, patched.as_bytes())?;
if let Ok(dir) = crate::registry::metadata_dir_for(&root) {
if let Ok((_, mut meta)) = crate::registry::MetaDir::open(&dir) {
if meta.original_hashes.get("Scripts/manage.py")
== Some(&fsx::sha256_bytes(original.as_bytes()))
{
meta.original_hashes.insert(
"Scripts/manage.py".into(),
fsx::sha256_bytes(patched.as_bytes()),
);
fsx::atomic_write_json(&dir.join("install.json"), &meta)?;
}
}
}
}
discard_damaged_launcher_state(&root);
if matches!(verb, Verb::StopAll | Verb::StartMysql | Verb::StartAll) {
recover_mysql_launcher_state(&root, verb != Verb::StopAll)?;
}
let mut cmd = Command::new(&python);
cmd.arg("-B")
.arg("-c")
.arg(LAUNCH_SCRIPT)
.arg(&script)
.arg(verb.arg())
.current_dir(&root)
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped());
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
cmd.creation_flags(0x0800_0000); // CREATE_NO_WINDOW
if force {
recover_world_for_forced_stop(&root)?;
}
tracing::info!(?verb, root = %root.display(), "driver: starting launcher verb");
let mut child = cmd.spawn()?;
let mut stdout = child.stdout.take().expect("piped");
let mut stderr = child.stderr.take().expect("piped");
let out_t = std::thread::spawn(move || {
let mut s = String::new();
let _ = stdout.read_to_string(&mut s);
s
});
let err_t = std::thread::spawn(move || {
let mut s = String::new();
let _ = stderr.read_to_string(&mut s);
s
});
let deadline = Instant::now() + verb.timeout(&root);
let status = loop {
if let Some(st) = child.try_wait()? {
break Some(st);
}
if Instant::now() > deadline {
// Never kill the servers themselves: only abandon the launcher process we spawned.
let _ = child.kill();
break None;
}
std::thread::sleep(Duration::from_millis(200));
};
let mut output = out_t.join().unwrap_or_default();
output.push_str(&err_t.join().unwrap_or_default());
let mut output = output.trim().to_string();
let (ok, exit_code) = match status {
Some(st) => (st.success(), st.code()),
None => (false, None),
};
let code = if ok {
None
let action = if force {
crate::launcher::ops::Action::ForceStopAll
} else {
// Log evidence beats the launcher's generic "stopped during startup" message.
let base = if status.is_none() {
ErrorCode::StartupFailed
} else {
translate(&output)
};
match base {
ErrorCode::StartupFailed | ErrorCode::Unknown => {
Some(crate::health::diagnose_installation(&root).unwrap_or(base))
verb.action()
};
tracing::info!(?verb, root = %root.display(), "driver: starting launcher action");
let lines = Mutex::new(Vec::<String>::new());
let progress = |line: &str| {
tracing::info!(?verb, "launcher: {line}");
lines.lock().unwrap_or_else(|e| e.into_inner()).push(line.to_string());
};
let result = crate::launcher::Settings::load(&root, 0).and_then(|mut cfg| {
if validating_update {
// Isolated startup must use the port from its temporary auth config.
cfg.env_remove.push("AC_REALM_SERVER_PORT".into());
}
crate::launcher::ops::run(&root, &cfg, 0, action, None, &progress)
});
let mut output = lines.into_inner().unwrap_or_else(|e| e.into_inner()).join("\n");
let ok = result.is_ok();
let code = match &result {
Ok(()) => None,
Err(error) => {
if !output.is_empty() {
output.push('\n');
}
output.push_str(&format!("ERROR: {error}"));
// Log evidence beats a generic "stopped during startup".
match error.code() {
ErrorCode::StartupFailed | ErrorCode::Unknown => Some(
crate::health::diagnose_installation(&root).unwrap_or(error.code()),
),
other => Some(other),
}
other => Some(other),
}
};
let exit_code = Some(if ok { 0 } else { 1 });
if code == Some(ErrorCode::PortInUse) {
let observed = crate::process::observe(&root, &crate::layout::read_ports(&root));
for service in [&observed.mysql, &observed.auth, &observed.world]
@@ -290,6 +253,9 @@ fn prepare_headless_world(root: &Path, verb: Verb) -> Result<()> {
if !matches!(verb, Verb::StartAll | Verb::StartWorld) {
return Ok(());
}
std::fs::create_dir_all(root.join("Core/Crashes"))?;
let probe = tempfile::NamedTempFile::new_in(root.join("Core/Crashes"))?;
probe.close()?;
for relative in [
"Settings/worldserver.conf.template",
"Core/configs/worldserver.conf",
@@ -314,35 +280,6 @@ fn prepare_headless_world(root: &Path, verb: Verb) -> Result<()> {
Ok(())
}
/// The launcher keeps one JSON record per service in `.state`. A crash or power loss while it writes one can leave
/// a file of the right length that holds only zero bytes (NTFS keeps the length but not the data), and the launcher
/// then dies on every start with an unreadable record. Such a file carries no information, so remove it: the
/// launcher treats a missing record as "not running". Only empty or all-zero `*.json` files are touched.
pub(crate) fn discard_damaged_launcher_state(root: &Path) -> Vec<PathBuf> {
let mut removed = Vec::new();
let Ok(entries) = std::fs::read_dir(root.join(".state")) else {
return removed;
};
for entry in entries.flatten() {
let path = entry.path();
if path
.extension()
.is_none_or(|e| !e.eq_ignore_ascii_case("json"))
|| !path.is_file()
{
continue;
}
let Ok(bytes) = std::fs::read(&path) else {
continue;
};
if bytes.iter().all(|b| *b == 0) && std::fs::remove_file(&path).is_ok() {
tracing::warn!(file = %path.display(), bytes = bytes.len(), "driver: removed a launcher state file damaged by an interrupted write");
removed.push(path);
}
}
removed
}
/// A lost launcher record must not hide this installation's running MySQL from
/// graceful shutdown. Adopt only the exact executable owning its configured port.
fn recover_mysql_launcher_state(root: &Path, prefer_listener: bool) -> Result<()> {
@@ -393,60 +330,6 @@ fn recover_mysql_launcher_state(root: &Path, prefer_listener: bool) -> Result<()
Ok(())
}
const LAUNCH_SCRIPT: &str = "import runpy,sys\nfrom pathlib import Path\nscript=sys.argv[1]\nsys.path.insert(0,str(Path(script).resolve().parent))\nsys.argv=sys.argv[1:]\nif sys.argv[1]=='stop-all':\n launcher=runpy.run_path(script,run_name='coa_manager_shutdown')\n config=launcher['settings']()\n with launcher['control_lock']():\n launcher['stop_all'](config)\nelse:\n runpy.run_path(script,run_name='__main__')";
pub(crate) fn patch_launcher_imports(text: &str) -> Result<String> {
let line = "sys.path.insert(0, str(Path(__file__).resolve().parent))";
if !text.contains("from squid_playerbots import") || text.contains(line) {
return Ok(text.into());
}
let root = "ROOT = Path(__file__).resolve().parents[1]";
if !text.contains(root) || !text.lines().any(|line| line.trim() == "import sys") {
return Err(Error::Invalid(
"The server launcher cannot load its integration scripts. Repair its program files."
.into(),
));
}
Ok(text.replacen(root, &format!("{root}\n{line}"), 1))
}
pub(crate) fn launcher_matches(signed: &str, actual: &[u8]) -> bool {
if signed.as_bytes() == actual {
return true;
}
if patch_launcher_imports(signed).is_ok_and(|s| s.as_bytes() == actual) {
return true;
}
crate::realms::patch_launcher(signed).is_ok_and(|s| {
s.as_bytes() == actual || patch_launcher_imports(&s).is_ok_and(|p| p.as_bytes() == actual)
})
}
/// Recover legacy metadata only when undoing supported Manager edits reproduces the recorded hash.
pub(crate) fn launcher_matches_recorded(recorded: &str, actual: &[u8]) -> bool {
let Ok(text) = std::str::from_utf8(actual) else {
return false;
};
let without_import = text.replacen(
"ROOT = Path(__file__).resolve().parents[1]\nsys.path.insert(0, str(Path(__file__).resolve().parent))",
"ROOT = Path(__file__).resolve().parents[1]", 1,
);
for candidate in [
Some(without_import.clone()),
crate::realms::unpatch_launcher(&without_import),
]
.into_iter()
.flatten()
{
if crate::fsx::sha256_bytes(candidate.as_bytes()).eq_ignore_ascii_case(recorded)
&& launcher_matches(&candidate, actual)
{
return true;
}
}
false
}
pub(crate) fn startup_failure(root: &Path, started: &DriverOutcome) -> String {
let code = started
.code
@@ -548,7 +431,7 @@ mod tests {
text.contains("launcher request failed before completion")
&& text.contains("in progress")
);
assert!(!text.contains("starting launcher verb"));
assert!(!text.contains("starting launcher action"));
}
#[test]
@@ -587,6 +470,7 @@ mod tests {
let folder = tempfile::tempdir().unwrap();
let root = folder.path();
prepare_headless_world(root, Verb::StartAll).unwrap();
assert!(root.join("Core/Crashes").is_dir());
std::fs::create_dir_all(root.join("Core/configs")).unwrap();
let path = root.join("Core/configs/worldserver.conf");
for original in [
@@ -604,74 +488,10 @@ mod tests {
}
#[test]
fn large_squid_provisioning_has_time_to_finish_without_extending_shutdown() {
let folder = tempfile::tempdir().unwrap();
let modules = folder.path().join("Core/configs/modules");
std::fs::create_dir_all(&modules).unwrap();
std::fs::write(
modules.join("playerbots.conf.dist"),
"AiPlayerbot.Enabled = 1\n",
)
.unwrap();
assert_eq!(
Verb::StartAll.timeout(folder.path()),
Duration::from_secs(2700)
);
assert_eq!(
Verb::StopAll.timeout(folder.path()),
Duration::from_secs(240)
);
std::fs::write(modules.join("playerbots.conf"), "AiPlayerbot.Enabled = 0\n").unwrap();
assert_eq!(
Verb::StartWorld.timeout(folder.path()),
Duration::from_secs(420)
);
}
#[test]
fn zero_filled_launcher_state_is_discarded_and_valid_state_is_kept() {
let folder = tempfile::tempdir().unwrap();
let state = folder.path().join(".state");
std::fs::create_dir_all(&state).unwrap();
std::fs::write(state.join("mysql.json"), vec![0u8; 116]).unwrap();
std::fs::write(state.join("configuration.json"), Vec::<u8>::new()).unwrap();
std::fs::write(state.join("world.json"), "{\"pid\": 4}\n").unwrap();
std::fs::write(state.join("stop-relay"), Vec::<u8>::new()).unwrap();
std::fs::write(state.join("auth.json"), "{\"pid\": 0}").unwrap();
let mut removed: Vec<_> = discard_damaged_launcher_state(folder.path())
.iter()
.map(|p| p.file_name().unwrap().to_string_lossy().into_owned())
.collect();
removed.sort();
assert_eq!(removed, ["configuration.json", "mysql.json"]);
assert!(
state.join("world.json").exists()
&& state.join("auth.json").exists()
&& state.join("stop-relay").exists()
);
assert!(discard_damaged_launcher_state(folder.path()).is_empty());
assert!(discard_damaged_launcher_state(&folder.path().join("missing")).is_empty());
}
#[test]
fn translates_known_launcher_messages() {
assert_eq!(
translate("RuntimeError: Port 8085 is already used. Stop the other server"),
ErrorCode::PortInUse
);
assert_eq!(
translate("Another start/stop action is in progress."),
ErrorCode::OperationInProgress
);
assert_eq!(
translate("The packaged database is missing. Extract the complete repack."),
ErrorCode::ServerFilesIncomplete
);
assert_eq!(
translate("world stopped during startup. Check its log."),
ErrorCode::StartupFailed
);
assert_eq!(translate("Exit code -1073741819"), ErrorCode::Unknown);
fn launcher_failures_carry_their_error_code() {
let e = Error::Service(ErrorCode::PortInUse, "Port 8085 is already used (PID 4).".into());
assert_eq!(e.code(), ErrorCode::PortInUse);
assert_eq!(e.to_string(), "Port 8085 is already used (PID 4).");
}
#[test]
@@ -714,13 +534,4 @@ mod tests {
assert!(!reason.contains("private"));
assert!(!reason.contains("Something went wrong"));
}
#[test]
fn launcher_import_fix_is_idempotent_and_retains_other_code() {
let text = "import sys\nROOT = Path(__file__).resolve().parents[1]\nfrom squid_playerbots import validate_bots\ncustom = 42\n";
let fixed = patch_launcher_imports(text).unwrap();
assert!(fixed.contains("sys.path.insert(0, str(Path(__file__).resolve().parent))"));
assert!(fixed.ends_with("custom = 42\n"));
assert_eq!(patch_launcher_imports(&fixed).unwrap(), fixed);
}
}
+4
View File
@@ -24,6 +24,9 @@ pub enum Error {
UnknownInstallation(String),
#[error("{0}")]
Invalid(String),
/// A server start or stop failed for a reason the UI can explain (the repack launcher's own errors).
#[error("{1}")]
Service(ErrorCode, String),
#[error("package not published: {0}")]
PackageNotPublished(String),
#[error("download server unreachable: {0}")]
@@ -199,6 +202,7 @@ impl Error {
Error::PackageNotPublished(_) => ErrorCode::PackageNotPublished,
Error::NetworkUnreachable(_) => ErrorCode::NetworkUnreachable,
Error::BotModulesConflict => ErrorCode::BotModulesConflict,
Error::Service(code, _) => *code,
Error::CompanionTemplatesMissing => ErrorCode::CompanionTemplatesMissing,
Error::CompanionCommandUnsupported => ErrorCode::CompanionCommandUnsupported,
_ => ErrorCode::Unknown,
+52 -15
View File
@@ -239,14 +239,14 @@ fn bootstrap_database_inner(root: &Path) -> Result<()> {
}
fs::copy(&boot, &target)?; // launcher needs database.json to render its files at first start
let started = driver::run(root, Verb::StartMysql)?;
if !started.ok {
return Err(Error::Invalid(format!(
"The database could not be started. {}",
driver::startup_failure(root, &started)
)));
}
let result = (|| -> Result<()> {
let started = driver::run(root, Verb::StartMysql)?;
if !started.ok {
return Err(Error::Invalid(format!(
"The database could not be started. {}",
driver::startup_failure(root, &started)
)));
}
let db = Db::from_repack(root, Account::Admin)?;
let (root_pw, app_pw) = (random_hex(48), random_hex(48));
let accounts = db.query(
@@ -362,6 +362,7 @@ pub fn install_base(p: &Params, report: &dyn Fn(Step)) -> Result<Installed> {
// 3. Extract into our own staging folder.
if staging_root.exists() {
if staging_root.join(MARKER).is_file() {
stop_installation(&staging_root)?;
fs::remove_dir_all(&staging_root)?; // leftover of an earlier failed attempt that we created
} else {
return Err(Error::Invalid(format!("{} is left over from an earlier installation that did not finish, and the Manager cannot tell whether it may be deleted. Delete that folder yourself, then try again.", staging_root.display())));
@@ -426,24 +427,60 @@ pub fn install_base(p: &Params, report: &dyn Fn(Step)) -> Result<Installed> {
})();
if result.is_err() {
if staging_root.join(MARKER).exists() {
// Unfinished work of ours; the destination was never touched.
let _ = driver::run(&staging_root, Verb::StopAll);
let _ = fs::remove_dir_all(&staging_root);
let unfinished = if staging_root.join(MARKER).is_file() {
Some(&staging_root)
} else if dest.join(MARKER).is_file() {
// Failed after the folder was moved into place. The destination was empty or absent before (preflight),
// so what carries our marker is only our unfinished install.
let _ = driver::run(&dest, Verb::StopAll);
let _ = fs::remove_dir_all(&dest);
Some(&dest)
} else {
None
};
if let Some(unfinished) = unfinished {
if let Err(cleanup) = stop_installation(unfinished) {
return Err(Error::Invalid(format!(
"{} {cleanup}",
result.as_ref().unwrap_err()
)));
}
let _ = fs::remove_dir_all(unfinished);
}
}
result
}
fn stop_installation(root: &Path) -> Result<()> {
if !root.join("Scripts/manage.py").is_file() {
return Ok(());
}
let stopped = driver::run(root, Verb::StopAll)?;
if !stopped.ok {
return Err(Error::Invalid(format!(
"The unfinished installation could not be stopped; its files were kept. {}",
driver::startup_failure(root, &stopped)
)));
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn an_unstoppable_partial_installation_keeps_its_files_for_recovery() {
let folder = tempfile::tempdir().unwrap();
let root = folder.path();
fs::create_dir_all(root.join("Scripts")).unwrap();
fs::write(root.join("Scripts/manage.py"), "# incomplete launcher").unwrap();
fs::write(root.join(MARKER), "").unwrap();
fs::write(root.join("database-preserved"), "unchanged").unwrap();
assert!(stop_installation(root).is_err());
assert_eq!(
fs::read_to_string(root.join("database-preserved")).unwrap(),
"unchanged"
);
assert!(root.join(MARKER).is_file());
}
fn reg(d: &Path) -> Registry {
Registry::at(d.join("reg/installs.json"))
}
+24
View File
@@ -0,0 +1,24 @@
//! The repack launcher in Rust: what `Scripts/manage.py` does, without Python.
//!
//! Formats on disk stay exactly those of `manage.py`, so the two can be used on the same server during the move
//! (an old `.bat` and a new Manager, or the other way round):
//!
//! * `.state/<service>.json` process records `{pid, exe, created}` (see [`crate::process::ProcessIdentity`]);
//! * `.state/control.lock` one start/stop action at a time: byte 0 locked, as `msvcrt.locking` does;
//! * `.state/control-owner.json`, `.state/configuration.json`, `.state/debug-logs.json`;
//! * the rendered configs (`Core/configs/*.conf`, `mysql/my.ini`, `mysql/admin-client.ini`) byte for byte.
//!
//! State files are written with a flush to disk before they replace the old ones (`manage.py` did not, and a
//! power cut could leave a zero-filled record that stopped every later start).
pub mod ops;
pub mod relay;
pub mod render;
pub mod services;
pub mod settings;
pub mod spawn;
pub mod squid;
pub mod state;
pub mod world;
pub use settings::Settings;
+88
View File
@@ -0,0 +1,88 @@
//! One start/stop action of a repack, with the control lock held (`manage.py main()`): the entry point of both
//! `coa-launcher.exe` and the Manager.
use std::path::Path;
use std::time::Duration;
use crate::error::Result;
use crate::launcher::services::{self, Progress};
use crate::launcher::world::{self, Supervisor};
use crate::launcher::{render, settings::Settings, squid, state};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Action {
StartAll,
StartMysql,
StartAuth,
StartWorld,
StopAll,
/// Stop the world without its console first (unsaved progress is lost), then everything else.
ForceStopAll,
Prepare,
}
impl Action {
/// The command name, as the `.bat` files and `manage.py` call it.
pub fn name(self) -> &'static str {
match self {
Action::StartAll => "start-all",
Action::StartMysql => "start-mysql",
Action::StartAuth => "start-auth",
Action::StartWorld => "start-world",
Action::StopAll => "stop-all",
Action::ForceStopAll => "force-stop-all",
Action::Prepare => "prepare",
}
}
pub fn parse(name: &str) -> Option<Action> {
[
Action::StartAll,
Action::StartMysql,
Action::StartAuth,
Action::StartWorld,
Action::StopAll,
Action::ForceStopAll,
Action::Prepare,
]
.into_iter()
.find(|a| a.name() == name)
}
}
/// Run `action`. A started world is supervised by `supervisor`, or by what the repack ships when it is `None`.
pub fn run(root: &Path, cfg: &Settings, offset: i32, action: Action, supervisor: Option<&Supervisor>, progress: Progress) -> Result<()> {
let _lock = state::ControlLock::acquire(root, action.name(), Duration::from_secs(30), progress)?;
match action {
// Shutdown uses the existing client and console settings: the templates may be exactly what a recovery
// needs to replace, so nothing is rendered.
Action::StopAll => return services::stop_all(root, cfg, progress),
Action::ForceStopAll => return services::force_stop_all(root, cfg, progress),
_ => {}
}
if matches!(action, Action::StartAll | Action::StartWorld) {
squid::validate_bots(root)?;
}
render::prepare(root, cfg)?;
if action == Action::Prepare {
return Ok(());
}
if matches!(action, Action::StartAll | Action::StartMysql) {
services::start_mysql(root, cfg, progress)?;
}
if matches!(action, Action::StartAll | Action::StartAuth) {
services::start_auth(root, cfg, progress)?;
}
if matches!(action, Action::StartAll | Action::StartWorld) {
let shipped;
let supervisor = match supervisor {
Some(s) => s,
None => {
shipped = Supervisor::of(root)?;
&shipped
}
};
world::start_world(root, cfg, offset, supervisor, progress)?;
}
Ok(())
}
+493
View File
@@ -0,0 +1,493 @@
//! The bug-report relay (`BugReport/relay.py` and `manage.py relay-worker`): delivers the reports the world
//! writes to `BugReport/reports/*.report` through the CoA report service.
//!
//! On disk everything stays as the Python relay keeps it, so either can take over a spool: the `<key>.status`
//! files the world reads back, the delivery journal `relay.sqlite3` (tables `deliveries` and `settings`), and
//! `relay.lock` (byte 0 locked while a worker runs). A delivery interrupted while it was posting becomes
//! `uncertain` and is never sent again (the service's duplicate filter may have been reset in the meantime).
use std::path::{Path, PathBuf};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use rusqlite::{params, Connection, OptionalExtension};
use sha2::{Digest, Sha256};
use crate::error::{Error, Result};
use crate::launcher::state;
const REPOSITORY: &str = "jealous-sound/azerothcore-wotlk-coa";
pub const SERVICE_URL: &str = "https://coa-bug-report.up.railway.app";
/// Distribution credential for this narrow intake API (the same as relay.py's); not a GitHub token.
pub const DEFAULT_API_KEY: &str = "coa_zRatxUHShOn-HEkoreKGME6sd3DdMG7eKTTKlj2JCK4";
const MAX_FILE: u64 = 16000;
const MAX_RESPONSE: usize = 64 * 1024;
/// `[1-9][0-9]{0,9}-[0-9a-f]{16,48}`: the name of a report file (without `.report`).
pub fn valid_key(key: &str) -> bool {
let Some((id, hex)) = key.split_once('-') else { return false };
(1..=10).contains(&id.len())
&& !id.starts_with('0')
&& id.bytes().all(|b| b.is_ascii_digit())
&& (16..=48).contains(&hex.len())
&& hex.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
}
/// Why a delivery did not create an issue. Only fixed local codes: never service bodies, credentials or report
/// content.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Failure {
/// 202 pending: the service is still creating it.
Pending(u64),
/// 429: try again later.
Limited(u64),
/// The report itself was refused.
Invalid,
/// The service refused this relay (redirect, auth, missing endpoint, GitHub access).
Blocked(u64),
/// The outcome is unknown (network, timeout, unexpected answer).
Uncertain,
}
/// Where reports go.
pub trait Service {
fn create(&self, title: &str, body: &str) -> std::result::Result<u64, Failure>;
}
/// The CoA report service over HTTPS.
pub struct ReportService {
api: String,
key: String,
client: reqwest::blocking::Client,
}
impl ReportService {
pub fn new(base_url: &str, api_key: &str) -> Result<ReportService> {
if api_key.is_empty() || !api_key.is_ascii() || api_key.chars().any(char::is_whitespace) {
return Err(Error::Invalid("Configure a valid report-service intake key.".into()));
}
let client = reqwest::blocking::Client::builder()
.redirect(reqwest::redirect::Policy::none())
.timeout(Duration::from_secs(30))
// One report every few seconds at most: a fresh connection each time, never a stale pooled one.
.pool_max_idle_per_host(0)
.user_agent("CoA-InGame-BugReport/1")
.build()
.map_err(|e| Error::Invalid(format!("The report client could not start: {e}")))?;
Ok(ReportService { api: format!("{base_url}/v1/reports"), key: api_key.into(), client })
}
}
/// `Retry-After` in seconds, kept within 1 s .. 1 day; `default` when absent or not a number.
fn retry_delay(retry_after: Option<&str>, default: u64) -> u64 {
retry_after.and_then(|v| v.trim().parse::<i64>().ok()).map_or(default, |v| v.clamp(1, 86400) as u64)
}
/// A JSON object of at most 64 KiB, or nothing.
fn json_object(raw: Option<&[u8]>) -> Option<serde_json::Map<String, serde_json::Value>> {
let raw = raw?;
if raw.len() > MAX_RESPONSE {
return None;
}
match serde_json::from_slice(raw).ok()? {
serde_json::Value::Object(map) => Some(map),
_ => None,
}
}
fn issue_number(data: &serde_json::Map<String, serde_json::Value>) -> std::result::Result<u64, Failure> {
let number = data.get("issue_number").and_then(|n| if n.is_u64() { n.as_u64() } else { None });
match number {
Some(n)
if data.get("status").and_then(|s| s.as_str()) == Some("created")
&& (1..=4294967295).contains(&n)
&& data.get("issue_url").and_then(|u| u.as_str())
== Some(format!("https://github.com/{REPOSITORY}/issues/{n}").as_str()) =>
{
Ok(n)
}
_ => Err(Failure::Uncertain),
}
}
/// What a service answer means (relay.py's `create`): the status, its `Retry-After` and its body (`None` when it
/// could not be read or was longer than 64 KiB).
pub fn classify(status: u16, retry_after: Option<&str>, body: Option<&[u8]>) -> std::result::Result<u64, Failure> {
let field = |data: &serde_json::Map<String, serde_json::Value>, k: &str| data.get(k).and_then(|v| v.as_str()).map(str::to_owned);
match status {
200..=202 => {
let data = json_object(body).ok_or(Failure::Uncertain)?;
match status {
202 if field(&data, "status").as_deref() == Some("pending") => Err(Failure::Pending(retry_delay(retry_after, 2))),
202 => Err(Failure::Uncertain),
_ => issue_number(&data),
}
}
429 => Err(Failure::Limited(retry_delay(retry_after, 300))),
400 | 413 | 415 | 422 => Err(Failure::Invalid),
301 | 302 | 303 | 307 | 308 | 401 | 403 | 404 | 405 => Err(Failure::Blocked(300)),
503 => {
let data = json_object(body).unwrap_or_default();
if field(&data, "status").as_deref() == Some("failed") && field(&data, "error").as_deref() == Some("github_access_denied") {
Err(Failure::Blocked(retry_delay(retry_after, 300)))
} else {
Err(Failure::Uncertain)
}
}
_ => Err(Failure::Uncertain),
}
}
impl Service for ReportService {
fn create(&self, title: &str, body: &str) -> std::result::Result<u64, Failure> {
use std::io::Read;
let sent = self
.client
.post(&self.api)
.header("Authorization", format!("Bearer {}", self.key))
.header("Accept", "application/json")
.header("Content-Type", "application/json")
.body(serde_json::json!({ "title": title, "body": body }).to_string())
.send();
let response = sent.map_err(|_| Failure::Uncertain)?;
let status = response.status().as_u16();
let retry_after = response.headers().get("Retry-After").and_then(|v| v.to_str().ok()).map(str::to_owned);
let mut raw = Vec::new();
let read = response.take(MAX_RESPONSE as u64 + 1).read_to_end(&mut raw).is_ok() && raw.len() <= MAX_RESPONSE;
classify(status, retry_after.as_deref(), read.then_some(raw.as_slice()))
}
}
/// A report: `COABUG1\n<title>\n<body>`, checked as the world writes it.
pub struct Report {
pub digest: String,
pub marker: String,
pub title: String,
pub body: String,
}
pub fn read_report(path: &Path) -> Result<Report> {
let bad = || Error::Invalid("Invalid report file".into());
let key = path.file_stem().and_then(|s| s.to_str()).ok_or_else(bad)?;
let meta = std::fs::symlink_metadata(path)?;
if !valid_key(key) || meta.file_type().is_symlink() || meta.len() > MAX_FILE {
return Err(bad());
}
let raw = std::fs::read(path)?;
let text = String::from_utf8(raw.clone()).map_err(|_| bad())?.replace("\r\n", "\n");
let rest = text.strip_prefix("COABUG1\n").ok_or_else(|| Error::Invalid("Unsupported report format".into()))?;
let invalid = || Error::Invalid("Invalid report content".into());
let (title, body) = rest.split_once('\n').ok_or_else(invalid)?;
if !(3..=200).contains(&title.len())
|| body.trim().is_empty()
|| title.chars().any(|c| (c as u32) < 32)
|| body.chars().any(|c| (c as u32) < 32 && !matches!(c, '\r' | '\n' | '\t'))
{
return Err(invalid());
}
let digest = hex(&Sha256::digest(&raw));
let id = hex(&Sha256::digest(format!("{key}:{digest}").as_bytes()));
Ok(Report { digest, marker: format!("<!-- coa-report:{id} -->"), title: title.into(), body: body.into() })
}
fn hex(bytes: &[u8]) -> String {
bytes.iter().map(|b| format!("{b:02x}")).collect()
}
/// `<key>.status`: what the world shows the player (`queued`, `created|<issue>`, `failed`, ...).
pub fn write_status(spool: &Path, key: &str, state: &str, number: Option<u64>) -> Result<()> {
let value = match (state, number) {
("created", Some(n)) => format!("created|{n}"),
("created", None) => "created|None".into(),
_ => state.to_string(),
};
let data = format!("{value}\n");
let destination = spool.join(format!("{key}.status"));
if std::fs::read(&destination).is_ok_and(|d| d == data.as_bytes()) {
return Ok(());
}
crate::fsx::atomic_write(&destination, data.as_bytes())
}
fn now() -> f64 {
SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs_f64()).unwrap_or(0.0)
}
/// The delivery journal of one spool.
pub struct Relay<S: Service> {
spool: PathBuf,
service: S,
db: Connection,
clock: Box<dyn Fn() -> f64 + Send>,
}
impl<S: Service> Relay<S> {
pub fn open(spool: &Path, service: S) -> Result<Relay<S>> {
Self::with_clock(spool, service, Box::new(now))
}
pub fn with_clock(spool: &Path, service: S, clock: Box<dyn Fn() -> f64 + Send>) -> Result<Relay<S>> {
let db = Connection::open(spool.join("relay.sqlite3")).map_err(sql)?;
db.execute_batch(
"PRAGMA synchronous=FULL;
CREATE TABLE IF NOT EXISTS deliveries (
key TEXT PRIMARY KEY, digest TEXT NOT NULL, marker TEXT NOT NULL, state TEXT NOT NULL,
number INTEGER, attempted REAL NOT NULL DEFAULT 0, next_try REAL NOT NULL DEFAULT 0
);
CREATE TABLE IF NOT EXISTS settings (key TEXT PRIMARY KEY, value REAL NOT NULL);
UPDATE deliveries SET state='uncertain' WHERE state='posting';",
)
.map_err(sql)?;
Ok(Relay { spool: spool.into(), service, db, clock })
}
fn set_state(&self, key: &str, state: &str, number: Option<u64>, delay: u64) -> Result<()> {
self.db
.execute(
"UPDATE deliveries SET state=?1, number=?2, next_try=?3 WHERE key=?4",
params![state, number.map(|n| n as i64), (self.clock)() + delay as f64, key],
)
.map_err(sql)?;
write_status(&self.spool, key, state, number)
}
fn set_network_gate(&self, delay: u64) -> Result<()> {
self.db
.execute("INSERT OR REPLACE INTO settings VALUES('next_network',?1)", params![(self.clock)() + delay as f64])
.map_err(sql)?;
Ok(())
}
/// Handle one report file; returns its delivery state.
pub fn process(&self, path: &Path) -> Result<String> {
let Some(key) = path.file_stem().and_then(|s| s.to_str()).filter(|k| valid_key(k)) else {
return Ok("ignored".into());
};
let report = match read_report(path) {
Ok(r) => r,
Err(_) => {
write_status(&self.spool, key, "failed", None)?;
return Ok("failed".into());
}
};
self.db
.execute(
"INSERT OR IGNORE INTO deliveries(key,digest,marker,state) VALUES(?1,?2,?3,'queued')",
params![key, report.digest, report.marker],
)
.map_err(sql)?;
let (digest, row_state, number, next_try): (String, String, Option<i64>, f64) = self
.db
.query_row("SELECT digest, state, number, next_try FROM deliveries WHERE key=?1", params![key], |r| {
Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?))
})
.map_err(sql)?;
let number = number.map(|n| n as u64);
if digest != report.digest {
// Never replace an existing delivery or publish edited content under the same ID.
write_status(&self.spool, key, "failed", None)?;
return Ok("changed".into());
}
if matches!(row_state.as_str(), "created" | "failed" | "uncertain") {
write_status(&self.spool, key, &row_state, number)?;
return Ok(row_state);
}
if next_try > (self.clock)() {
write_status(&self.spool, key, &row_state, None)?;
return Ok(row_state);
}
let gate: Option<f64> = self
.db
.query_row("SELECT value FROM settings WHERE key='next_network'", [], |r| r.get(0))
.optional()
.map_err(sql)?;
if gate.is_some_and(|g| g > (self.clock)()) {
write_status(&self.spool, key, &row_state, None)?;
return Ok(row_state);
}
self.set_network_gate(5)?;
// A crash after this point needs review: the service's duplicate cache can reset on deploy.
self.db
.execute("UPDATE deliveries SET state='posting', attempted=?1 WHERE key=?2", params![(self.clock)(), key])
.map_err(sql)?;
match self.service.create(&report.title, &report.body) {
Ok(n) => {
self.set_state(key, "created", Some(n), 0)?;
Ok("created".into())
}
Err(failure) => {
let (state, delay) = match failure {
Failure::Limited(d) | Failure::Pending(d) => ("queued", d),
Failure::Blocked(d) => ("blocked", d),
Failure::Invalid => ("failed", 300),
Failure::Uncertain => ("uncertain", 300),
};
self.set_state(key, state, None, delay)?;
if let Failure::Limited(d) | Failure::Blocked(d) = failure {
self.set_network_gate(d)?;
}
Ok(state.into())
}
}
}
/// One pass over the spool, in name order.
pub fn pass(&self) -> Result<()> {
let mut reports: Vec<PathBuf> = std::fs::read_dir(&self.spool)?
.flatten()
.map(|e| e.path())
.filter(|p| p.extension().is_some_and(|x| x == "report"))
.collect();
reports.sort();
for path in reports {
self.process(&path)?;
}
Ok(())
}
}
fn sql(e: rusqlite::Error) -> Error {
Error::Invalid(format!("The bug-report journal failed ({e})."))
}
/// `relay-worker`: deliver reports until the supervisor asks the relay to stop (`.state/stop-relay`).
pub fn worker(root: &Path) -> Result<()> {
let spool = root.join("BugReport/reports");
std::fs::create_dir_all(&spool)?;
let _lock = state::FileLock::try_acquire(&spool.join("relay.lock"))?
.ok_or_else(|| Error::Invalid("Another bug-report relay is already using this spool.".into()))?;
let key = std::env::var("COA_BUGREPORT_API_KEY").unwrap_or_else(|_| DEFAULT_API_KEY.into());
let relay = Relay::open(&spool, ReportService::new(SERVICE_URL, &key)?)?;
state::record(root, "relay-ready", std::process::id())?;
println!("Bug-report relay ready. Waiting for in-game reports.");
let stop = state::dir(root).join("stop-relay");
while !stop.exists() {
relay.pass()?;
for _ in 0..10 {
if stop.exists() {
return Ok(());
}
std::thread::sleep(Duration::from_millis(500));
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::{Arc, Mutex};
type Answers = Arc<Mutex<Vec<std::result::Result<u64, Failure>>>>;
struct Fake(Answers, Arc<Mutex<u32>>);
impl Service for Fake {
fn create(&self, _: &str, _: &str) -> std::result::Result<u64, Failure> {
*self.1.lock().unwrap() += 1;
self.0.lock().unwrap().remove(0)
}
}
fn report(spool: &Path, key: &str, text: &str) -> PathBuf {
let p = spool.join(format!("{key}.report"));
std::fs::write(&p, text).unwrap();
p
}
#[test]
fn keys_follow_the_world_format() {
assert!(valid_key("1-0123456789abcdef"));
assert!(valid_key("4294967295-0123456789abcdef0123456789abcdef0123456789abcdef"));
for bad in ["0-0123456789abcdef", "1-0123456789abcde", "1-0123456789ABCDEF", "12345678901-0123456789abcdef", "x"] {
assert!(!valid_key(bad), "{bad}");
}
}
#[test]
fn service_answers_map_like_relay_py() {
let ok = format!(r#"{{"status":"created","issue_number":12,"issue_url":"https://github.com/{REPOSITORY}/issues/12"}}"#);
let cases: Vec<(u16, Option<&str>, Option<&[u8]>, std::result::Result<u64, Failure>)> = vec![
(201, None, Some(ok.as_bytes()), Ok(12)),
(200, None, Some(ok.as_bytes()), Ok(12)),
(201, None, Some(br#"{"status":"created","issue_number":12,"issue_url":"https://evil/12"}"#), Err(Failure::Uncertain)),
(201, None, Some(br#"{"status":"created","issue_number":0,"issue_url":"x"}"#), Err(Failure::Uncertain)),
(201, None, Some(b"[1]"), Err(Failure::Uncertain)),
(201, None, None, Err(Failure::Uncertain)),
(202, Some("7"), Some(br#"{"status":"pending"}"#), Err(Failure::Pending(7))),
(202, None, Some(br#"{"status":"pending"}"#), Err(Failure::Pending(2))),
(202, None, Some(br#"{"status":"other"}"#), Err(Failure::Uncertain)),
(429, Some("999999"), None, Err(Failure::Limited(86400))),
(429, Some("0"), None, Err(Failure::Limited(1))),
(429, Some("soon"), None, Err(Failure::Limited(300))),
(422, None, None, Err(Failure::Invalid)),
(302, None, None, Err(Failure::Blocked(300))),
(401, None, None, Err(Failure::Blocked(300))),
(503, Some("30"), Some(br#"{"status":"failed","error":"github_access_denied"}"#), Err(Failure::Blocked(30))),
(503, None, Some(b"{}"), Err(Failure::Uncertain)),
(500, None, None, Err(Failure::Uncertain)),
];
for (i, (status, retry, body, expected)) in cases.into_iter().enumerate() {
assert_eq!(classify(status, retry, body), expected, "case {i}");
}
assert!(json_object(Some(&vec![b' '; MAX_RESPONSE + 1])).is_none(), "oversized answers are refused");
assert!(ReportService::new(SERVICE_URL, "has space").is_err());
assert!(ReportService::new(SERVICE_URL, "coa_key").is_ok());
}
#[test]
fn a_report_is_checked_and_identified_like_relay_py() {
let d = tempfile::tempdir().unwrap();
let p = report(d.path(), "7-0123456789abcdef", "COABUG1\r\nBroken quest\r\nThe NPC is missing.\r\n");
let r = read_report(&p).unwrap();
assert_eq!(r.title, "Broken quest");
assert_eq!(r.body, "The NPC is missing.\n");
assert_eq!(r.digest, hex(&Sha256::digest(std::fs::read(&p).unwrap())));
assert!(r.marker.starts_with("<!-- coa-report:") && r.marker.len() == 16 + 64 + 4);
for bad in ["COABUG2\nTitle\nBody", "COABUG1\nab\nBody", "COABUG1\nTitle\n \n", "COABUG1\nTi\u{7}tle\nBody", "COABUG1\nTitle"] {
std::fs::write(&p, bad).unwrap();
assert!(read_report(&p).is_err(), "{bad:?}");
}
}
#[test]
fn deliveries_follow_the_journal() {
let d = tempfile::tempdir().unwrap();
let spool = d.path();
let t = Arc::new(Mutex::new(1000.0f64));
let calls = Arc::new(Mutex::new(0));
let answers: Answers = Arc::new(Mutex::new(vec![Err(Failure::Limited(60)), Ok(42)]));
let clock = t.clone();
let relay = Relay::with_clock(spool, Fake(answers, calls.clone()), Box::new(move || *clock.lock().unwrap())).unwrap();
let p = report(spool, "7-0123456789abcdef", "COABUG1\nBroken quest\nThe NPC is missing.\n");
let status = || std::fs::read_to_string(spool.join("7-0123456789abcdef.status")).unwrap();
assert_eq!(relay.process(&p).unwrap(), "queued", "429 keeps it queued");
assert_eq!(status(), "queued\n");
assert_eq!(relay.process(&p).unwrap(), "queued", "not before its retry time");
assert_eq!(*calls.lock().unwrap(), 1);
*t.lock().unwrap() += 61.0;
assert_eq!(relay.process(&p).unwrap(), "created");
assert_eq!(status(), "created|42\n");
assert_eq!(relay.process(&p).unwrap(), "created", "never sent twice");
assert_eq!(*calls.lock().unwrap(), 2);
std::fs::write(&p, "COABUG1\nBroken quest\nEdited.\n").unwrap();
assert_eq!(relay.process(&p).unwrap(), "changed");
relay
.db
.execute("INSERT INTO deliveries(key,digest,marker,state) VALUES('8-0123456789abcdef','x','m','posting')", [])
.unwrap();
drop(relay);
let reopened = Relay::open(spool, Fake(Arc::new(Mutex::new(vec![])), calls.clone())).unwrap();
let state: String =
reopened.db.query_row("SELECT state FROM deliveries WHERE key='8-0123456789abcdef'", [], |r| r.get(0)).unwrap();
assert_eq!(state, "uncertain", "an interrupted post is never retried");
}
#[test]
fn a_second_worker_cannot_take_the_spool() {
let d = tempfile::tempdir().unwrap();
let first = state::FileLock::try_acquire(&d.path().join("relay.lock")).unwrap();
assert!(first.is_some());
assert!(state::FileLock::try_acquire(&d.path().join("relay.lock")).unwrap().is_none());
drop(first);
assert!(state::FileLock::try_acquire(&d.path().join("relay.lock")).unwrap().is_some());
}
}
+271
View File
@@ -0,0 +1,271 @@
//! `prepare`: the configuration files a repack runs with, rendered from `Settings/*.template` and
//! `Settings/repack.json` (`manage.py prepare()`), byte for byte the same.
use std::path::{Path, PathBuf};
use crate::error::{Error, Result};
use crate::launcher::{settings::Settings, state};
/// Services whose running process blocks moving the folder or changing ports.
const SERVICES: [&str; 5] = ["mysql", "auth", "world", "supervisor", "relay"];
/// The root as the servers see it: forward slashes, and the short (8.3) form when the real one has non-Latin
/// letters, which MySQL and the servers do not read reliably from their config files.
pub fn native_root(root: &Path) -> Result<String> {
let mut value = root.to_string_lossy().into_owned();
if !value.is_ascii() {
if let Some(short) = sys::short_path(root) {
value = short;
}
}
if !value.is_ascii() {
return Err(Error::Invalid(
"Extract the repack to a path with Latin letters, such as C:\\Games\\CoA-Repack.".into(),
));
}
Ok(value.replace('\\', "/"))
}
/// Text as Python's text mode reads it: strict UTF-8, Windows and old Mac line ends turned into "\n".
fn read_text(path: &Path) -> Result<String> {
let bytes = std::fs::read(path)?;
let text = String::from_utf8(bytes).map_err(|_| Error::Invalid(format!("{} is not UTF-8 text.", path.display())))?;
Ok(text.replace("\r\n", "\n").replace('\r', "\n"))
}
/// Text written as Python's text mode writes it on Windows: "\n" becomes "\r\n".
fn windows_text(text: &str) -> Vec<u8> {
if cfg!(windows) {
text.replace('\n', "\r\n").into_bytes()
} else {
text.as_bytes().to_vec()
}
}
fn placeholders(line: &str) -> Vec<String> {
let mut out = Vec::new();
let bytes = line.as_bytes();
let mut i = 0;
while i < bytes.len() {
if bytes[i] == b'@' {
let mut j = i + 1;
while j < bytes.len() && (bytes[j].is_ascii_alphabetic() || bytes[j] == b'_') {
j += 1;
}
if j < bytes.len() && j > i + 1 && bytes[j] == b'@' {
out.push(line[i..=j].to_string());
i = j + 1;
continue;
}
}
i += 1;
}
out
}
fn credentials(root: &Path) -> Result<(String, String)> {
let v: serde_json::Value = crate::fsx::read_json(&root.join("Settings/database.json"))?;
let good = |k: &str| {
v.get(k)
.and_then(|x| x.as_str())
.filter(|s| s.len() == 48 && s.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)))
.map(str::to_string)
};
match (good("rootPassword"), good("appPassword")) {
(Some(r), Some(a)) => Ok((r, a)),
_ => Err(Error::Invalid("Invalid packaged database configuration.".into())),
}
}
/// Render every file the repack's services read. Refuses while a service runs and the folder or the ports
/// changed since the last render.
pub fn prepare(root: &Path, config: &Settings) -> Result<Vec<PathBuf>> {
let base = native_root(root)?;
let signature = serde_json::json!({
"root": root.to_string_lossy(),
"ports": serde_json::Value::Object(config.port_map()),
});
let previous = state::dir(root).join("configuration.json");
if previous.exists() {
let recorded: Option<serde_json::Value> = crate::fsx::read_json(&previous).ok();
if recorded.as_ref() != Some(&signature) && SERVICES.iter().any(|s| state::running(root, s).is_some()) {
return Err(Error::Invalid("Stop this repack before moving its folder or changing its ports.".into()));
}
}
let (root_password, app_password) = credentials(root)?;
for folder in ["Core/configs/modules", "Core/Logs", "BugReport/reports", "BugReport/Logs", "mysql/logs", ".state"] {
std::fs::create_dir_all(root.join(folder))?;
}
let mysql_port = config.mysql_port;
let mut values: Vec<(&str, String)> = vec![
("DATA", format!("{base}/Data")),
("LOGS", format!("{base}/Core/Logs")),
("ASCENSION_DBC", format!("{base}/Data/dbc/Ascension")),
("MYSQL_EXE", format!("{base}/mysql/bin/mysql.exe")),
("AUTH_PORT", config.auth_port.to_string()),
("WORLD_PORT", config.world_port.to_string()),
("RA_PORT", config.ra_port.to_string()),
];
for (key, db) in [
("LoginDatabaseInfo", "acore_auth"),
("WorldDatabaseInfo", config.realm.world_db),
("CharacterDatabaseInfo", config.realm.characters_db),
] {
values.push((key, format!("127.0.0.1;{mysql_port};acore;{app_password};{db}")));
}
let mut written = Vec::new();
for (name, target) in [
("authserver.conf", "Core/configs/authserver.conf"),
("worldserver.conf", "Core/configs/worldserver.conf"),
("mod_ascension_compat.conf", "Core/configs/modules/mod_ascension_compat.conf"),
] {
let mut text = read_text(&root.join("Settings").join(format!("{name}.template")))?;
for (key, value) in &values {
text = text.replace(&format!("@{key}@"), value);
}
let mut unresolved: Vec<String> = text
.split('\n')
.filter(|l| !l.trim().is_empty() && !l.trim_start().starts_with('#'))
.flat_map(placeholders)
.collect();
unresolved.sort();
unresolved.dedup();
if !unresolved.is_empty() {
return Err(Error::Service(
crate::error::ErrorCode::InvalidConfigValue,
format!("An unresolved placeholder remains in Settings/{name}.template: {}", unresolved.join(", ")),
));
}
// these three keep "\n" (Python wrote them with newline="\n")
std::fs::write(root.join(target), text.as_bytes())?;
written.push(root.join(target));
}
let files: [(&str, String); 3] = [
(
"Core/configs/modules/coa_bugreport.conf",
format!(
"# Managed by the repack launcher. Enabled whenever worldserver starts.\nCoABugReport.Enable = 1\nCoABugReport.SpoolDirectory = \"{base}/BugReport/reports\"\nCoABugReport.CooldownSeconds = 120\n"
),
),
(
"mysql/my.ini",
format!(
"[mysqld]\nbasedir=\"{base}/mysql\"\ndatadir=\"{base}/mysql/data\"\nport={mysql_port}\nbind-address=127.0.0.1\nmysqlx=0\ncharacter-set-server=utf8mb4\ncollation-server=utf8mb4_unicode_ci\nmax_allowed_packet=128M\ninnodb_buffer_pool_size=256M\nskip-log-bin\nlog-error=\"{base}/mysql/logs/mysql-error.log\"\npid-file=\"{base}/mysql/mysql.pid\"\n"
),
),
(
"mysql/admin-client.ini",
format!(
"[client]\nuser=root\npassword={root_password}\nhost=127.0.0.1\nport={mysql_port}\nprotocol=tcp\ndefault-character-set=utf8mb4\n"
),
),
];
for (rel, text) in files {
std::fs::write(root.join(rel), windows_text(&text))?;
written.push(root.join(rel));
}
state::write_json(&previous, &signature)?;
Ok(written)
}
#[cfg(windows)]
mod sys {
use std::os::windows::ffi::OsStrExt;
use std::path::Path;
use windows_sys::Win32::Storage::FileSystem::GetShortPathNameW;
pub fn short_path(path: &Path) -> Option<String> {
let wide: Vec<u16> = path.as_os_str().encode_wide().chain(Some(0)).collect();
let mut buf = vec![0u16; 32768];
let n = unsafe { GetShortPathNameW(wide.as_ptr(), buf.as_mut_ptr(), buf.len() as u32) };
(n > 0 && (n as usize) < buf.len()).then(|| String::from_utf16_lossy(&buf[..n as usize]))
}
}
#[cfg(not(windows))]
mod sys {
pub fn short_path(_: &std::path::Path) -> Option<String> {
None
}
}
#[cfg(test)]
mod tests {
use super::*;
pub(crate) fn fixture(root: &Path) {
let w = |rel: &str, text: &[u8]| {
let p = root.join(rel);
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
std::fs::write(p, text).unwrap();
};
w("Settings/repack.json", br#"{"authPort": 3724, "mysqlPort": 3307, "raPassword": "e0c39beaa5c14128", "raPort": 3443, "raUsername": "COAMANAGER", "worldPort": 8085}"#);
w("Settings/database.json", format!(r#"{{"rootPassword": "{}", "appPassword": "{}"}}"#, "a".repeat(48), "0123456789abcdef".repeat(3)).as_bytes());
w("Settings/authserver.conf.template", b"[authserver]\r\nLoginDatabaseInfo = \"@LoginDatabaseInfo@\"\r\nRealmServerPort = @AUTH_PORT@\r\nLogsDir = \"@LOGS@\"\r\n# @NOT_A_VALUE@ in a comment is fine\r\n");
w("Settings/worldserver.conf.template", "[worldserver]\nDataDir = \"@DATA@\"\nWorldServerPort = @WORLD_PORT@\nRa.Port = @RA_PORT@\nWorldDatabaseInfo = \"@WorldDatabaseInfo@\"\nCharacterDatabaseInfo = \"@CharacterDatabaseInfo@\"\nMySQLExecutable = \"@MYSQL_EXE@\"\nMotd = \"Ünïcode stays\"\n".as_bytes());
w("Settings/mod_ascension_compat.conf.template", b"Ascension.DbcDir = \"@ASCENSION_DBC@\"\rOld.Mac = 1\r");
}
#[test]
fn placeholders_left_outside_comments_are_refused() {
let d = tempfile::tempdir().unwrap();
fixture(d.path());
std::fs::write(d.path().join("Settings/worldserver.conf.template"), "A = @UNKNOWN@\n").unwrap();
let cfg = Settings::load(d.path(), 0).unwrap();
let err = prepare(d.path(), &cfg).unwrap_err().to_string();
assert!(err.contains("worldserver.conf.template: @UNKNOWN@"), "{err}");
}
#[test]
fn a_bad_password_file_is_refused() {
let d = tempfile::tempdir().unwrap();
fixture(d.path());
std::fs::write(d.path().join("Settings/database.json"), r#"{"rootPassword":"short","appPassword":"x"}"#).unwrap();
let cfg = Settings::load(d.path(), 0).unwrap();
assert!(prepare(d.path(), &cfg).unwrap_err().to_string().contains("Invalid packaged database configuration"));
}
/// Byte-for-byte the same files as the Python launcher. COA_MANAGE_PY = a manage.py to compare with (taken from
/// coa-server-build); skipped without it.
#[test]
fn renders_exactly_what_manage_py_renders() {
let Ok(manage) = std::env::var("COA_MANAGE_PY") else { return };
let python = std::env::var("COA_PYTHON").unwrap_or_else(|_| "python".into());
let rust = tempfile::tempdir().unwrap();
let py = tempfile::tempdir().unwrap();
for d in [rust.path(), py.path()] {
fixture(d);
}
std::fs::create_dir_all(py.path().join("Scripts")).unwrap();
std::fs::copy(&manage, py.path().join("Scripts/manage.py")).unwrap();
// manage.py imports squid_playerbots lazily; prepare does not need it.
let out = std::process::Command::new(&python)
.args(["-I", "-B"])
.arg(py.path().join("Scripts/manage.py"))
.arg("prepare")
.output()
.unwrap();
assert!(out.status.success(), "{}{}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr));
let cfg = Settings::load(rust.path(), 0).unwrap();
let written = prepare(rust.path(), &cfg).unwrap();
let root_text = |p: &Path, base: &Path| {
let n = native_root(base).unwrap();
String::from_utf8(std::fs::read(p).unwrap()).unwrap().replace(&n, "<ROOT>")
};
for file in &written {
let rel = file.strip_prefix(rust.path()).unwrap();
assert_eq!(
root_text(file, rust.path()),
root_text(&py.path().join(rel), py.path()),
"{} differs",
rel.display()
);
}
let sig = |base: &Path| -> serde_json::Value {
let mut v: serde_json::Value = crate::fsx::read_json(&base.join(".state/configuration.json")).unwrap();
v["root"] = serde_json::Value::Null;
v
};
assert_eq!(sig(rust.path()), sig(py.path()));
}
}
+571
View File
@@ -0,0 +1,571 @@
//! Starting, checking and stopping the services of one repack: MySQL, authserver, worldserver
//! (`manage.py start_mysql`, `start_auth`, `stop_all` and their helpers), with the same rules.
use std::net::{SocketAddr, TcpStream};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::time::{Duration, Instant};
use crate::error::{Error, ErrorCode, Result};
use crate::launcher::{settings::Settings, state};
use crate::process::ProcessIdentity;
pub type Progress<'a> = &'a dyn Fn(&str);
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
const CREATE_NEW_PROCESS_GROUP: u32 = 0x0000_0200;
fn hidden(cmd: &mut Command) -> &mut Command {
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
cmd.creation_flags(CREATE_NO_WINDOW | CREATE_NEW_PROCESS_GROUP);
}
cmd
}
/// Start `exe` with its output appended to `log`, and record it as `name`. `env_remove` are variables of this
/// process the service must not see.
pub fn spawn(root: &Path, name: &str, exe: &Path, args: &[&str], cwd: &Path, log: &Path, env_remove: &[String]) -> Result<ProcessIdentity> {
let child = crate::launcher::spawn::start(exe, args, cwd, log, env_remove)?;
state::record(root, name, child.pid)
}
// ---------------------------------------------------------------------------------------------------------------
// Ports
// ---------------------------------------------------------------------------------------------------------------
/// Wait (up to 30 s) until `port` can be bound by a new server. A port with a listening owner is refused at
/// once; a port Windows still holds for a stopped process (a PID-zero row) is waited for. The test bind is
/// exclusive (`SO_EXCLUSIVEADDRUSE`), never a shared one.
pub fn ensure_free(port: u16, progress: Progress) -> Result<()> {
let deadline = Instant::now() + Duration::from_secs(30);
let mut announced = false;
loop {
let mut owners: Vec<u32> = sys::tcp_rows_v4()
.into_iter()
.filter(|r| r.state == sys::LISTEN && r.local_port == port)
.map(|r| r.pid)
.collect();
owners.sort_unstable();
owners.dedup();
if owners.iter().any(|p| *p != 0) {
let list: Vec<String> = owners.iter().map(u32::to_string).collect();
return Err(Error::Service(
ErrorCode::PortInUse,
format!("Port {port} is already used (PID {}). Stop the other server or change Settings/repack.json.", list.join(", ")),
));
}
match sys::exclusive_bind(port) {
Ok(()) => return Ok(()),
Err(code) if code == 10013 || code == 10048 => {
if Instant::now() >= deadline {
return Err(Error::Invalid(format!(
"Port {port} remains unavailable after 30 seconds (Windows bind error {code}). No process was stopped. Retry after the previous database shutdown has finished, or check the Windows port reservation."
)));
}
if !announced {
progress(&format!("Waiting for Windows to release port {port}..."));
announced = true;
}
std::thread::sleep(Duration::from_millis(250));
}
Err(code) => return Err(Error::Invalid(format!("Port {port} cannot be checked (Windows error {code})."))),
}
}
}
/// Is the recorded process of `name` serving `port`? Its listener row is the evidence; when a system does not
/// show the owner of a listener, the server side of a fresh loopback connection is (never for MySQL, whose
/// listener has always been visible and which should not get stray connections).
pub fn ready(root: &Path, name: &str, port: u16) -> bool {
let Some(record) = state::running(root, name) else { return false };
let listening = sys::tcp_rows_v4().iter().any(|r| r.state == sys::LISTEN && r.local_port == port && r.pid == record.pid);
if listening {
return crate::process::is_alive(&record);
}
if name == "mysql" {
return false;
}
accepted_by(port, record.pid) && crate::process::is_alive(&record)
}
/// Connect to 127.0.0.1:`port` and check that exactly one established server-side row, owned by `pid`, answers
/// that connection.
fn accepted_by(port: u16, pid: u32) -> bool {
let addr: SocketAddr = ([127, 0, 0, 1], port).into();
let Ok(client) = TcpStream::connect_timeout(&addr, Duration::from_millis(500)) else { return false };
let Ok(mine) = client.local_addr().map(|a| a.port()) else { return false };
let me = std::process::id();
let rows: Vec<sys::TcpRow> = sys::tcp_rows_v4()
.into_iter()
.chain(sys::tcp_rows_v6())
.filter(|r| r.remote_port == mine && r.remote_loopback && !(r.local_port == mine && r.pid == me))
.collect();
rows.len() == 1 && rows[0].state == sys::ESTABLISHED && rows[0].pid == pid
}
pub fn wait_ready(root: &Path, name: &str, port: u16, seconds: u64) -> Result<()> {
let until = Instant::now() + Duration::from_secs(seconds);
while Instant::now() < until {
if ready(root, name, port) {
return Ok(());
}
if state::running(root, name).is_none() {
return Err(Error::Service(ErrorCode::StartupFailed, format!("{name} stopped during startup. Check its log.")));
}
std::thread::sleep(Duration::from_millis(500));
}
Err(Error::Service(
ErrorCode::StartupFailed,
format!("{name} is still starting: its expected TCP listener on port {port} was not found; check its log."),
))
}
// ---------------------------------------------------------------------------------------------------------------
// MySQL client
// ---------------------------------------------------------------------------------------------------------------
/// Run SQL (or a `mysqladmin` command) with the repack's own client and administrator login.
pub fn mysql(root: &Path, sql: Option<&str>, admin: Option<&str>) -> Result<String> {
let exe = root.join(if admin.is_some() { "mysql/bin/mysqladmin.exe" } else { "mysql/bin/mysql.exe" });
let defaults = format!("--defaults-file={}", root.join("mysql/admin-client.ini").display());
let mut cmd = Command::new(exe);
hidden(&mut cmd).arg(defaults);
match admin {
Some(a) => cmd.arg(a),
None => cmd.args(["--batch", "--skip-column-names"]),
};
let payload = sql.map(|s| s.as_bytes().to_vec());
let timeout = if payload.as_ref().is_some_and(|p| p.len() > 1024 * 1024) { 900 } else { 90 };
cmd.stdin(if payload.is_some() { Stdio::piped() } else { Stdio::null() }).stdout(Stdio::piped()).stderr(Stdio::piped());
let mut child = cmd.spawn()?;
if let (Some(data), Some(mut stdin)) = (payload, child.stdin.take()) {
std::thread::spawn(move || {
use std::io::Write;
let _ = stdin.write_all(&data);
});
}
// Both outputs are read while the client runs: a full pipe would stop it (and look like a timeout).
let read = |pipe: Option<Box<dyn std::io::Read + Send>>| {
std::thread::spawn(move || {
let mut buf = Vec::new();
if let Some(mut p) = pipe {
let _ = p.read_to_end(&mut buf);
}
buf
})
};
let out_reader = read(child.stdout.take().map(|p| Box::new(p) as Box<dyn std::io::Read + Send>));
let err_reader = read(child.stderr.take().map(|p| Box::new(p) as Box<dyn std::io::Read + Send>));
let started = Instant::now();
let failed = |stderr: &[u8]| {
let text = String::from_utf8_lossy(stderr);
let detail = text.lines().rev().find(|l| !l.trim().is_empty()).unwrap_or("").trim().to_string();
let mut message = "The repack database command failed; check mysql/logs/mysql-error.log.".to_string();
if !detail.is_empty() {
message.push_str(&format!(" ({detail})"));
}
Error::Invalid(message)
};
let status = loop {
if let Some(status) = child.try_wait()? {
break status;
}
if started.elapsed() > Duration::from_secs(timeout) {
let _ = child.kill();
let _ = child.wait();
let _ = out_reader.join();
return Err(failed(b"timed out"));
}
std::thread::sleep(Duration::from_millis(50));
};
let stdout = out_reader.join().unwrap_or_default();
let stderr = err_reader.join().unwrap_or_default();
if !status.success() {
return Err(failed(&stderr));
}
Ok(String::from_utf8_lossy(&stdout).trim().to_string())
}
// ---------------------------------------------------------------------------------------------------------------
// Start and stop
// ---------------------------------------------------------------------------------------------------------------
pub fn start_mysql(root: &Path, cfg: &Settings, progress: Progress) -> Result<()> {
if cfg.shared_database {
// An extra world uses the main folder's database; it must already run.
return mysql(root, None, Some("ping")).map(|_| ()).map_err(|e| {
Error::Service(ErrorCode::DatabaseNotRunning, format!("The main server's database is not running. {e}"))
});
}
if state::running(root, "mysql").is_some() {
wait_ready(root, "mysql", cfg.mysql_port, 300)?;
mysql(root, None, Some("ping"))?;
progress("MySQL is already running.");
return Ok(());
}
ensure_free(cfg.mysql_port, progress)?;
if !root.join("mysql/data/mysql").is_dir() {
return Err(Error::Service(ErrorCode::ServerFilesIncomplete, "The packaged database is missing. Extract the complete repack.".into()));
}
progress("Starting MySQL...");
let ini = format!("--defaults-file={}", root.join("mysql/my.ini").display());
spawn(root, "mysql", &root.join("mysql/bin/mysqld.exe"), &[&ini, "--no-monitor"], &root.join("mysql"), &root.join("mysql/logs/startup.log"), &cfg.env_remove)?;
wait_ready(root, "mysql", cfg.mysql_port, 300)?;
mysql(root, None, Some("ping"))?;
mysql(
root,
Some(&format!(
"UPDATE acore_auth.realmlist SET name='{}',address='127.0.0.1',localAddress='127.0.0.1',port={} WHERE id={};",
cfg.realm.name, cfg.world_port, cfg.realm.id
)),
None,
)?;
Ok(())
}
pub fn start_auth(root: &Path, cfg: &Settings, progress: Progress) -> Result<()> {
start_mysql(root, cfg, progress)?;
if state::running(root, "auth").is_some() {
wait_ready(root, "auth", cfg.auth_port, 60)?;
progress("Authserver is already running.");
return Ok(());
}
ensure_free(cfg.auth_port, progress)?;
// An interrupted world startup can leave flag 3, which authserver excludes.
mysql(root, Some(&format!("UPDATE acore_auth.realmlist SET flag=0 WHERE id={};", cfg.realm.id)), None)?;
progress("Starting authserver...");
spawn(root, "auth", &root.join("Core/authserver.exe"), &["-c", "configs/authserver.conf"], &root.join("Core"), &root.join("Core/Logs/auth-console.log"), &cfg.env_remove)?;
wait_ready(root, "auth", cfg.auth_port, 60)
}
/// Stop the recorded process, only if it is still that process.
pub fn terminate(record: &ProcessIdentity) -> Result<()> {
if !crate::process::is_alive(record) {
return Ok(());
}
sys::terminate(record)
}
pub fn wait_stopped(record: &ProcessIdentity, seconds: u64) -> bool {
let until = Instant::now() + Duration::from_secs(seconds);
while crate::process::is_alive(record) && Instant::now() < until {
std::thread::sleep(Duration::from_millis(250));
}
!crate::process::is_alive(record)
}
/// The recorded world, when it is this folder's own `Core/worldserver.exe` (never stop a process only because a
/// record names it).
fn owned_world(root: &Path) -> Result<Option<ProcessIdentity>> {
let Some(world) = state::running(root, "world") else { return Ok(None) };
let expected = root.join("Core/worldserver.exe");
let same = std::fs::canonicalize(&world.exe).ok().zip(std::fs::canonicalize(&expected).ok()).is_some_and(|(a, b)| a == b);
if !same {
return Err(Error::Invalid("World process ownership could not be verified; the database was left running.".into()));
}
Ok(Some(world))
}
/// Ask the world's console for a graceful shutdown. False when the console is not this world's or does not answer.
fn ask_shutdown(root: &Path, cfg: &Settings) -> bool {
ready(root, "world", cfg.ra_port)
&& crate::ra::Ra::connect_to(cfg.ra_port, &cfg.ra_username, &cfg.ra_password)
.and_then(|ra| ra.send_without_answer("server shutdown 1s 0"))
.is_ok()
}
/// Stop this folder's world without its console (unsaved progress since the last save is lost).
fn stop_world_process(world: &ProcessIdentity) -> Result<()> {
terminate(world).map_err(|_| Error::Invalid("Worldserver could not be stopped safely; its database was left running.".into()))?;
if !wait_stopped(world, 90) {
return Err(Error::Invalid("Worldserver is still stopping; its database was left running.".into()));
}
Ok(())
}
/// Stop the world at once, then everything else as [`stop_all`] does. Only when the user asked for it.
pub fn force_stop_all(root: &Path, cfg: &Settings, progress: Progress) -> Result<()> {
if let Some(world) = owned_world(root)? {
stop_world_process(&world)?;
progress("Force-stopped this server's verified world process; unsaved progress may be lost.");
}
stop_all(root, cfg, progress)
}
/// Stop everything of this repack, world first (gracefully through its console), its database last. An extra
/// world leaves the shared database alone.
pub fn stop_all(root: &Path, cfg: &Settings, progress: Progress) -> Result<()> {
if let Some(world) = owned_world(root)? {
if ask_shutdown(root, cfg) {
progress("Graceful world shutdown requested.");
} else {
progress("World console unavailable; stopping this repack's recorded world process.");
stop_world_process(&world)?;
}
// A console request can be lost (seen when a client disconnected at once). While the world still runs
// and its console still answers, it has not begun to stop: ask again. Asking twice is harmless.
let mut stopped = wait_stopped(&world, 15);
for _ in 0..2 {
if stopped {
break;
}
if ask_shutdown(root, cfg) {
progress("The world has not begun to stop; shutdown requested again.");
}
stopped = wait_stopped(&world, 15);
}
if !stopped && !wait_stopped(&world, 45) {
return Err(Error::Invalid("Worldserver is still stopping; its database has been left running.".into()));
}
}
if let Some(supervisor) = state::running(root, "supervisor") {
if !wait_stopped(&supervisor, 45) {
return Err(Error::Invalid("The report relay is still finishing a request. Try Stop All again shortly.".into()));
}
}
if let Some(relay) = state::running(root, "relay") {
std::fs::write(state::dir(root).join("stop-relay"), b"")?;
if !wait_stopped(&relay, 40) {
return Err(Error::Invalid("The report relay did not finish; it was left running for recovery.".into()));
}
}
if let Some(auth) = state::running(root, "auth") {
terminate(&auth)?;
if !wait_stopped(&auth, 10) {
return Err(Error::Invalid("Authserver did not stop.".into()));
}
}
if let Some(database) = state::running(root, "mysql").filter(|_| !cfg.shared_database) {
let shutdown = mysql(root, None, Some("shutdown"));
if !wait_stopped(&database, 60) {
shutdown?;
return Err(Error::Invalid("MySQL is still stopping; wait before copying the repack.".into()));
}
}
progress("All services from this repack are stopped. It is safe to move or copy this folder.");
Ok(())
}
/// Which services run (`manage.py status-json`).
pub fn status(root: &Path) -> serde_json::Value {
let mut out = serde_json::Map::new();
for name in ["mysql", "auth", "world", "relay"] {
out.insert(name.into(), state::running(root, name).is_some().into());
}
let debug: bool = crate::fsx::read_json::<serde_json::Value>(&state::dir(root).join("debug-logs.json"))
.ok()
.and_then(|v| v.get("enabled").and_then(|e| e.as_bool()))
.unwrap_or(false);
out.insert("debugLogs".into(), debug.into());
serde_json::Value::Object(out)
}
pub fn log_path(root: &Path, name: &str) -> PathBuf {
match name {
"mysql" => root.join("mysql/logs/startup.log"),
"auth" => root.join("Core/Logs/auth-console.log"),
"world" => root.join("Core/Logs/world-console.log"),
"supervisor" => root.join("Core/Logs/supervisor.log"),
_ => root.join("BugReport/Logs/relay.log"),
}
}
// ---------------------------------------------------------------------------------------------------------------
// Windows
// ---------------------------------------------------------------------------------------------------------------
#[cfg(windows)]
mod sys {
use crate::error::{Error, Result};
use crate::process::ProcessIdentity;
use windows_sys::Win32::Foundation::CloseHandle;
use windows_sys::Win32::NetworkManagement::IpHelper::GetExtendedTcpTable;
use windows_sys::Win32::Networking::WinSock::{setsockopt, SOL_SOCKET, SO_EXCLUSIVEADDRUSE};
use windows_sys::Win32::System::Threading::{OpenProcess, TerminateProcess, PROCESS_QUERY_LIMITED_INFORMATION, PROCESS_TERMINATE};
pub const LISTEN: u32 = 2;
pub const ESTABLISHED: u32 = 5;
pub struct TcpRow {
pub state: u32,
pub local_port: u16,
pub remote_port: u16,
pub remote_loopback: bool,
pub pid: u32,
}
fn table(af: u32) -> Vec<u8> {
const TCP_TABLE_OWNER_PID_ALL: i32 = 5;
let mut size = 0u32;
let mut buf: Vec<u8> = Vec::new();
for _ in 0..4 {
let code = unsafe {
GetExtendedTcpTable(
if buf.is_empty() { std::ptr::null_mut() } else { buf.as_mut_ptr().cast() },
&mut size,
0,
af,
TCP_TABLE_OWNER_PID_ALL,
0,
)
};
match code {
0 if !buf.is_empty() => return buf,
0 | 122 => buf = vec![0u8; size as usize + 4096],
_ => return Vec::new(),
}
}
Vec::new()
}
fn u32_at(b: &[u8], o: usize) -> u32 {
u32::from_le_bytes(b[o..o + 4].try_into().unwrap())
}
pub fn tcp_rows_v4() -> Vec<TcpRow> {
let b = table(2);
let mut out = Vec::new();
if b.len() < 4 {
return out;
}
for i in 0..u32_at(&b, 0) as usize {
let o = 4 + 24 * i;
if o + 24 > b.len() {
break;
}
let remote = u32_at(&b, o + 12).to_le_bytes();
out.push(TcpRow {
state: u32_at(&b, o),
local_port: u16::from_be((u32_at(&b, o + 8) & 0xFFFF) as u16),
remote_port: u16::from_be((u32_at(&b, o + 16) & 0xFFFF) as u16),
remote_loopback: remote == [127, 0, 0, 1],
pid: u32_at(&b, o + 20),
});
}
out
}
pub fn tcp_rows_v6() -> Vec<TcpRow> {
let b = table(23);
let mut out = Vec::new();
if b.len() < 4 {
return out;
}
// MIB_TCP6ROW_OWNER_PID: local addr 16, scope 4, local port 4, remote addr 16, scope 4, remote port 4, state 4, pid 4
for i in 0..u32_at(&b, 0) as usize {
let o = 4 + 56 * i;
if o + 56 > b.len() {
break;
}
let remote = &b[o + 24..o + 40];
let mapped_loopback = remote[..10].iter().all(|x| *x == 0) && remote[10] == 0xff && remote[11] == 0xff && remote[12..] == [127, 0, 0, 1];
out.push(TcpRow {
state: u32_at(&b, o + 48),
local_port: u16::from_be((u32_at(&b, o + 20) & 0xFFFF) as u16),
remote_port: u16::from_be((u32_at(&b, o + 44) & 0xFFFF) as u16),
remote_loopback: mapped_loopback,
pid: u32_at(&b, o + 52),
});
}
out
}
/// Bind 0.0.0.0:port exclusively and release it. Err carries the Windows socket error.
pub fn exclusive_bind(port: u16) -> std::result::Result<(), i32> {
use socket2::{Domain, Socket, Type};
use std::os::windows::io::AsRawSocket;
let socket = Socket::new(Domain::IPV4, Type::STREAM, None).map_err(|e| e.raw_os_error().unwrap_or(-1))?;
let one: i32 = 1;
let set = unsafe {
setsockopt(socket.as_raw_socket() as _, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (&one as *const i32).cast(), 4)
};
if set != 0 {
return Err(std::io::Error::last_os_error().raw_os_error().unwrap_or(-1));
}
let addr: std::net::SocketAddr = ([0, 0, 0, 0], port).into();
socket.bind(&addr.into()).map_err(|e| e.raw_os_error().unwrap_or(-1))
}
pub fn terminate(record: &ProcessIdentity) -> Result<()> {
unsafe {
let h = OpenProcess(PROCESS_TERMINATE | PROCESS_QUERY_LIMITED_INFORMATION, 0, record.pid);
if h.is_null() {
return Err(Error::Invalid("Unable to stop the repack process.".into()));
}
let same = crate::process::is_alive(record);
let ok = same && TerminateProcess(h, 0) != 0;
CloseHandle(h);
if !ok {
return Err(Error::Invalid("The process changed while stopping it.".into()));
}
}
Ok(())
}
}
#[cfg(not(windows))]
mod sys {
use crate::error::{Error, Result};
use crate::process::ProcessIdentity;
pub const LISTEN: u32 = 2;
pub const ESTABLISHED: u32 = 5;
pub struct TcpRow {
pub state: u32,
pub local_port: u16,
pub remote_port: u16,
pub remote_loopback: bool,
pub pid: u32,
}
pub fn tcp_rows_v4() -> Vec<TcpRow> {
Vec::new()
}
pub fn tcp_rows_v6() -> Vec<TcpRow> {
Vec::new()
}
pub fn exclusive_bind(_: u16) -> std::result::Result<(), i32> {
Ok(())
}
pub fn terminate(_: &ProcessIdentity) -> Result<()> {
Err(Error::Invalid("not supported".into()))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_port_with_a_listener_is_refused_and_a_free_one_passes() {
let held = std::net::TcpListener::bind("0.0.0.0:0").unwrap();
let port = held.local_addr().unwrap().port();
let err = ensure_free(port, &|_| {}).unwrap_err().to_string();
assert!(err.contains(&format!("Port {port} is already used (PID {}", std::process::id())), "{err}");
drop(held);
ensure_free(port, &|_| {}).unwrap();
}
#[test]
fn a_service_is_ready_only_on_its_own_port() {
let d = tempfile::tempdir().unwrap();
let held = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let port = held.local_addr().unwrap().port();
assert!(!ready(d.path(), "auth", port), "no record yet");
state::record(d.path(), "auth", std::process::id()).unwrap();
assert!(ready(d.path(), "auth", port));
let other = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
drop(other);
assert!(!ready(d.path(), "auth", port + 1) || port + 1 == 0);
}
#[test]
fn status_reads_the_records() {
let d = tempfile::tempdir().unwrap();
state::record(d.path(), "mysql", std::process::id()).unwrap();
let s = status(d.path());
assert_eq!(s["mysql"], true);
assert_eq!(s["world"], false);
assert_eq!(s["debugLogs"], false);
}
}
+168
View File
@@ -0,0 +1,168 @@
//! `Settings/repack.json`: ports and the console login of one repack (`manage.py settings()`).
use std::path::Path;
use crate::error::{Error, Result};
pub const PORT_KEYS: [&str; 4] = ["mysqlPort", "authPort", "worldPort", "raPort"];
/// The realm a folder runs: its row in `acore_auth.realmlist` and its two game databases.
///
/// Without `Settings/realm-profile.json` this is what the repack launcher always did (realm 1 "AzerothCore" on
/// `acore_world`/`acore_characters`). With it, the active profile decides, as the Manager's realm patch of
/// `manage.py` did.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Realm {
pub id: u32,
pub name: &'static str,
pub world_db: &'static str,
pub characters_db: &'static str,
}
impl Realm {
pub fn load(root: &Path) -> Result<Realm> {
let path = root.join("Settings/realm-profile.json");
if !path.exists() {
return Ok(Realm { id: 1, name: "AzerothCore", world_db: "acore_world", characters_db: "acore_characters" });
}
let v: serde_json::Value = crate::fsx::read_json(&path)?;
Ok(match v.get("active").and_then(|a| a.as_str()).unwrap_or("coa") {
"wildcard" => Realm { id: 2, name: "Wildcard", world_db: "acore_world_wildcard", characters_db: "acore_characters_wildcard" },
"reborn" => Realm { id: 3, name: "Warcraft Reborn", world_db: "acore_world_reborn", characters_db: "acore_characters_reborn" },
_ => Realm { id: 1, name: "Conquest of Azeroth", world_db: "acore_world", characters_db: "acore_characters" },
})
}
}
/// An extra world of a server (`<server>/.realms/<name>`): it shares the main folder's database and never
/// starts or stops it.
pub fn is_extra_world(root: &Path) -> bool {
root.parent().and_then(|p| p.file_name()).is_some_and(|n| n == ".realms")
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Settings {
pub mysql_port: u16,
pub auth_port: u16,
pub world_port: u16,
pub ra_port: u16,
pub ra_username: String,
pub ra_password: String,
pub realm: Realm,
/// The database belongs to the main folder of this server (an extra world): it is only checked, never
/// started.
pub shared_database: bool,
/// Environment variables the started services must not see (for example a port override of the caller).
pub env_remove: Vec<String>,
/// The whole document, for keys this code does not know (kept when it is written back).
pub raw: serde_json::Map<String, serde_json::Value>,
}
impl Settings {
/// Read `Settings/repack.json`, with every port moved by `offset` (a second world of the same server runs on
/// shifted ports). The same checks as `manage.py`: integer ports in 1025..65535 after the offset, all
/// different.
pub fn load(root: &Path, offset: i32) -> Result<Settings> {
let bytes = std::fs::read(root.join("Settings/repack.json"))?;
let text = String::from_utf8_lossy(&bytes);
let text = text.strip_prefix('\u{feff}').unwrap_or(&text);
let raw: serde_json::Map<String, serde_json::Value> =
serde_json::from_str(text).map_err(|e| Error::Invalid(format!("Settings/repack.json: {e}")))?;
let mut ports = [0u16; 4];
for (i, key) in PORT_KEYS.iter().enumerate() {
// Python's `type(value) is not int` refuses booleans and floats alike.
let value = raw.get(*key).and_then(|v| v.as_i64()).filter(|_| raw[*key].is_i64() || raw[*key].is_u64());
let shifted = value.map(|v| v + i64::from(offset));
match shifted {
Some(p) if p > 1024 && p < 65536 => ports[i] = p as u16,
_ => return Err(Error::Service(crate::error::ErrorCode::InvalidConfigValue, "Invalid port in Settings/repack.json".into())),
}
}
let mut unique = ports.to_vec();
unique.sort_unstable();
unique.dedup();
if unique.len() != 4 {
return Err(Error::Invalid("Each service needs a different port.".into()));
}
let text_of = |k: &str| raw.get(k).and_then(|v| v.as_str()).unwrap_or_default().to_string();
Ok(Settings {
mysql_port: ports[0],
auth_port: ports[1],
world_port: ports[2],
ra_port: ports[3],
ra_username: text_of("raUsername"),
ra_password: text_of("raPassword"),
realm: Realm::load(root)?,
shared_database: is_extra_world(root),
env_remove: Vec::new(),
raw,
})
}
/// `{"mysqlPort": .., "authPort": .., "worldPort": .., "raPort": ..}` as `manage.py` records it in
/// `.state/configuration.json` (the keys of repack.json ending in "Port", in the file's order).
pub fn port_map(&self) -> serde_json::Map<String, serde_json::Value> {
let shifted = [self.mysql_port, self.auth_port, self.world_port, self.ra_port];
let mut out = serde_json::Map::new();
for key in self.raw.keys().filter(|k| k.ends_with("Port")) {
let value = PORT_KEYS
.iter()
.position(|p| p == key)
.map(|i| serde_json::Value::from(shifted[i]))
.unwrap_or_else(|| self.raw[key].clone());
out.insert(key.clone(), value);
}
out
}
}
#[cfg(test)]
mod tests {
use super::*;
fn write(dir: &Path, text: &str) {
std::fs::create_dir_all(dir.join("Settings")).unwrap();
std::fs::write(dir.join("Settings/repack.json"), text).unwrap();
}
#[test]
fn ports_are_checked_like_the_python_launcher() {
let d = tempfile::tempdir().unwrap();
write(d.path(), r#"{"mysqlPort":3307,"authPort":3724,"worldPort":8085,"raPort":3443,"raUsername":"U","raPassword":"P"}"#);
let s = Settings::load(d.path(), 0).unwrap();
assert_eq!((s.mysql_port, s.auth_port, s.world_port, s.ra_port), (3307, 3724, 8085, 3443));
assert_eq!(s.ra_username, "U");
let shifted = Settings::load(d.path(), 10).unwrap();
assert_eq!(shifted.world_port, 8095);
assert_eq!(shifted.port_map()["worldPort"], serde_json::json!(8095));
for bad in [
r#"{"mysqlPort":1024,"authPort":3724,"worldPort":8085,"raPort":3443}"#,
r#"{"mysqlPort":"3307","authPort":3724,"worldPort":8085,"raPort":3443}"#,
r#"{"mysqlPort":3307.0,"authPort":3724,"worldPort":8085,"raPort":3443}"#,
r#"{"mysqlPort":true,"authPort":3724,"worldPort":8085,"raPort":3443}"#,
r#"{"mysqlPort":3307,"authPort":3307,"worldPort":8085,"raPort":3443}"#,
r#"{"authPort":3724,"worldPort":8085,"raPort":3443}"#,
] {
write(d.path(), bad);
assert!(Settings::load(d.path(), 0).is_err(), "{bad}");
}
write(d.path(), "\u{feff}{\"mysqlPort\":3307,\"authPort\":3724,\"worldPort\":8085,\"raPort\":65535}");
assert!(Settings::load(d.path(), 1).is_err(), "65536 after the offset");
assert!(Settings::load(d.path(), 0).is_ok(), "a byte order mark is accepted");
}
#[test]
fn the_realm_follows_the_active_profile() {
let d = tempfile::tempdir().unwrap();
assert_eq!(Realm::load(d.path()).unwrap().name, "AzerothCore");
std::fs::create_dir_all(d.path().join("Settings")).unwrap();
for (active, id, db) in [("coa", 1, "acore_world"), ("wildcard", 2, "acore_world_wildcard"), ("reborn", 3, "acore_world_reborn")] {
std::fs::write(d.path().join("Settings/realm-profile.json"), format!("{{\"active\":\"{active}\"}}")).unwrap();
let r = Realm::load(d.path()).unwrap();
assert_eq!((r.id, r.world_db), (id, db));
}
assert!(is_extra_world(&d.path().join(".realms/secondary")));
assert!(!is_extra_world(d.path()));
}
}
Binary file not shown.
+398
View File
@@ -0,0 +1,398 @@
//! SQUID Playerbots on a repack (`Scripts/squid_playerbots.py`): the bot modules must not both run, how long a
//! SQUID world may take to start, and its database, provisioned before the world starts.
//!
//! The SQL journals are the ones the Python script keeps, unchanged: `coa_squid_migrations(path, sha256)` and
//! `coa_squid_pending(path, sha256)` in every target schema, and the SQUID installer's `coa_bots_installed`.
use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf};
use sha1::Digest as _;
use crate::error::{Error, Result};
/// `key = value` lines of a module config (comments and quotes dropped), as `options()` reads them.
pub fn options(path: &Path) -> BTreeMap<String, String> {
let mut out = BTreeMap::new();
let Ok(bytes) = std::fs::read(path) else { return out };
let text = String::from_utf8_lossy(&bytes);
let text = text.strip_prefix('\u{feff}').unwrap_or(&text);
for line in text.lines() {
let line = line.trim_start();
let Some((key, rest)) = line.split_once('=') else { continue };
let key = key.trim_end();
if key.is_empty() || key.starts_with('#') || key.contains(char::is_whitespace) {
continue;
}
let value = rest.split('#').next().unwrap_or("").trim();
out.insert(key.to_string(), value.trim_matches('"').to_string());
}
out
}
/// A secondary world shares the primary's package files.
pub fn package_root(root: &Path) -> PathBuf {
let secondary = root.file_name().is_some_and(|n| n == "secondary")
&& root.parent().and_then(|p| p.file_name()).is_some_and(|n| n == ".realms");
if secondary {
root.parent().and_then(Path::parent).map(Path::to_path_buf).unwrap_or_else(|| root.to_path_buf())
} else {
root.to_path_buf()
}
}
pub fn module_options(root: &Path, name: &str) -> (PathBuf, BTreeMap<String, String>) {
let folder = root.join("Core/configs/modules");
let active = folder.join(name);
let mut path = if active.exists() { active } else { folder.join(format!("{name}.dist")) };
if !path.exists() && name == "playerbots.conf" {
path = package_root(root).join("Core/configs/modules/playerbots.conf.dist");
}
let values = options(&path);
(path, values)
}
/// Invalid booleans count as the modules' compiled default: enabled.
pub fn enabled(values: &BTreeMap<String, String>, key: &str) -> bool {
!matches!(values.get(key).map(|v| v.to_ascii_lowercase()).as_deref(), Some("0" | "false" | "no" | "off"))
}
pub fn validate_bots(root: &Path) -> Result<()> {
let (a, av) = module_options(root, "mod_coa_playerbots.conf");
let (b, bv) = module_options(root, "playerbots.conf");
if a.exists() && b.exists() && enabled(&av, "CoaBots.Enable") && enabled(&bv, "AiPlayerbot.Enabled") {
return Err(Error::Invalid(
"CoA Companions and SQUID Playerbots cannot both be enabled. Disable one bot module in Modules or its config.".into(),
));
}
Ok(())
}
/// Seconds a world may take to open its port: SQUID loads its bots first.
pub fn startup_timeout(root: &Path) -> u64 {
let (path, values) = module_options(root, "playerbots.conf");
if path.exists() && enabled(&values, "AiPlayerbot.Enabled") {
1500
} else {
180
}
}
/// Replace (or append) `key = value` lines; the file is written with "\n" line ends.
pub fn set_options(path: &Path, values: &[(&str, String)]) -> Result<()> {
let bytes = std::fs::read(path)?;
let text = String::from_utf8_lossy(&bytes);
let mut text = text.strip_prefix('\u{feff}').unwrap_or(&text).replace("\r\n", "\n");
for (key, value) in values {
let line = format!("{key} = {value}");
let mut found = false;
let lines: Vec<String> = text
.split('\n')
.map(|l| {
let t = l.trim_start();
let matches = t.strip_prefix(key).is_some_and(|rest| rest.trim_start().starts_with('='));
if matches {
found = true;
line.clone()
} else {
l.to_string()
}
})
.collect();
text = lines.join("\n");
if !found {
text.push('\n');
text.push_str(&line);
text.push('\n');
}
}
crate::fsx::atomic_write(path, text.as_bytes())
}
fn valid_relative(rel: &str) -> bool {
!rel.is_empty() && rel.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'.' | b'/' | b'-'))
}
/// Table names a base file creates (`CREATE TABLE [IF NOT EXISTS] name`).
fn created_tables(sql: &str) -> BTreeSet<String> {
let mut out = BTreeSet::new();
let upper = sql.to_ascii_uppercase();
let mut from = 0;
while let Some(i) = upper[from..].find("CREATE") {
let start = from + i + "CREATE".len();
from = start;
let rest = &sql[start..];
let mut words = rest.split_whitespace();
if !words.next().is_some_and(|w| w.eq_ignore_ascii_case("TABLE")) {
continue;
}
let mut name = words.next().unwrap_or("");
if name.eq_ignore_ascii_case("IF") {
let _ = words.next(); // NOT
let _ = words.next(); // EXISTS
name = words.next().unwrap_or("");
}
let name: String = name.trim_start_matches('`').chars().take_while(|c| c.is_ascii_alphanumeric() || *c == '_').collect();
if !name.is_empty() {
out.insert(name);
}
}
out
}
fn sha256_hex(bytes: &[u8]) -> String {
crate::fsx::sha256_bytes(bytes)
}
fn sha1_hex(bytes: &[u8]) -> String {
let mut h = sha1::Sha1::new();
h.update(bytes);
h.finalize().iter().map(|b| format!("{b:02x}")).collect()
}
fn rows(text: &str) -> Vec<(String, String)> {
text.lines().filter_map(|r| r.split_once('\t')).map(|(a, b)| (a.to_string(), b.to_string())).collect()
}
/// Provision an enabled SQUID without replaying imported base tables (`prepare_playerbots`). `mysql(sql)` runs
/// SQL with the repack's administrator login and returns its output.
pub fn prepare_playerbots(root: &Path, mysql_port: u16, mysql: &dyn Fn(&str) -> Result<String>, progress: &dyn Fn(&str)) -> Result<()> {
let (mut path, values) = module_options(root, "playerbots.conf");
if !path.exists() || !enabled(&values, "AiPlayerbot.Enabled") {
return Ok(());
}
validate_bots(root)?;
let sql_root = package_root(root).join("Extras/SquidPlayerbots/sql");
if !sql_root.join("playerbots/base").is_dir() {
return Err(Error::Invalid("SQUID Playerbots database files are missing. Repair the server installation.".into()));
}
let world = options(&root.join("Core/configs/worldserver.conf"));
let mut schemas: Vec<(&str, String)> = Vec::new();
for (kind, key) in [("characters", "CharacterDatabaseInfo"), ("world", "WorldDatabaseInfo")] {
let schema = world.get(key).and_then(|v| v.rsplit(';').next()).unwrap_or("").to_string();
let ok = matches!(schema.as_str(), "acore_world" | "acore_characters" | "acore_world_wildcard" | "acore_characters_wildcard");
if !ok {
return Err(Error::Invalid("Unsupported world/characters database for SQUID Playerbots.".into()));
}
schemas.push((kind, schema));
}
schemas.push(("playerbots", "acore_playerbots".into()));
let list = |schema: &str| -> Result<BTreeSet<String>> {
Ok(mysql(&format!("SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_SCHEMA='{schema}';"))?
.lines()
.map(str::to_string)
.collect())
};
let existing_playerbots = list("acore_playerbots")?;
let bookkeeping = ["updates", "updates_include", "version_db_playerbots", "coa_squid_migrations", "coa_bots_installed", "coa_squid_pending"];
let data_tables: Vec<&String> = existing_playerbots.iter().filter(|t| !bookkeeping.contains(&t.as_str())).collect();
let mut installer_history = BTreeSet::new();
if existing_playerbots.contains("coa_bots_installed") {
for name in mysql("SELECT file FROM `acore_playerbots`.coa_bots_installed;")?.lines() {
let mut n = name.replace('\\', "/");
while n.contains("//") {
n = n.replace("//", "/");
}
let n = n.trim_matches('/').to_string();
if n.to_ascii_lowercase().ends_with(".sql") {
installer_history.insert(n);
}
}
}
let mut tables: BTreeMap<&str, BTreeSet<String>> = BTreeMap::new();
let mut histories: BTreeMap<&str, BTreeMap<String, String>> = BTreeMap::new();
let mut ledgers: BTreeMap<&str, BTreeMap<String, String>> = BTreeMap::new();
for (kind, schema) in &schemas {
let t = if *kind == "playerbots" { existing_playerbots.clone() } else { list(schema)? };
if t.contains("coa_squid_pending") {
let pending = mysql(&format!("SELECT path FROM `{schema}`.coa_squid_pending;"))?;
let pending = pending.trim();
if !pending.is_empty() {
return Err(Error::Invalid(format!(
"A SQUID base import was interrupted. Restore the database backup or repair the incomplete import before continuing; no SQL was applied: {pending}"
)));
}
}
let mut history = BTreeMap::new();
if t.contains("updates") {
for (name, digest) in rows(&mysql(&format!("SELECT name,hash FROM `{schema}`.updates;"))?) {
history.insert(name, digest.to_ascii_lowercase());
}
}
let mut ledger = BTreeMap::new();
if t.contains("coa_squid_migrations") {
for (name, digest) in rows(&mysql(&format!("SELECT path,sha256 FROM `{schema}`.coa_squid_migrations;"))?) {
ledger.insert(name, digest);
}
}
tables.insert(kind, t);
histories.insert(kind, history);
ledgers.insert(kind, ledger);
}
if !data_tables.is_empty() && installer_history.is_empty() && histories["playerbots"].is_empty() && ledgers["playerbots"].is_empty() {
for table in data_tables {
let quoted = table.replace('`', "``");
if mysql(&format!("SELECT EXISTS(SELECT 1 FROM `acore_playerbots`.`{quoted}` LIMIT 1);"))?.trim() == "1" {
return Err(Error::Invalid(
"Existing SQUID data has no recorded installation history. Repair the imported database history before continuing; no SQL was applied.".into(),
));
}
}
}
mysql("CREATE DATABASE IF NOT EXISTS acore_playerbots CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;")?;
for host in ["localhost", "127.0.0.1"] {
mysql(&format!("GRANT ALL PRIVILEGES ON acore_playerbots.* TO 'acore'@'{host}';"))?;
}
let (_, password) = crate::db::credentials(root)?;
if password.len() != 48 || !password.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) {
return Err(Error::Invalid("Invalid packaged database configuration.".into()));
}
if path.file_name().is_some_and(|n| n.to_string_lossy().ends_with(".dist")) {
let active = root.join("Core/configs/modules/playerbots.conf");
std::fs::create_dir_all(active.parent().unwrap())?;
std::fs::write(&active, std::fs::read(&path)?)?;
path = active;
}
set_options(
&path,
&[
("PlayerbotsDatabaseInfo", format!("\"127.0.0.1;{mysql_port};acore;{password};acore_playerbots\"")),
("Playerbots.Updates.EnableDatabases", "0".into()),
],
)?;
for (kind, schema) in &schemas {
mysql(&format!("CREATE TABLE IF NOT EXISTS `{schema}`.coa_squid_migrations (path VARCHAR(240) PRIMARY KEY, sha256 CHAR(64) NOT NULL);"))?;
mysql(&format!("CREATE TABLE IF NOT EXISTS `{schema}`.coa_squid_pending (path VARCHAR(240) PRIMARY KEY, sha256 CHAR(64) NOT NULL);"))?;
let history = &histories[kind];
let recorded = ledgers[kind].clone();
for stage in ["base", "updates", "custom"] {
let mut sources: Vec<PathBuf> = std::fs::read_dir(sql_root.join(kind).join(stage))
.map(|rd| rd.flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|e| e == "sql")).collect())
.unwrap_or_default();
sources.sort();
for source in sources {
let relative = source.strip_prefix(&sql_root).unwrap_or(&source).to_string_lossy().replace('\\', "/");
if !valid_relative(&relative) {
return Err(Error::Invalid("Invalid SQUID SQL filename.".into()));
}
let bytes = std::fs::read(&source)?;
let digest = sha256_hex(&bytes);
if let Some(previous) = recorded.get(&relative) {
if *previous != digest {
return Err(Error::Invalid(format!("A previously applied SQUID database migration changed: {relative}")));
}
if stage != "base" {
continue;
}
}
let ledger_sql = if recorded.contains_key(&relative) {
String::new()
} else {
format!("INSERT INTO `{schema}`.coa_squid_migrations VALUES ('{relative}','{digest}');")
};
let text = String::from_utf8_lossy(&bytes);
let text = text.strip_prefix('\u{feff}').unwrap_or(&text).to_string();
if stage == "base" {
let definitions = created_tables(&text);
let present: BTreeSet<String> = definitions.intersection(&tables[kind]).cloned().collect();
if !present.is_empty() && present != definitions {
return Err(Error::Invalid(format!("SQUID base file has only some of its tables. Repair the incomplete database before continuing: {relative}")));
}
if definitions.is_empty() {
return Err(Error::Invalid(format!("SQUID base file has no recognizable table definitions; repair is required: {relative}")));
}
if present == definitions {
if !ledger_sql.is_empty() {
mysql(&ledger_sql)?;
}
continue;
}
mysql(&format!("INSERT INTO `{schema}`.coa_squid_pending VALUES ('{relative}','{digest}'); COMMIT;"))?;
let complete = format!("DELETE FROM `{schema}`.coa_squid_pending WHERE path='{relative}' AND sha256='{digest}'; COMMIT;");
progress(&format!("Importing SQUID {relative} into {schema} ({} bytes); large imports may take several minutes...", bytes.len()));
mysql(&format!("USE `{schema}`;\n{text}\n{ledger_sql}\n{complete}")).map_err(|_| {
Error::Invalid(format!(
"SQUID import failed: {relative} in {schema}. The world server was not started. The incomplete import is recorded; restore a database backup or repair that import before retrying."
))
})?;
progress(&format!("Imported SQUID {relative}."));
if let Some(t) = tables.get_mut(kind) {
t.extend(definitions);
}
continue;
}
if installer_history.iter().any(|n| *n == relative || n.ends_with(&format!("/{relative}"))) {
mysql(&ledger_sql)?;
continue;
}
let file_name = source.file_name().unwrap_or_default().to_string_lossy().into_owned();
if let Some(upstream) = history.get(&file_name) {
let lf = String::from_utf8_lossy(&bytes).replace("\r\n", "\n");
let accepted = [sha1_hex(&bytes), sha1_hex(lf.as_bytes())];
if !upstream.is_empty() && !accepted.contains(upstream) {
return Err(Error::Invalid(format!("SQUID update history does not match the shipped SQL: {relative}")));
}
mysql(&ledger_sql)?;
continue;
}
mysql(&format!("USE `{schema}`;\n{text}\n{ledger_sql}"))?;
}
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn config_lines_are_read_like_the_python_script() {
let d = tempfile::tempdir().unwrap();
let p = d.path().join("playerbots.conf");
std::fs::write(&p, "\u{feff}# comment = 1\nAiPlayerbot.Enabled = 0 # off\n Key.Two=\"quoted\"\nnot a line\nEmpty =\n").unwrap();
let o = options(&p);
assert_eq!(o.get("AiPlayerbot.Enabled").map(String::as_str), Some("0"));
assert_eq!(o.get("Key.Two").map(String::as_str), Some("quoted"));
assert_eq!(o.get("Empty").map(String::as_str), Some(""));
assert!(!o.contains_key("#"));
assert!(!enabled(&o, "AiPlayerbot.Enabled"));
assert!(enabled(&o, "Missing"));
}
#[test]
fn both_bot_modules_on_is_refused_and_squid_gets_a_long_startup() {
let d = tempfile::tempdir().unwrap();
let m = d.path().join("Core/configs/modules");
std::fs::create_dir_all(&m).unwrap();
std::fs::write(m.join("mod_coa_playerbots.conf"), "CoaBots.Enable = 1\n").unwrap();
std::fs::write(m.join("playerbots.conf.dist"), "AiPlayerbot.Enabled = 1\n").unwrap();
assert!(validate_bots(d.path()).is_err());
assert_eq!(startup_timeout(d.path()), 1500);
std::fs::write(m.join("playerbots.conf"), "AiPlayerbot.Enabled = 0\n").unwrap();
validate_bots(d.path()).unwrap();
assert_eq!(startup_timeout(d.path()), 180);
}
#[test]
fn options_are_replaced_or_appended() {
let d = tempfile::tempdir().unwrap();
let p = d.path().join("playerbots.conf");
std::fs::write(&p, "A = 1\r\n Playerbots.Updates.EnableDatabases = 1\r\n").unwrap();
set_options(&p, &[("Playerbots.Updates.EnableDatabases", "0".into()), ("PlayerbotsDatabaseInfo", "\"x\"".into())]).unwrap();
assert_eq!(std::fs::read_to_string(&p).unwrap(), "A = 1\nPlayerbots.Updates.EnableDatabases = 0\n\nPlayerbotsDatabaseInfo = \"x\"\n");
}
#[test]
fn base_tables_are_found() {
let t = created_tables("CREATE TABLE IF NOT EXISTS `ai_playerbot_names` (\n id int);\ncreate table playerbots_random_bots(x int);\n-- CREATE INDEX i ON t(x);");
assert_eq!(t, ["ai_playerbot_names".to_string(), "playerbots_random_bots".to_string()].into_iter().collect());
}
#[test]
fn a_secondary_world_uses_the_primary_package() {
assert_eq!(package_root(Path::new("C:/S/.realms/secondary")), Path::new("C:/S"));
assert_eq!(package_root(Path::new("C:/S")), Path::new("C:/S"));
}
}
+198
View File
@@ -0,0 +1,198 @@
//! `.state/`: which processes belong to this repack, and the one-action-at-a-time lock.
use std::fs::{File, OpenOptions};
use std::io::{Seek, SeekFrom, Write};
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};
use crate::error::{Error, Result};
use crate::fsx;
use crate::process::{self, ProcessIdentity};
pub fn dir(root: &Path) -> PathBuf {
root.join(".state")
}
/// Written like `manage.py atomic_json`: two-space JSON and a newline, now flushed to disk before it replaces
/// the old file.
pub fn write_json(path: &Path, value: &impl serde::Serialize) -> Result<()> {
let mut text = serde_json::to_string_pretty(value)?;
text.push('\n');
fsx::atomic_write(path, text.as_bytes())
}
/// The recorded process of `name` when it is still that process (same executable and start time). A missing,
/// empty or damaged record is no process: `manage.py` failed on those, and every later start with it.
pub fn running(root: &Path, name: &str) -> Option<ProcessIdentity> {
let record = process::read_state_record(root, name)?;
process::is_alive(&record).then_some(record)
}
/// Record the process `pid` as `name`. Fails when it has already exited.
pub fn record(root: &Path, name: &str, pid: u32) -> Result<ProcessIdentity> {
let identity = process::identity(pid)
.ok_or_else(|| Error::Invalid(format!("{name} exited during startup; check its log.")))?;
write_json(&dir(root).join(format!("{name}.json")), &identity)?;
Ok(identity)
}
/// Held while one start/stop action runs. Byte 0 of `.state/control.lock` is locked, exactly the region
/// `msvcrt.locking(fd, LK_NBLCK, 1)` locks in `manage.py`, so a Python launcher and this one exclude each other.
pub struct ControlLock {
file: File,
owner: PathBuf,
}
impl ControlLock {
/// Wait up to `wait` for the lock. `action` is recorded for whoever waits next ("start-all", ...).
pub fn acquire(root: &Path, action: &str, wait: Duration, progress: &dyn Fn(&str)) -> Result<ControlLock> {
let state = dir(root);
std::fs::create_dir_all(&state)?;
let mut file = OpenOptions::new().read(true).append(true).create(true).open(state.join("control.lock"))?;
if file.seek(SeekFrom::End(0))? == 0 {
file.write_all(b"0")?;
file.flush()?;
}
let owner = state.join("control-owner.json");
let deadline = Instant::now() + wait;
let mut announced = false;
loop {
if sys::try_lock(&file)? {
break;
}
let detail = match fsx::read_json::<serde_json::Value>(&owner) {
Ok(v) if v.get("pid").is_some() && v.get("action").is_some() => {
format!(" PID {}, action {}.", v["pid"], v["action"].as_str().unwrap_or(""))
}
_ => " Owner information is unavailable.".into(),
};
if Instant::now() >= deadline {
return Err(Error::Service(crate::error::ErrorCode::OperationInProgress, format!("Another start/stop action is in progress.{detail}")));
}
if !announced {
progress(&format!("Waiting for the current server action.{detail}"));
announced = true;
}
std::thread::sleep(Duration::from_millis(250));
}
let started = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs_f64())
.unwrap_or(0.0);
let lock = ControlLock { file, owner };
write_json(
&lock.owner,
&serde_json::json!({ "pid": std::process::id(), "action": action, "started": started }),
)?;
Ok(lock)
}
}
/// Byte 0 of a file locked while held (`msvcrt.locking`), for example the bug-report relay's `relay.lock`.
pub struct FileLock {
file: File,
}
impl FileLock {
/// Take the lock, or `None` when another process (or handle) holds it.
pub fn try_acquire(path: &Path) -> Result<Option<FileLock>> {
let mut file = OpenOptions::new().read(true).append(true).create(true).open(path)?;
if file.seek(SeekFrom::End(0))? == 0 {
file.write_all(b"0")?;
file.flush()?;
}
Ok(sys::try_lock(&file)?.then_some(FileLock { file }))
}
}
impl Drop for FileLock {
fn drop(&mut self) {
sys::unlock(&self.file);
}
}
impl Drop for ControlLock {
fn drop(&mut self) {
let _ = std::fs::remove_file(&self.owner);
sys::unlock(&self.file);
}
}
#[cfg(windows)]
mod sys {
use std::fs::File;
use std::os::windows::io::AsRawHandle;
use windows_sys::Win32::Storage::FileSystem::{LockFile, UnlockFile};
/// `LockFile` on byte 0, length 1: the call `msvcrt.locking` makes. Non-blocking.
pub fn try_lock(file: &File) -> std::io::Result<bool> {
let ok = unsafe { LockFile(file.as_raw_handle() as _, 0, 0, 1, 0) };
if ok != 0 {
return Ok(true);
}
let err = std::io::Error::last_os_error();
// ERROR_LOCK_VIOLATION (33): someone else holds it.
if err.raw_os_error() == Some(33) {
Ok(false)
} else {
Err(err)
}
}
pub fn unlock(file: &File) {
unsafe {
UnlockFile(file.as_raw_handle() as _, 0, 0, 1, 0);
}
}
}
#[cfg(not(windows))]
mod sys {
use std::fs::File;
pub fn try_lock(_: &File) -> std::io::Result<bool> {
Ok(true)
}
pub fn unlock(_: &File) {}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_damaged_record_is_no_process() {
let d = tempfile::tempdir().unwrap();
std::fs::create_dir_all(dir(d.path())).unwrap();
std::fs::write(dir(d.path()).join("mysql.json"), [0u8; 116]).unwrap();
assert!(running(d.path(), "mysql").is_none());
std::fs::write(dir(d.path()).join("auth.json"), b"").unwrap();
assert!(running(d.path(), "auth").is_none());
}
#[test]
fn this_process_is_recorded_and_found_running() {
let d = tempfile::tempdir().unwrap();
let me = record(d.path(), "probe", std::process::id()).unwrap();
assert_eq!(running(d.path(), "probe"), Some(me));
let text = std::fs::read_to_string(dir(d.path()).join("probe.json")).unwrap();
assert!(text.starts_with("{\n \"pid\": ") && text.ends_with("}\n"), "{text}");
}
#[test]
fn one_action_at_a_time() {
let d = tempfile::tempdir().unwrap();
let first = ControlLock::acquire(d.path(), "start-all", Duration::from_secs(1), &|_| {}).unwrap();
let owner: serde_json::Value = fsx::read_json(&dir(d.path()).join("control-owner.json")).unwrap();
assert_eq!(owner["action"], "start-all");
let said = std::sync::Mutex::new(Vec::new());
let second = ControlLock::acquire(d.path(), "stop-all", Duration::from_millis(600), &|m| said.lock().unwrap().push(m.to_string()));
if cfg!(windows) {
let err = second.err().expect("the second action waits and gives up").to_string();
assert!(err.contains("Another start/stop action is in progress") && err.contains("start-all"), "{err}");
assert_eq!(said.lock().unwrap().len(), 1);
}
drop(first);
assert!(!dir(d.path()).join("control-owner.json").exists());
ControlLock::acquire(d.path(), "stop-all", Duration::from_secs(1), &|_| {}).unwrap();
}
}
+300
View File
@@ -0,0 +1,300 @@
//! The world server and the bug-report relay beside it (`manage.py start_world`, `watch_world`, `wait_relay`),
//! and the detailed-logging switch (`debug_logs`).
//!
//! A world is started through a supervisor process that outlives the caller: it starts `worldserver.exe`, keeps
//! the relay running while the world runs, and stops the relay when the world ends. The supervisor is
//! `coa-launcher.exe watch-world`, or `manage.py watch-world` on a repack that does not ship it yet (both write
//! the same records). The relay itself is still the Python `BugReport/relay.py`, run through the repack's
//! Python, until it is ported too.
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};
use crate::error::{Error, ErrorCode, Result};
use crate::launcher::services::{self, ensure_free, mysql, spawn, start_mysql, wait_ready, Progress};
use crate::launcher::spawn::Proc;
use crate::launcher::{settings::Settings, squid, state};
fn stop_relay_flag(root: &Path) -> std::path::PathBuf {
state::dir(root).join("stop-relay")
}
/// The relay is up and has finished starting (it records itself as `relay-ready` once it serves).
pub fn wait_relay(root: &Path) -> Result<()> {
let until = Instant::now() + Duration::from_secs(20);
while Instant::now() < until {
if let (Some(relay), Some(ready)) = (state::running(root, "relay"), state::running(root, "relay-ready")) {
if relay == ready {
return Ok(());
}
}
std::thread::sleep(Duration::from_millis(250));
}
Err(Error::Invalid("Bug-report relay is not ready; check BugReport/Logs/relay.log.".into()))
}
/// The process that runs `watch-world` for a started world.
#[derive(Debug, Clone)]
pub enum Supervisor {
/// `coa-launcher.exe` (this crate's launcher).
Launcher(PathBuf),
/// The repack's Python with `Scripts/manage.py`.
Python { python: PathBuf, script: PathBuf },
}
impl Supervisor {
/// The supervisor a repack ships: `Scripts/coa-launcher.exe` when present, otherwise its Python launcher.
pub fn of(root: &Path) -> Result<Supervisor> {
let exe = root.join("Scripts/coa-launcher.exe");
if exe.is_file() {
return Ok(Supervisor::Launcher(exe));
}
let python = squid::package_root(root).join("Runtime/python/python.exe");
let script = root.join("Scripts/manage.py");
if python.is_file() && script.is_file() {
return Ok(Supervisor::Python { python, script });
}
Err(Error::Service(
ErrorCode::ServerFilesIncomplete,
"This server has no world supervisor (Scripts/coa-launcher.exe or Scripts/manage.py). Repair its program files.".into(),
))
}
}
/// How long a world may take to open both of its listeners, together: slow worlds (many bots, a cold disk) are
/// common, and the limit must not depend on the bot module.
const WORLD_STARTUP_SECONDS: u64 = 1500;
/// Wait until the world's console answers a command (it can listen before it accepts logins).
fn wait_console(root: &Path, cfg: &Settings, until: Instant) -> Result<()> {
let mut last = String::new();
while Instant::now() < until {
if state::running(root, "world").is_none() {
return Err(Error::Service(
ErrorCode::StartupFailed,
"World startup failed: worldserver stopped before its console accepted commands.".into(),
));
}
match crate::ra::Ra::connect_to(cfg.ra_port, &cfg.ra_username, &cfg.ra_password).and_then(|mut ra| ra.run("server info")) {
Ok(_) => return Ok(()),
Err(e) => last = e.to_string(),
}
std::thread::sleep(Duration::from_millis(500));
}
Err(Error::Service(ErrorCode::StartupFailed, format!("World startup failed: its console is still starting. {last}")))
}
fn seconds_until(until: Instant) -> u64 {
until.saturating_duration_since(Instant::now()).as_secs()
}
/// Start the world (and its database, unless it is shared), and wait until its console accepts commands.
pub fn start_world(root: &Path, cfg: &Settings, offset: i32, supervisor: &Supervisor, progress: Progress) -> Result<()> {
start_mysql(root, cfg, progress)?;
squid::validate_bots(root)?;
let until = Instant::now() + Duration::from_secs(squid::startup_timeout(root).max(WORLD_STARTUP_SECONDS));
if state::running(root, "world").is_some() {
if state::running(root, "supervisor").is_none() {
return Err(Error::Service(
ErrorCode::WorldserverAlreadyRunning,
"Worldserver has no repack supervisor. Use Stop_All_Server.bat before restarting it.".into(),
));
}
wait_ready(root, "world", cfg.world_port, seconds_until(until))?;
wait_relay(root)?;
wait_console(root, cfg, until)?;
progress("Worldserver and bug-report relay are already running.");
return Ok(());
}
ensure_free(cfg.world_port, progress)?;
ensure_free(cfg.ra_port, progress)?;
if state::running(root, "supervisor").is_some() || state::running(root, "relay").is_some() {
return Err(Error::Service(
ErrorCode::OperationInProgress,
"The previous world/relay shutdown is still finishing. Try again shortly.".into(),
));
}
squid::prepare_playerbots(root, cfg.mysql_port, &|sql| mysql(root, Some(sql), None), progress)?;
progress("Starting worldserver and its bug-report relay...");
let _ = std::fs::remove_file(stop_relay_flag(root));
let offset_text = offset.to_string();
let root_text = root.to_string_lossy().into_owned();
let log = root.join("Core/Logs/supervisor.log");
match supervisor {
Supervisor::Launcher(exe) => {
spawn(root, "supervisor", exe, &["--root", &root_text, "--port-offset", &offset_text, "watch-world"], root, &log, &cfg.env_remove)?
}
Supervisor::Python { python, script } => {
let script = script.to_string_lossy().into_owned();
spawn(root, "supervisor", python, &["-B", &script, "--port-offset", &offset_text, "watch-world"], root, &log, &cfg.env_remove)?
}
};
let first = Instant::now() + Duration::from_secs(20);
while state::running(root, "world").is_none() && Instant::now() < first {
if state::running(root, "supervisor").is_none() {
return Err(Error::Service(ErrorCode::StartupFailed, "World startup failed; check Core/Logs/supervisor.log.".into()));
}
std::thread::sleep(Duration::from_millis(250));
}
wait_ready(root, "world", cfg.world_port, seconds_until(until))?;
wait_ready(root, "world", cfg.ra_port, seconds_until(until))?;
wait_relay(root)?;
wait_console(root, cfg, until)?;
progress("Worldserver and automatic bug reporting are ready.");
Ok(())
}
fn spawn_child(root: &Path, name: &str, exe: &Path, args: &[&str], cwd: &Path, log: &Path) -> Result<Proc> {
// The supervisor was started with the environment its services should have.
let child = crate::launcher::spawn::start(exe, args, cwd, log, &[])?;
state::record(root, name, child.pid)?;
Ok(child)
}
/// The relay worker: `coa-launcher relay-worker` when the supervisor is the launcher (`launcher`), otherwise the
/// repack's Python running `Scripts/manage.py relay-worker` (BugReport/relay.py).
fn spawn_relay(root: &Path, launcher: Option<&Path>) -> Result<Proc> {
let log = root.join("BugReport/Logs/relay.log");
if let Some(exe) = launcher {
let root_text = root.to_string_lossy().into_owned();
return spawn_child(root, "relay", exe, &["--root", &root_text, "relay-worker"], root, &log);
}
let python = squid::package_root(root).join("Runtime/python/python.exe");
let manage = root.join("Scripts/manage.py");
if !python.is_file() || !manage.is_file() {
return Err(Error::Invalid("The bug-report relay needs the repack's Python and Scripts/manage.py.".into()));
}
let manage = manage.to_string_lossy().into_owned();
spawn_child(root, "relay", &python, &["-B", &manage, "relay-worker"], root, &root.join("BugReport/Logs/relay.log"))
}
/// The supervisor (`watch-world`): run the world, keep the relay alive while it runs, stop the relay after it.
/// `launcher` is the launcher executable that runs the relay (`None`: the Python relay).
pub fn watch_world(root: &Path, launcher: Option<&Path>, log: Progress) -> Result<()> {
squid::validate_bots(root)?;
let world = spawn_child(root, "world", &root.join("Core/worldserver.exe"), &["-c", "configs/worldserver.conf"], &root.join("Core"), &root.join("Core/Logs/world-console.log"))?;
let mut relay: Option<Proc> = None;
while world.try_wait().is_none() {
let dead = relay.as_ref().is_none_or(|r| r.try_wait().is_some());
if dead {
match spawn_relay(root, launcher) {
Ok(r) => relay = Some(r),
Err(e) => {
log(&format!("Report relay could not start ({e}); retrying."));
std::thread::sleep(Duration::from_secs(5));
continue;
}
}
}
std::thread::sleep(Duration::from_secs(2));
}
std::fs::write(stop_relay_flag(root), b"")?;
if let Some(r) = relay {
let until = Instant::now() + Duration::from_secs(40);
while r.try_wait().is_none() && Instant::now() < until {
std::thread::sleep(Duration::from_millis(250));
}
if r.try_wait().is_none() {
// An interrupted POST stays uncertain in the relay's journal; it is not resent.
if let Some(record) = state::running(root, "relay") {
services::terminate(&record)?;
}
}
}
Ok(())
}
// ---------------------------------------------------------------------------------------------------------------
// Detailed logging (Debug_Logs_On.bat / Debug_Logs_Off.bat)
// ---------------------------------------------------------------------------------------------------------------
const DEBUG_TEMPLATES: [&str; 2] = ["worldserver.conf.template", "authserver.conf.template"];
/// One template line with every logger forced to Trace and the console/server appenders to the most detail.
fn debug_line(line: &str) -> String {
let body = line.strip_prefix('#').unwrap_or(line).trim_start();
for appender in ["Appender.Console", "Appender.Server"] {
if let Some(rest) = body.strip_prefix(appender).and_then(|r| r.strip_prefix('=')) {
let parts: Vec<&str> = rest.splitn(4, ',').collect();
if parts.len() == 4 && parts[..3].iter().all(|p| !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit())) {
return format!("{appender}={},6,7,{}", parts[0], parts[3]);
}
}
}
if let Some(rest) = body.strip_prefix("Logger.") {
if let Some((name, value)) = rest.split_once('=') {
if !name.is_empty() && name.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'.') {
if let Some((level, tail)) = value.split_once(',') {
if !level.is_empty() && level.bytes().all(|b| b.is_ascii_digit()) {
return format!("Logger.{name}=6,{tail}");
}
}
}
}
}
let t = line.trim_end();
if let Some(v) = t.strip_prefix("Log.Async.Enable") {
let v = v.trim_start();
if let Some(n) = v.strip_prefix('=') {
let n = n.trim();
if !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()) {
return "Log.Async.Enable = 1".into();
}
}
}
line.to_string()
}
/// Turn detailed logging on or off (the templates; services apply it at their next start). Returns the changed
/// templates.
pub fn debug_logs(root: &Path, enable: bool) -> Result<Vec<String>> {
let mut changed = Vec::new();
for name in DEBUG_TEMPLATES {
let path = root.join("Settings").join(name);
let original = root.join("Settings").join(format!("{name}.original"));
if !original.exists() {
std::fs::write(&original, std::fs::read(&path)?)?;
}
let new_bytes = if enable {
let text = String::from_utf8(std::fs::read(&original)?).map_err(|_| Error::Invalid(format!("{name} is not UTF-8.")))?;
let newline = if text.contains("\r\n") { "\r\n" } else { "\n" };
let mut out = text.lines().map(debug_line).collect::<Vec<_>>().join(newline);
if text.ends_with('\n') {
out.push_str(newline);
}
out.into_bytes()
} else {
std::fs::read(&original)?
};
if std::fs::read(&path)? != new_bytes {
std::fs::write(&path, &new_bytes)?;
changed.push(name.to_string());
}
}
state::write_json(&state::dir(root).join("debug-logs.json"), &serde_json::json!({ "enabled": enable }))?;
Ok(changed)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn detailed_logging_rewrites_loggers_and_restores_the_original() {
let d = tempfile::tempdir().unwrap();
std::fs::create_dir_all(d.path().join("Settings")).unwrap();
let world = "Appender.Console=1,3,0\r\nAppender.Server=2,2,0,Server.log,w\r\n#Logger.module=4,Console Server\r\nLogger.root=5,Console Server\r\nLog.Async.Enable = 0\r\nOther = 1\r\n";
std::fs::write(d.path().join("Settings/worldserver.conf.template"), world).unwrap();
std::fs::write(d.path().join("Settings/authserver.conf.template"), "Logger.root=2,Console\n").unwrap();
let changed = debug_logs(d.path(), true).unwrap();
assert_eq!(changed.len(), 2);
assert_eq!(
std::fs::read_to_string(d.path().join("Settings/worldserver.conf.template")).unwrap(),
"Appender.Console=1,3,0\r\nAppender.Server=2,6,7,Server.log,w\r\nLogger.module=6,Console Server\r\nLogger.root=6,Console Server\r\nLog.Async.Enable = 1\r\nOther = 1\r\n"
);
assert_eq!(debug_logs(d.path(), true).unwrap().len(), 0, "already on");
debug_logs(d.path(), false).unwrap();
assert_eq!(std::fs::read_to_string(d.path().join("Settings/worldserver.conf.template")).unwrap(), world);
assert_eq!(services::status(d.path())["debugLogs"], false);
}
}
+222
View File
@@ -0,0 +1,222 @@
//! `Scripts/manage.py` as Managers up to 0.9.10 edited it.
//!
//! Those Managers ran the repack's Python launcher themselves and changed its text: an import fix for their bridge
//! and a realm-profile patch (database and realm row of the active realm). This Manager starts servers with
//! [`crate::launcher`] and never edits the file; it only has to recognise those edits, so that an update or a file
//! check treats a file one of them changed as unmodified. Nothing here writes a file.
use crate::error::{Error, Result};
const LAUNCHER_REALM_REPLACEMENTS: &[(&str, &str)] = &[
("(\"WorldDatabaseInfo\", \"acore_world\")", "(\"WorldDatabaseInfo\", \"acore_world_wildcard\" if coa_realm() == 'wildcard' else \"acore_world\")"),
("(\"CharacterDatabaseInfo\", \"acore_characters\")", "(\"CharacterDatabaseInfo\", \"acore_characters_wildcard\" if coa_realm() == 'wildcard' else \"acore_characters\")"),
("SET name='AzerothCore',address=", "SET name='{coa_realm_name()}',address="),
("WHERE id=1;", "WHERE id={coa_realm_id()};"),
("mysql(\"UPDATE acore_auth.realmlist SET flag=0", "mysql(f\"UPDATE acore_auth.realmlist SET flag=0"),
];
const LAUNCHER_REALM_INSERT: &str = "# coa-manager-realm-profiles-v1\ndef coa_realm():\n path = ROOT / 'Settings/realm-profile.json'\n return json.loads(path.read_text(encoding='utf-8')).get('active', 'coa') if path.exists() else 'coa'\n\ndef coa_realm_id():\n return 2 if coa_realm() == 'wildcard' else 1\n\ndef coa_realm_name():\n return 'Wildcard' if coa_realm() == 'wildcard' else 'Conquest of Azeroth'\n\n";
fn launcher_insert() -> String {
LAUNCHER_REALM_INSERT
.replace("profiles-v1", "profiles-v2")
.replace(
"return 2 if",
"return 3 if coa_realm() == 'reborn' else 2 if",
)
.replace(
"return 'Wildcard' if",
"return 'Warcraft Reborn' if coa_realm() == 'reborn' else 'Wildcard' if",
)
}
fn launcher_replacements() -> Vec<(&'static str, String)> {
LAUNCHER_REALM_REPLACEMENTS.iter().map(|(from, to)| (*from, to
.replace("\"acore_world_wildcard\" if", "\"acore_world_reborn\" if coa_realm() == 'reborn' else \"acore_world_wildcard\" if")
.replace("\"acore_characters_wildcard\" if", "\"acore_characters_reborn\" if coa_realm() == 'reborn' else \"acore_characters_wildcard\" if"))).collect()
}
/// The realm-profile patch older Managers wrote.
pub(crate) fn patch_launcher(source: &str) -> Result<String> {
if source.contains("# coa-manager-realm-profiles-v2") {
return Ok(source.into());
}
if source.contains("# coa-manager-realm-profiles-v1") {
let original = unpatch_launcher(source)
.ok_or_else(|| Error::Invalid("Unrecognised realm launcher patch.".into()))?;
return patch_launcher(&original);
}
let mut out = source.to_string();
for (from, to) in launcher_replacements() {
if !out.contains(from) {
return Err(Error::Invalid(
"This launcher does not support realm profiles. Update the server package first."
.into(),
));
}
out = out.replace(from, &to);
}
// Insert before the entry point so ROOT, json and functions are all defined when called.
let marker = "if __name__ == \"__main__\":";
if !out.contains(marker) {
return Err(Error::Invalid(
"Unrecognised server launcher entry point.".into(),
));
}
Ok(out.replace(marker, &format!("{}{marker}", launcher_insert())))
}
/// Reverse only our exact realm transformation; callers must verify the recovered original hash.
pub(crate) fn unpatch_launcher(source: &str) -> Option<String> {
let (insert, replacements) = if source.contains(&launcher_insert()) {
(launcher_insert(), launcher_replacements())
} else if source.contains(LAUNCHER_REALM_INSERT) {
(
LAUNCHER_REALM_INSERT.into(),
LAUNCHER_REALM_REPLACEMENTS
.iter()
.map(|(a, b)| (*a, b.to_string()))
.collect(),
)
} else {
return None;
};
let mut original = source.replacen(&insert, "", 1);
for (from, to) in &replacements {
original = original.replace(to, from);
}
let mut check = original.clone();
for (from, to) in &replacements {
check = check.replace(from, to);
}
check = check.replace(
"if __name__ == \"__main__\":",
&format!("{insert}if __name__ == \"__main__\":"),
);
(check == source).then_some(original)
}
/// The import fix older Managers wrote (needed to run manage.py through their bridge).
pub(crate) fn patch_launcher_imports(text: &str) -> Result<String> {
let line = "sys.path.insert(0, str(Path(__file__).resolve().parent))";
if !text.contains("from squid_playerbots import") || text.contains(line) {
return Ok(text.into());
}
let root = "ROOT = Path(__file__).resolve().parents[1]";
if !text.contains(root) || !text.lines().any(|line| line.trim() == "import sys") {
return Err(Error::Invalid(
"The server launcher cannot load its integration scripts. Repair its program files."
.into(),
));
}
Ok(text.replacen(root, &format!("{root}\n{line}"), 1))
}
pub(crate) fn launcher_matches(signed: &str, actual: &[u8]) -> bool {
if signed.as_bytes() == actual {
return true;
}
if patch_launcher_imports(signed).is_ok_and(|s| s.as_bytes() == actual) {
return true;
}
patch_launcher(signed).is_ok_and(|s| {
s.as_bytes() == actual || patch_launcher_imports(&s).is_ok_and(|p| p.as_bytes() == actual)
})
}
/// Recover legacy metadata only when undoing supported Manager edits reproduces the recorded hash.
pub(crate) fn launcher_matches_recorded(recorded: &str, actual: &[u8]) -> bool {
let Ok(text) = std::str::from_utf8(actual) else {
return false;
};
let without_import = text.replacen(
"ROOT = Path(__file__).resolve().parents[1]\nsys.path.insert(0, str(Path(__file__).resolve().parent))",
"ROOT = Path(__file__).resolve().parents[1]", 1,
);
for candidate in [
Some(without_import.clone()),
unpatch_launcher(&without_import),
]
.into_iter()
.flatten()
{
if crate::fsx::sha256_bytes(candidate.as_bytes()).eq_ignore_ascii_case(recorded)
&& launcher_matches(&candidate, actual)
{
return true;
}
}
false
}
#[cfg(test)]
mod tests {
use super::*;
use crate::fsx;
use std::collections::BTreeMap;
use std::fs;
#[test]
fn old_launcher_upgrades_and_both_patch_versions_are_reversible() {
let original = "(\"WorldDatabaseInfo\", \"acore_world\")\n(\"CharacterDatabaseInfo\", \"acore_characters\")\nSET name='AzerothCore',address=\nWHERE id=1;\nmysql(\"UPDATE acore_auth.realmlist SET flag=0\nif __name__ == \"__main__\":\n";
let mut old = original.to_string();
for (from, to) in LAUNCHER_REALM_REPLACEMENTS {
old = old.replace(from, to);
}
old = old.replace(
"if __name__ == \"__main__\":",
&format!("{LAUNCHER_REALM_INSERT}if __name__ == \"__main__\":"),
);
assert_eq!(unpatch_launcher(&old).as_deref(), Some(original));
let new = patch_launcher(&old).unwrap();
assert!(new.contains("acore_world_reborn"));
assert!(new.contains("return 3 if coa_realm() == 'reborn'"));
assert!(new.contains("return 'Warcraft Reborn' if"));
assert_eq!(patch_launcher(&new).unwrap(), new);
assert_eq!(unpatch_launcher(&new).as_deref(), Some(original));
}
#[test]
fn unknown_launcher_is_refused_without_partial_patching() {
assert!(patch_launcher("print('custom launcher')").is_err());
}
#[test]
fn launcher_import_fix_is_idempotent_and_retains_other_code() {
let text = "import sys\nROOT = Path(__file__).resolve().parents[1]\nfrom squid_playerbots import validate_bots\ncustom = 42\n";
let fixed = patch_launcher_imports(text).unwrap();
assert!(fixed.contains("sys.path.insert(0, str(Path(__file__).resolve().parent))"));
assert!(fixed.ends_with("custom = 42\n"));
assert_eq!(patch_launcher_imports(&fixed).unwrap(), fixed);
}
#[test]
fn a_launcher_patched_by_an_older_manager_stays_pristine_but_external_edits_conflict() {
let d = tempfile::tempdir().unwrap();
let root = d.path().join("server");
let source = "(\"WorldDatabaseInfo\", \"acore_world\")\n(\"CharacterDatabaseInfo\", \"acore_characters\")\nSET name='AzerothCore',address=\nWHERE id=1;\nmysql(\"UPDATE acore_auth.realmlist SET flag=0\nif __name__ == \"__main__\":\n";
fsx::atomic_write(&root.join("Scripts/manage.py"), source.as_bytes()).unwrap();
// What an older Manager left: the realm patch applied and its hash recorded as the pristine one.
let patched = patch_launcher(source).unwrap();
fsx::atomic_write(&root.join("Scripts/manage.py"), patched.as_bytes()).unwrap();
let mut meta = crate::registry::InstallMeta::new(crate::registry::InstallKind::New, &root);
meta.original_hashes.insert("Scripts/manage.py".into(), fsx::sha256_bytes(patched.as_bytes()));
crate::registry::MetaDir::create(&root, &meta).unwrap();
assert!(crate::diag::verify_managed(&root, &meta).is_empty());
let manifest: crate::manifest::Manifest = serde_json::from_value(serde_json::json!({
"schema": 1, "kind": "update", "version": "2.0.0", "core": {"commit": null}, "builtAt": "fixture", "minManagerVersion": "0.1.0",
"files": [{"path":"Scripts/manage.py","sha256":fsx::sha256_bytes(b"next release"),"size":12,"owner":"core","policy":"replace"}]
})).unwrap();
assert_eq!(
crate::update::plan(&root, &meta, &manifest, &BTreeMap::new(), None).unwrap()[0].action,
crate::update::Action::Replace
);
let mut modified = fs::read(root.join("Scripts/manage.py")).unwrap();
modified.extend_from_slice(b"# custom edit\n");
fsx::atomic_write(&root.join("Scripts/manage.py"), &modified).unwrap();
assert_eq!(
crate::update::plan(&root, &meta, &manifest, &BTreeMap::new(), None).unwrap()[0].action,
crate::update::Action::Conflict
);
}
}
+6
View File
@@ -11,8 +11,10 @@ pub mod accounts;
pub mod allsettings;
pub mod backup;
pub mod channels;
pub mod character_start_check;
pub mod cleanbase;
pub mod client;
pub mod client_graphics;
pub mod clientdl;
pub mod companions;
pub mod config;
@@ -26,6 +28,7 @@ pub mod diag;
pub mod docker;
pub mod download;
pub mod driver;
pub mod legacy_launcher;
pub mod error;
pub mod firewall;
pub mod friends;
@@ -34,7 +37,9 @@ pub mod glue_config;
pub mod health;
pub mod install;
pub mod layout;
pub mod launcher;
pub mod logging;
pub mod server_logging;
pub mod manifest;
pub mod migrations;
pub mod modules;
@@ -54,6 +59,7 @@ pub mod realmlist;
pub mod realms;
pub mod registry;
pub mod release;
pub mod release_history;
pub mod release_schema;
pub mod remote_client;
pub mod repair;
+101 -1
View File
@@ -307,6 +307,51 @@ pub struct Item {
pub error: Option<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Audit {
pub total: usize,
pub applied: usize,
pub checksum_verified: usize,
pub legacy_unknown: usize,
}
pub fn inventory_sha256(list: &[Migration]) -> Result<String> {
let inventory: Vec<_> = list
.iter()
.map(|m| (&m.db, &m.id, &m.sha256, &m.compatible_sha256, m.destructive))
.collect();
Ok(fsx::sha256_bytes(&serde_json::to_vec(&inventory)?))
}
pub fn audit_applied(store: &dyn Store, list: &[Migration]) -> Result<Audit> {
let rows = store.load_readonly()?;
check_history(&rows, list)?;
let mut audit = Audit {
total: list.len(),
applied: 0,
checksum_verified: 0,
legacy_unknown: 0,
};
for migration in list {
let row = recorded(&rows, migration)
.filter(|r| r.status == Status::Applied)
.ok_or_else(|| {
Error::Invalid(format!(
"Release migration {} ({}) is not recorded as applied.",
migration.id, migration.db
))
})?;
audit.applied += 1;
if row.sha256 == "0".repeat(64) {
audit.legacy_unknown += 1;
} else {
audit.checksum_verified += 1;
}
}
Ok(audit)
}
pub fn status(store: &dyn Store, list: &[Migration]) -> Result<Vec<Item>> {
let rows = store.load()?;
Ok(list
@@ -358,7 +403,7 @@ fn preserve_auth_history(store: &dyn Store, rows: &[LedgerRow], list: &[Migratio
}
/// Migrations that were published with different bytes but have the same effect, so a server that applied either
/// version accepts the other. The Wildcard table repair went out as `c1d8…` (0.261005.0, 0.261006.1) and as `9e4a…`
/// version accepts the other. The Wildcard table repair went out as `c1d8…` (0.261005.0, 0.261006.1) and as `9e4a…`
/// (0.261005.22, 0.261007.24); the packages carry no list of compatible versions, so the Manager knows this pair.
const SAME_EFFECT: &[(&str, &[&str])] = &[(
"manager_repair__20261005_missing_wildcard_tables",
@@ -667,6 +712,61 @@ mod tests {
}
}
#[test]
fn qualification_inventory_digest_matches_release_pipeline_encoding() {
let list = vec![Migration {
id: "one".into(),
db: "world".into(),
sha256: "a".repeat(64),
compatible_sha256: vec![],
destructive: false,
}];
assert_eq!(
inventory_sha256(&list).unwrap(),
"b35e45f666304500e69ff352f83103910075ace998afb7915b548765b8c30703"
);
}
#[test]
fn qualification_rejects_missing_interrupted_failed_and_changed_history() {
let (_dir, list) = setup(&[("world", "qualification_probe", "SELECT 1;")]);
let store = Mem::default();
assert!(audit_applied(&store, &list).is_err());
for status in [Status::Running, Status::Failed, Status::Pending] {
store
.put(&LedgerRow {
db: "world".into(),
id: list[0].id.clone(),
sha256: list[0].sha256.clone(),
status,
error: None,
baseline: false,
})
.unwrap();
assert!(audit_applied(&store, &list).is_err());
}
store
.put(&LedgerRow {
db: "world".into(),
id: list[0].id.clone(),
sha256: "a".repeat(64),
status: Status::Applied,
error: None,
baseline: false,
})
.unwrap();
assert!(audit_applied(&store, &list).is_err());
store.rows.borrow_mut()[0].sha256 = list[0].sha256.clone();
assert_eq!(audit_applied(&store, &list).unwrap().checksum_verified, 1);
store.rows.borrow_mut()[0].sha256 = "0".repeat(64);
let audit = audit_applied(&store, &list).unwrap();
assert_eq!(
(audit.applied, audit.checksum_verified, audit.legacy_unknown),
(1, 0, 1)
);
assert!(store.ran.borrow().is_empty());
}
fn setup(files: &[(&str, &str, &str)]) -> (tempfile::TempDir, Vec<Migration>) {
let d = tempfile::tempdir().unwrap();
let mut list = Vec::new();
+47 -3
View File
@@ -197,7 +197,13 @@ fn list_in(cat: &[Entry], root: &Path) -> Vec<ModuleView> {
.and_then(|c| c.get(&e.enable_key).map(truthy))
.unwrap_or(e.default_on)
};
let blocked = wildcard && matches!(e.id.as_str(), "companions" | "playerbots");
let dependency_missing = e.id == "dungeon-clear"
&& entry_in(cat, "playerbots")
.and_then(|entry| bot_enabled(root, &entry))
.map(|enabled| !enabled)
.unwrap_or(true);
let blocked = dependency_missing
|| (wildcard && matches!(e.id.as_str(), "companions" | "playerbots" | "dungeon-clear"));
let version = if e.id == "playerbots" {
crate::squid::release(root).map(|release| {
[
@@ -228,7 +234,9 @@ fn list_in(cat: &[Entry], root: &Path) -> Vec<ModuleView> {
};
ModuleView {
version,
compatibility: if blocked {
compatibility: if dependency_missing {
"requires-squid"
} else if blocked {
"unsupported"
} else if wildcard && e.id != "client-compat" {
"experimental"
@@ -296,7 +304,7 @@ fn require_bot_server_stopped(root: &Path) -> Result<()> {
pub fn set_enabled(root: &Path, meta: &Path, id: &str, on: bool) -> Result<()> {
let _update_lock = crate::update::operation_lock(meta)?;
crate::update::ensure_recovered(meta)?;
let _lock = if matches!(id, "companions" | "playerbots") {
let _lock = if matches!(id, "companions" | "playerbots" | "dungeon-clear") {
require_bot_server_stopped(root)?;
fs::create_dir_all(root.join(".state"))?;
let lock = fs::OpenOptions::new()
@@ -317,6 +325,9 @@ pub fn set_enabled(root: &Path, meta: &Path, id: &str, on: bool) -> Result<()> {
};
if on {
crate::realms::guard_module(root, id)?;
if id == "dungeon-clear" {
crate::realms::guard_module(root, "playerbots")?;
}
}
if id == "custom-races" {
if let Ok(meta_content) = fs::read_to_string(meta.join("install.json")) {
@@ -379,6 +390,9 @@ pub fn ensure_bot_exclusivity(root: &Path) -> Result<()> {
fn set_enabled_in(cat: &[Entry], root: &Path, meta: &Path, id: &str, on: bool) -> Result<()> {
let e = entry_in(cat, id)?;
if on && id == "dungeon-clear" && !bot_enabled(root, &entry_in(cat, "playerbots")?)? {
return Err(Error::Invalid("Enable SQUID bots before enabling Dungeon Clear.".into()));
}
if !e.switchable || e.enable_key.is_empty() {
return Err(Error::Invalid("This part cannot be switched off.".into()));
}
@@ -394,6 +408,15 @@ fn set_enabled_in(cat: &[Entry], root: &Path, meta: &Path, id: &str, on: bool) -
}
}
}
if (id == "playerbots" && !on) || (id == "companions" && on) {
if let Some(dependency) = cat.iter().find(|entry| entry.id == "dungeon-clear") {
if dir(root).join(&dependency.conf).exists()
|| dir(root).join(format!("{}.dist", dependency.conf)).exists()
{
set_enabled_in(cat, root, meta, "dungeon-clear", false)?;
}
}
}
let conf = active_file(root, &e)?;
let mut file = ConfFile::parse_bytes(&fs::read(&conf)?)?;
if file.get(&e.enable_key).map(truthy).unwrap_or(e.default_on) == on
@@ -818,6 +841,27 @@ mod tests {
);
}
#[test]
fn dungeon_clear_requires_squid_and_stays_off_after_squid_is_reenabled() {
let d = tempfile::tempdir().unwrap();
let root = d.path();
fs::create_dir_all(dir(root)).unwrap();
fs::write(dir(root).join("playerbots.conf"), "AiPlayerbot.Enabled = 0\n").unwrap();
fs::write(dir(root).join("mod_coa_playerbots.conf"), "CoaBots.Enable = 0\n").unwrap();
let dungeon = dir(root).join("mod_dungeon_clear.conf");
fs::write(&dungeon, "DungeonClear.Enable = 0\n").unwrap();
let cat = catalog();
assert!(set_enabled_in(&cat, root, root, "dungeon-clear", true).is_err());
assert!(!list_in(&cat, root).iter().find(|entry| entry.id == "dungeon-clear").unwrap().switchable);
set_enabled_in(&cat, root, root, "playerbots", true).unwrap();
set_enabled_in(&cat, root, root, "dungeon-clear", true).unwrap();
assert!(read(&dungeon).unwrap().get("DungeonClear.Enable").map(truthy).unwrap());
set_enabled_in(&cat, root, root, "playerbots", false).unwrap();
assert!(!read(&dungeon).unwrap().get("DungeonClear.Enable").map(truthy).unwrap());
set_enabled_in(&cat, root, root, "playerbots", true).unwrap();
assert!(!read(&dungeon).unwrap().get("DungeonClear.Enable").map(truthy).unwrap());
}
#[test]
fn bot_systems_are_mutually_exclusive_in_both_directions_and_manual_configs() {
let d = tempfile::tempdir().unwrap();
+18 -29
View File
@@ -176,7 +176,6 @@ fn set_tree(main: &Path, tree: Tree, enabled: bool) -> Result<realms::View> {
}
}
}
secondary_launcher(&fs::read_to_string(main.join("Scripts/manage.py"))?)?;
}
let status = process::observe(main, &crate::layout::read_ports(main));
if status.world.state != ServiceState::Stopped
@@ -349,25 +348,18 @@ fn prepare(main: &Path, tree: Tree) -> Result<PathBuf> {
..Default::default()
},
)?;
let source = fs::read_to_string(main.join("Scripts/manage.py"))?;
let source = secondary_launcher(&source)?;
fsx::atomic_write(&second.join("Scripts/manage.py"), source.as_bytes())?;
Ok(second)
}
fn secondary_launcher(source: &str) -> Result<String> {
let marker = "def start_world(config, offset):\n start_mysql(config)";
let source = source.replace("\r\n", "\n");
if !source.contains(marker) {
return Err(Error::Invalid(
"The launcher does not support a shared database world. Update the server first."
.into(),
));
// The world supervisor and the bug-report relay of the extra world (the launcher itself runs in the Manager
// and knows that this world shares the main database).
for script in ["Scripts/coa-launcher.exe", "Scripts/manage.py"] {
let target = second.join(script);
if main.join(script).is_file() {
fs::create_dir_all(second.join("Scripts"))?;
fsx::atomic_write(&target, &fs::read(main.join(script))?)?;
} else if target.exists() {
fs::remove_file(&target)?;
}
}
Ok(source.replace(
marker,
"def start_world(config, offset):\n mysql(admin=\"ping\")",
))
Ok(second)
}
fn start_tree(main: &Path, tree: Tree) -> Result<()> {
@@ -408,7 +400,7 @@ pub fn start(main: &Path) -> Result<()> {
fn stop_tree(main: &Path, tree: Tree) -> Result<()> {
let second = tree_root(main, tree);
if !second.join("Scripts/manage.py").exists() {
if !second.join("Settings/repack.json").exists() {
if tree_running(main, tree) {
return Err(Error::Invalid(format!(
"The running {}'s launcher is missing. The shared database was left running.",
@@ -497,15 +489,12 @@ mod tests {
)
.unwrap();
let err = set_reborn_enabled(t.path(), true).unwrap_err().to_string();
assert!(err.contains("Select Conquest of Azeroth first"), "{err}");
let expected = if cfg!(windows) {
"Select Conquest of Azeroth first"
} else {
"Simultaneous realms currently require Windows"
};
assert!(err.contains(expected), "{err}");
assert!(!realms::state(t.path()).unwrap().with_reborn);
}
#[test]
fn secondary_never_starts_the_shared_database() {
let patched = secondary_launcher("def start_world(config, offset):\r\n start_mysql(config)\r\n wait_ready('world', 8086)\r\n").unwrap();
assert!(patched.contains("mysql(admin=\"ping\")"));
assert!(!patched.contains("start_mysql(config)"));
assert!(secondary_launcher("def start_world(): pass").is_err());
}
}
+83
View File
@@ -1004,6 +1004,89 @@ mod tests {
};
let mut server = start();
db.query("CREATE DATABASE acore_characters; CREATE DATABASE acore_world; CREATE DATABASE acore_auth; CREATE TABLE acore_characters.probe(id INT PRIMARY KEY, note VARCHAR(40)); CREATE TABLE acore_world.probe(id INT NOT NULL DEFAULT 0); INSERT INTO acore_world.probe VALUES(43); CREATE TABLE acore_auth.probe(id INT); INSERT INTO acore_auth.probe VALUES(44); CREATE USER 'fixture_user'@'localhost' IDENTIFIED BY 'fixture'; CREATE TRIGGER acore_characters.probe_insert BEFORE INSERT ON acore_characters.probe FOR EACH ROW SET NEW.note='triggered'; INSERT INTO acore_characters.probe VALUES(42,'original'); CREATE VIEW acore_characters.probe_view AS SELECT c.id,w.id AS world_id FROM acore_characters.probe c CROSS JOIN acore_world.probe w; CREATE PROCEDURE acore_characters.probe_proc() SELECT id FROM acore_characters.probe; CREATE FUNCTION acore_characters.probe_func() RETURNS INT DETERMINISTIC RETURN 73;").unwrap();
// Regression: an upgrade must distinguish pre-existing unsupported character starts
// from a newly lost start, without weakening any structural schema check.
db.query("CREATE TABLE acore_characters.characters(guid INT UNSIGNED PRIMARY KEY,race INT UNSIGNED NOT NULL,class INT UNSIGNED NOT NULL); CREATE TABLE acore_world.playercreateinfo(race INT UNSIGNED,class INT UNSIGNED,PRIMARY KEY(race,class)); INSERT INTO acore_characters.characters VALUES(100,44,14),(101,44,14),(102,7,14);").unwrap();
let starts = [1, 2, 3, 4, 5, 6, 7, 8, 10, 11]
.into_iter()
.flat_map(|race| (12..=32).map(move |class| format!("({race},{class})")))
.collect::<Vec<_>>()
.join(",");
db.query(&format!(
"INSERT INTO acore_world.playercreateinfo VALUES {starts};"
))
.unwrap();
crate::schema_check::capture(&db, &root).unwrap();
let baseline = crate::character_start_check::capture(&db, &root).unwrap();
assert_eq!(baseline.realms[crate::realms::Mode::Coa.name()].len(), 2);
assert!(
!crate::schema_check::check(&db, &root).unwrap().is_empty(),
"ordinary diagnostics stay strict"
);
assert!(
crate::schema_check::check_update_with_report(&db, &root, Some(&baseline))
.unwrap()
.is_empty(),
"unchanged old gaps must not block an unrelated upgrade"
);
assert_eq!(
db.query("SELECT COUNT(*) FROM acore_characters.characters;")
.unwrap()
.trim(),
"3"
);
let report_dir = crate::registry::metadata_dir_for(&root)
.unwrap()
.join("diagnostics");
let report_path = fs::read_dir(report_dir)
.unwrap()
.flatten()
.map(|e| e.path())
.find(|p| {
p.file_name()
.unwrap()
.to_string_lossy()
.starts_with("schema-validation-")
})
.unwrap();
let report: serde_json::Value = fsx::read_json(&report_path).unwrap();
assert_eq!(report["preexistingUnsupportedCharacters"], 2);
assert_eq!(
report["preexistingCharacterStarts"],
serde_json::json!([{"race":44,"class":14,"count":2}])
);
assert_eq!(report["problems"], serde_json::json!([]));
// Same count and race/class but a different GUID must still block.
db.query("UPDATE acore_characters.characters SET guid=103 WHERE guid=101;")
.unwrap();
assert!(
!crate::schema_check::check_update_with_report(&db, &root, Some(&baseline))
.unwrap()
.is_empty()
);
db.query("UPDATE acore_characters.characters SET guid=101 WHERE guid=103;")
.unwrap();
// Loss of a formerly valid start is never grandfathered.
db.query("DELETE FROM acore_world.playercreateinfo WHERE race=7 AND class=14;")
.unwrap();
assert!(
!crate::schema_check::check_update_with_report(&db, &root, Some(&baseline))
.unwrap()
.is_empty()
);
db.query("INSERT INTO acore_world.playercreateinfo VALUES(7,14);")
.unwrap();
db.query("ALTER TABLE acore_world.probe MODIFY id VARCHAR(30) NOT NULL DEFAULT '0';")
.unwrap();
assert!(
!crate::schema_check::check_update_with_report(&db, &root, Some(&baseline))
.unwrap()
.is_empty(),
"existing character warnings cannot hide a structural failure"
);
db.query("ALTER TABLE acore_world.probe MODIFY id INT NOT NULL DEFAULT 0; DROP TABLE acore_characters.characters; DROP TABLE acore_world.playercreateinfo;").unwrap();
fs::remove_file(root.join(crate::schema_check::CONTRACT)).unwrap();
// Shared auth must not run again when the active realm changes.
use crate::migrations::Store;
db.query("CREATE DATABASE acore_world_wildcard;").unwrap();
+23
View File
@@ -88,6 +88,29 @@ impl Ra {
self.command(c)
}
/// Send a command whose answer does not matter (`server shutdown`). The reply is still read (up to the next
/// prompt, the end of the connection, or a few seconds): closing a socket that holds unread data resets the
/// connection, and the server can then drop the command it has not processed yet.
pub fn send_without_answer(mut self, cmd: &str) -> Result<()> {
let c = crate::console::check_command(cmd)?;
self.stream.write_all(format!("{c}\r\n").as_bytes())?;
self.stream.flush()?;
self.stream.set_read_timeout(Some(Duration::from_secs(10)))?;
let mut seen = Vec::new();
let mut buf = [0u8; 4096];
while let Ok(n) = self.stream.read(&mut buf) {
if n == 0 {
break;
}
seen.extend_from_slice(&buf[..n]);
if seen.ends_with(b"AC>") || seen.len() > 1 << 20 {
break;
}
}
let _ = self.stream.shutdown(std::net::Shutdown::Both);
Ok(())
}
fn command(&mut self, cmd: &str) -> Result<String> {
debug_assert!(!cmd.contains(['\r', '\n']));
self.stream.write_all(format!("{cmd}\r\n").as_bytes())?;
-196
View File
@@ -534,8 +534,6 @@ pub fn ensure_created(root: &Path, mode: Mode) -> Result<()> {
"Update the server to a build with Warcraft Reborn support first.".into(),
));
}
// Verify launcher support before creating databases, as selecting a realm does.
prepare_launcher(root)?;
let before = configs(root)?;
create_realm(root, &mut s, mode, &before)
}
@@ -565,8 +563,6 @@ pub fn select(root: &Path, mode: Mode) -> Result<View> {
"Disable the realms that start together before switching realms.".into(),
));
}
// Verify launcher support before creating databases or changing the selected realm.
prepare_launcher(root)?;
let before = configs(root)?;
fsx::atomic_write_json(&snapshot(root, s.active), &before)?;
create_realm(root, &mut s, mode, &before)?;
@@ -608,125 +604,6 @@ pub fn select(root: &Path, mode: Mode) -> Result<View> {
view(root)
}
/// Adapt the bundled launcher's canonical schema and realm choices without changing its supervision logic.
pub fn prepare_launcher(root: &Path) -> Result<()> {
// A Docker server has no launcher to adapt: the Docker backend reads the active realm itself.
if crate::docker::is_docker(root) {
return Ok(());
}
let path = root.join("Scripts/manage.py");
let source = fs::read_to_string(&path)?;
let patched = patch_launcher(&source)?;
if patched != source {
fsx::atomic_write(&path, patched.as_bytes())?;
// A Manager-owned transformation is still pristine for subsequent updates and file checks.
if let Ok(dir) = crate::registry::metadata_dir_for(root) {
if let Ok((_, mut meta)) = crate::registry::MetaDir::open(&dir) {
if meta
.original_hashes
.get("Scripts/manage.py")
.is_some_and(|hash| hash == &fsx::sha256_bytes(source.as_bytes()))
{
meta.original_hashes.insert(
"Scripts/manage.py".into(),
fsx::sha256_bytes(patched.as_bytes()),
);
fsx::atomic_write_json(&dir.join("install.json"), &meta)?;
}
}
}
}
Ok(())
}
const LAUNCHER_REALM_REPLACEMENTS: &[(&str, &str)] = &[
("(\"WorldDatabaseInfo\", \"acore_world\")", "(\"WorldDatabaseInfo\", \"acore_world_wildcard\" if coa_realm() == 'wildcard' else \"acore_world\")"),
("(\"CharacterDatabaseInfo\", \"acore_characters\")", "(\"CharacterDatabaseInfo\", \"acore_characters_wildcard\" if coa_realm() == 'wildcard' else \"acore_characters\")"),
("SET name='AzerothCore',address=", "SET name='{coa_realm_name()}',address="),
("WHERE id=1;", "WHERE id={coa_realm_id()};"),
("mysql(\"UPDATE acore_auth.realmlist SET flag=0", "mysql(f\"UPDATE acore_auth.realmlist SET flag=0"),
];
const LAUNCHER_REALM_INSERT: &str = "# coa-manager-realm-profiles-v1\ndef coa_realm():\n path = ROOT / 'Settings/realm-profile.json'\n return json.loads(path.read_text(encoding='utf-8')).get('active', 'coa') if path.exists() else 'coa'\n\ndef coa_realm_id():\n return 2 if coa_realm() == 'wildcard' else 1\n\ndef coa_realm_name():\n return 'Wildcard' if coa_realm() == 'wildcard' else 'Conquest of Azeroth'\n\n";
fn launcher_insert() -> String {
LAUNCHER_REALM_INSERT
.replace("profiles-v1", "profiles-v2")
.replace(
"return 2 if",
"return 3 if coa_realm() == 'reborn' else 2 if",
)
.replace(
"return 'Wildcard' if",
"return 'Warcraft Reborn' if coa_realm() == 'reborn' else 'Wildcard' if",
)
}
fn launcher_replacements() -> Vec<(&'static str, String)> {
LAUNCHER_REALM_REPLACEMENTS.iter().map(|(from, to)| (*from, to
.replace("\"acore_world_wildcard\" if", "\"acore_world_reborn\" if coa_realm() == 'reborn' else \"acore_world_wildcard\" if")
.replace("\"acore_characters_wildcard\" if", "\"acore_characters_reborn\" if coa_realm() == 'reborn' else \"acore_characters_wildcard\" if"))).collect()
}
pub(crate) fn patch_launcher(source: &str) -> Result<String> {
if source.contains("# coa-manager-realm-profiles-v2") {
return Ok(source.into());
}
if source.contains("# coa-manager-realm-profiles-v1") {
let original = unpatch_launcher(source)
.ok_or_else(|| Error::Invalid("Unrecognised realm launcher patch.".into()))?;
return patch_launcher(&original);
}
let mut out = source.to_string();
for (from, to) in launcher_replacements() {
if !out.contains(from) {
return Err(Error::Invalid(
"This launcher does not support realm profiles. Update the server package first."
.into(),
));
}
out = out.replace(from, &to);
}
// Insert before the entry point so ROOT, json and functions are all defined when called.
let marker = "if __name__ == \"__main__\":";
if !out.contains(marker) {
return Err(Error::Invalid(
"Unrecognised server launcher entry point.".into(),
));
}
Ok(out.replace(marker, &format!("{}{marker}", launcher_insert())))
}
/// Reverse only our exact realm transformation; callers must verify the recovered original hash.
pub(crate) fn unpatch_launcher(source: &str) -> Option<String> {
let (insert, replacements) = if source.contains(&launcher_insert()) {
(launcher_insert(), launcher_replacements())
} else if source.contains(LAUNCHER_REALM_INSERT) {
(
LAUNCHER_REALM_INSERT.into(),
LAUNCHER_REALM_REPLACEMENTS
.iter()
.map(|(a, b)| (*a, b.to_string()))
.collect(),
)
} else {
return None;
};
let mut original = source.replacen(&insert, "", 1);
for (from, to) in &replacements {
original = original.replace(to, from);
}
let mut check = original.clone();
for (from, to) in &replacements {
check = check.replace(from, to);
}
check = check.replace(
"if __name__ == \"__main__\":",
&format!("{insert}if __name__ == \"__main__\":"),
);
(check == source).then_some(original)
}
/// The character-creation model the world server advertises for a realm. Every realm has its own database and its own
/// entry on Overview, so it advertises exactly one model: a list such as `"coa wcr"` would let players create
/// Warcraft Reborn characters in the Conquest of Azeroth realm.
@@ -770,7 +647,6 @@ pub fn before_start(root: &Path) -> Result<()> {
if !root.join(STATE).exists() {
return Ok(());
}
prepare_launcher(root)?;
if s.simultaneous && !view(root)?.supported {
return Err(Error::Invalid(
"The installed server build does not support simultaneous Wildcard startup.".into(),
@@ -1107,26 +983,6 @@ CoA.GameModeMask = 0
assert!(!v.supported);
}
#[test]
fn old_launcher_upgrades_and_both_patch_versions_are_reversible() {
let original = "(\"WorldDatabaseInfo\", \"acore_world\")\n(\"CharacterDatabaseInfo\", \"acore_characters\")\nSET name='AzerothCore',address=\nWHERE id=1;\nmysql(\"UPDATE acore_auth.realmlist SET flag=0\nif __name__ == \"__main__\":\n";
let mut old = original.to_string();
for (from, to) in LAUNCHER_REALM_REPLACEMENTS {
old = old.replace(from, to);
}
old = old.replace(
"if __name__ == \"__main__\":",
&format!("{LAUNCHER_REALM_INSERT}if __name__ == \"__main__\":"),
);
assert_eq!(unpatch_launcher(&old).as_deref(), Some(original));
let new = patch_launcher(&old).unwrap();
assert!(new.contains("acore_world_reborn"));
assert!(new.contains("return 3 if coa_realm() == 'reborn'"));
assert!(new.contains("return 'Warcraft Reborn' if"));
assert_eq!(patch_launcher(&new).unwrap(), new);
assert_eq!(unpatch_launcher(&new).as_deref(), Some(original));
}
#[test]
fn a_docker_server_is_checked_for_wildcard_support_in_its_own_binary() {
let d = tempfile::tempdir().unwrap();
@@ -1157,20 +1013,6 @@ CoA.GameModeMask = 0
assert!(view(d.path()).unwrap().supported);
}
#[test]
fn a_docker_server_has_no_launcher_to_adapt() {
let d = tempfile::tempdir().unwrap();
fs::create_dir_all(d.path().join("Settings")).unwrap();
// No Scripts/manage.py anywhere: on a repack this fails, on a Docker server there is nothing to do.
assert!(prepare_launcher(d.path()).is_err());
fs::write(
d.path().join("Settings/docker.json"),
br#"{"project":"t1"}"#,
)
.unwrap();
prepare_launcher(d.path()).unwrap();
}
#[test]
fn fresh_wildcard_disables_bots_and_preserves_scaling() {
let mut f = Files::new();
@@ -1270,42 +1112,4 @@ CoA.GameModeMask = 0
.is_err());
assert!(guard_module(t.path(), "content-scaling").is_ok());
}
#[test]
fn unknown_launcher_is_refused_without_partial_patching() {
assert!(patch_launcher("print('custom launcher')").is_err());
}
#[test]
fn managed_launcher_patch_remains_pristine_but_external_edits_conflict() {
let d = tempfile::tempdir().unwrap();
let root = d.path().join("server");
let source = "(\"WorldDatabaseInfo\", \"acore_world\")\n(\"CharacterDatabaseInfo\", \"acore_characters\")\nSET name='AzerothCore',address=\nWHERE id=1;\nmysql(\"UPDATE acore_auth.realmlist SET flag=0\nif __name__ == \"__main__\":\n";
fsx::atomic_write(&root.join("Scripts/manage.py"), source.as_bytes()).unwrap();
let mut meta = crate::registry::InstallMeta::new(crate::registry::InstallKind::New, &root);
meta.original_hashes.insert(
"Scripts/manage.py".into(),
fsx::sha256_bytes(source.as_bytes()),
);
let dir = crate::registry::MetaDir::create(&root, &meta).unwrap();
prepare_launcher(&root).unwrap();
let (_, meta) = crate::registry::MetaDir::open(&dir.root).unwrap();
assert!(crate::diag::verify_managed(&root, &meta).is_empty());
let manifest: crate::manifest::Manifest = serde_json::from_value(serde_json::json!({
"schema": 1, "kind": "update", "version": "2.0.0", "core": {"commit": null}, "builtAt": "fixture", "minManagerVersion": "0.1.0",
"files": [{"path":"Scripts/manage.py","sha256":fsx::sha256_bytes(b"next release"),"size":12,"owner":"core","policy":"replace"}]
})).unwrap();
assert_eq!(
crate::update::plan(&root, &meta, &manifest, &BTreeMap::new(), None).unwrap()[0].action,
crate::update::Action::Replace
);
let mut modified = fs::read(root.join("Scripts/manage.py")).unwrap();
modified.extend_from_slice(b"# custom edit\n");
fsx::atomic_write(&root.join("Scripts/manage.py"), &modified).unwrap();
prepare_launcher(&root).unwrap();
assert_eq!(
crate::update::plan(&root, &meta, &manifest, &BTreeMap::new(), None).unwrap()[0].action,
crate::update::Action::Conflict
);
}
}
+69 -30
View File
@@ -21,22 +21,33 @@ pub struct SqlFile {
pub sha256: String,
}
fn sql_in(dir: &Path) -> Vec<PathBuf> {
let mut v: Vec<PathBuf> = fs::read_dir(dir)
.map(|rd| {
rd.flatten()
.map(|e| e.path())
.filter(|p| p.extension().map(|e| e == "sql").unwrap_or(false))
.collect()
})
.unwrap_or_default();
v.sort();
v
fn entries(dir: &Path) -> Result<Vec<fs::DirEntry>> {
match fs::read_dir(dir) {
Ok(rd) => Ok(rd.collect::<std::io::Result<Vec<_>>>()?),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(vec![]),
Err(error) => Err(error.into()),
}
}
fn sql_in(dir: &Path) -> Result<Vec<PathBuf>> {
let mut paths: Vec<_> = entries(dir)?
.into_iter()
.map(|entry| entry.path())
.filter(|path| path.extension().is_some_and(|ext| ext == "sql"))
.collect();
paths.sort();
Ok(paths)
}
/// The order in which files were first added to the repository (a pending script may rely on a table a module
/// created earlier). Files git does not know come last, in name order.
fn introduction_rank(repo: &Path, pathspecs: &[&str]) -> std::collections::HashMap<String, usize> {
fn introduction_rank(
repo: &Path,
pathspecs: &[&str],
) -> Result<std::collections::HashMap<String, usize>> {
if !repo.join(".git").exists() {
return Ok(Default::default());
}
let mut args = vec![
"log",
"--full-history",
@@ -48,18 +59,22 @@ fn introduction_rank(repo: &Path, pathspecs: &[&str]) -> std::collections::HashM
"--",
];
args.extend_from_slice(pathspecs);
let out = Command::new("git").current_dir(repo).args(&args).output();
let mut rank = std::collections::HashMap::new();
if let Ok(o) = out {
for (i, line) in String::from_utf8_lossy(&o.stdout)
.lines()
.filter(|l| l.ends_with(".sql"))
.enumerate()
{
rank.entry(line.to_string()).or_insert(i);
}
let out = Command::new("git").current_dir(repo).args(&args).output()?;
if !out.status.success() {
return Err(Error::Invalid(format!(
"Cannot establish SQL migration order: {}",
String::from_utf8_lossy(&out.stderr)
)));
}
rank
let mut rank = std::collections::HashMap::new();
for (i, line) in String::from_utf8_lossy(&out.stdout)
.lines()
.filter(|line| line.ends_with(".sql"))
.enumerate()
{
rank.entry(line.to_string()).or_insert(i);
}
Ok(rank)
}
/// Incremental SQL of a core checkout. Installation-only module bases must never be replayed on a live database.
@@ -91,7 +106,7 @@ fn collect_core_sql_mode(core: &Path, include_base: bool) -> Result<Vec<SqlFile>
("world", ["db_world", "pending_db_world"]),
] {
for d in dirs {
for f in sql_in(&core.join("data/sql/updates").join(d)) {
for f in sql_in(&core.join("data/sql/updates").join(d))? {
let stem = f.file_stem().unwrap().to_string_lossy().into_owned();
let rel = format!(
"data/sql/updates/{d}/{}",
@@ -101,8 +116,8 @@ fn collect_core_sql_mode(core: &Path, include_base: bool) -> Result<Vec<SqlFile>
}
}
}
if let Ok(rd) = fs::read_dir(core.join("modules")) {
let mut mods: Vec<_> = rd.flatten().collect();
{
let mut mods = entries(&core.join("modules"))?;
mods.sort_by_key(|e| e.file_name());
for m in mods {
let name = m.file_name().to_string_lossy().into_owned();
@@ -110,7 +125,7 @@ fn collect_core_sql_mode(core: &Path, include_base: bool) -> Result<Vec<SqlFile>
for kind in ["auth", "characters", "world"] {
let base = m.path().join(format!("data/sql/db-{kind}"));
for f in if include_base {
sql_in(&base.join("base"))
sql_in(&base.join("base"))?
} else {
vec![]
} {
@@ -121,7 +136,7 @@ fn collect_core_sql_mode(core: &Path, include_base: bool) -> Result<Vec<SqlFile>
);
push(kind, format!("mod_{mname}__base__{stem}"), f, rel)?;
}
for f in sql_in(&base) {
for f in sql_in(&base)? {
let stem = f.file_stem().unwrap().to_string_lossy().into_owned();
let rel = format!(
"modules/{name}/data/sql/db-{kind}/{}",
@@ -132,7 +147,7 @@ fn collect_core_sql_mode(core: &Path, include_base: bool) -> Result<Vec<SqlFile>
}
}
}
let rank = introduction_rank(core, &["data/sql/updates", "modules"]);
let rank = introduction_rank(core, &["data/sql/updates", "modules"])?;
out.sort_by_key(|f| rank.get(&f.origin).copied().unwrap_or(usize::MAX));
Ok(out)
}
@@ -155,7 +170,7 @@ pub fn export_baseline(server: &Path, out: &Path) -> Result<Vec<(String, u64)>>
/// SQL a bots module checkout ships for the characters database (its `dist/sql`).
pub fn collect_bots_sql(bots: &Path) -> Result<Vec<SqlFile>> {
let mut out = Vec::new();
for f in sql_in(&bots.join("dist/sql")) {
for f in sql_in(&bots.join("dist/sql"))? {
let stem = f.file_stem().unwrap().to_string_lossy().into_owned();
out.push(SqlFile {
db: "characters".into(),
@@ -364,6 +379,30 @@ mod tests {
fs::write(p, c).unwrap();
}
#[test]
fn sql_collection_rejects_broken_history_in_a_git_checkout() {
let dir = tempfile::tempdir().unwrap();
write(dir.path(), ".git", "gitdir: missing-history");
write(dir.path(), "data/sql/updates/db_world/one.sql", "SELECT 1;");
assert!(collect_core_sql(dir.path())
.unwrap_err()
.to_string()
.contains("migration order"));
}
#[test]
fn sql_collection_rejects_unreadable_directories_instead_of_omitting_migrations() {
let dir = tempfile::tempdir().unwrap();
write(dir.path(), "data/sql/updates/db_world", "not a directory");
assert!(collect_core_sql(dir.path()).is_err());
let bots = tempfile::tempdir().unwrap();
write(bots.path(), "dist/sql", "not a directory");
assert!(collect_bots_sql(bots.path()).is_err());
let modules = tempfile::tempdir().unwrap();
write(modules.path(), "modules", "not a directory");
assert!(collect_core_sql(modules.path()).is_err());
}
#[test]
fn collects_core_and_module_sql_with_module_base_first_and_stable_ids() {
let d = tempfile::tempdir().unwrap();
+229
View File
@@ -0,0 +1,229 @@
//! Read-only, bounded canonical histories. Offline fallback is also bundled in the UI.
use serde_json::Value;
use std::{io::Read, path::Path, time::Duration};
const LIMIT: u64 = 2 * 1024 * 1024;
fn repository(component: &str) -> Result<(&'static str, &'static str), String> {
match component {
"server" => Ok(("Corfirean/coa-server-build", "main")),
"manager" => Ok(("Corfirean/coa-server-manager", "master")),
_ => Err("Unknown release component".into()),
}
}
fn validate(bytes: &[u8], component: &str) -> Result<Value, String> {
let (repo, _) = repository(component)?;
if bytes.len() as u64 > LIMIT {
return Err("Release history is too large".into());
}
let value: Value = serde_json::from_slice(bytes).map_err(|e| e.to_string())?;
if value["schema"] != 1 || value["component"] != component || value["repository"] != repo {
return Err("Release history identity mismatch".into());
}
let releases = value["releases"].as_array().ok_or("Missing releases")?;
if releases.len() > 2000 {
return Err("Too many releases".into());
}
for release in releases {
if release.get("prerelease").is_some_and(|v| !v.is_boolean())
|| release.get("experimentalFeatures").is_some_and(|v| {
v.as_array()
.is_none_or(|items| items.iter().any(|item| !item.is_string()))
})
{
return Err("Invalid release flags".into());
}
for field in ["tag", "date"] {
if release[field]
.as_str()
.is_none_or(|s| s.is_empty() || s.len() > 100)
{
return Err("Invalid release metadata".into());
}
}
let version = release["version"].as_str().ok_or("Missing version")?;
if version.len() > 80
|| !version
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b".-+".contains(&b))
{
return Err("Invalid version".into());
}
let notes = release["notes"].as_array().ok_or("Missing notes")?;
if notes.len() > 500
|| notes
.iter()
.any(|n| n.as_str().is_none_or(|s| s.len() > 10000))
{
return Err("Invalid release notes".into());
}
}
Ok(value)
}
pub fn load(component: &str, cache_dir: &Path) -> Result<Value, String> {
load_for_target(component, cache_dir, None)
}
pub fn load_for_target(
component: &str,
cache_dir: &Path,
target: Option<&str>,
) -> Result<Value, String> {
let (repo, branch) = repository(component)?;
load_with_remote(component, cache_dir, target, || {
let client = reqwest::blocking::Client::builder()
.timeout(Duration::from_secs(8))
.redirect(reqwest::redirect::Policy::none())
.build()
.map_err(|e| e.to_string())?;
let response = client
.get(format!(
"https://raw.githubusercontent.com/{repo}/{branch}/changelog/history.json"
))
.query(&[("target", target.unwrap_or(""))])
.header(reqwest::header::CACHE_CONTROL, "no-cache")
.send()
.and_then(|r| r.error_for_status())
.map_err(|e| e.to_string())?;
let mut bytes = Vec::new();
response
.take(LIMIT + 1)
.read_to_end(&mut bytes)
.map_err(|e| e.to_string())?;
Ok(bytes)
})
}
fn load_with_remote(
component: &str,
cache_dir: &Path,
target: Option<&str>,
remote: impl FnOnce() -> Result<Vec<u8>, String>,
) -> Result<Value, String> {
repository(component)?;
let cache = cache_dir.join(format!("{component}.json"));
let cached = || {
let mut bytes = Vec::new();
std::fs::File::open(&cache)
.ok()?
.take(LIMIT + 1)
.read_to_end(&mut bytes)
.ok()?;
validate(&bytes, component).ok()
};
if cache
.metadata()
.and_then(|m| m.modified())
.ok()
.and_then(|t| t.elapsed().ok())
.is_some_and(|age| age < Duration::from_secs(3600))
{
if let Some(mut value) = cached() {
if target.is_none_or(|target| {
value["releases"].as_array().is_some_and(|releases| {
releases
.iter()
.any(|release| release["version"].as_str() == Some(target))
})
}) {
value["source"] = "cache".into();
return Ok(value);
}
}
}
let fetched = (|| {
let bytes = remote()?;
let mut value = validate(&bytes, component)?;
if std::fs::create_dir_all(cache_dir).is_ok() {
let _ = crate::fsx::atomic_write(&cache, &bytes);
}
value["source"] = "remote".into();
Ok(value)
})();
fetched.or_else(|error| {
cached()
.map(|mut value| {
value["source"] = "cache".into();
value
})
.ok_or(error)
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn accepts_both_complete_bundled_canonical_histories() {
assert!(validate(include_bytes!("../../../changelog/history.json"), "manager").is_ok());
assert!(validate(
include_bytes!("../../../src/data/server-history.json"),
"server"
)
.is_ok());
}
#[test]
fn rejects_cross_component_and_untrusted_components() {
let bytes = br#"{"schema":1,"component":"manager","repository":"Corfirean/coa-server-manager","releases":[]}"#;
assert!(validate(bytes, "manager").is_ok());
assert!(validate(bytes, "server").is_err());
assert!(repository("../../other").is_err());
assert!(validate(&vec![b' '; LIMIT as usize + 1], "manager").is_err());
}
#[test]
fn rejects_malformed_records_before_the_ui_can_use_them() {
let mut value = serde_json::json!({"schema": 1, "component": "server",
"repository": "Corfirean/coa-server-build", "releases": [{
"version": "0.261028.83", "tag": "0.261028.83", "date": "2026-10-28",
"notes": ["Reviewed note"]
}]});
assert!(validate(&serde_json::to_vec(&value).unwrap(), "server").is_ok());
value["releases"][0]["date"] = Value::Null;
assert!(validate(&serde_json::to_vec(&value).unwrap(), "server").is_err());
value["releases"][0]["date"] = "2026-10-28".into();
value["releases"][0]["notes"] = serde_json::json!([{"html": "not a text note"}]);
assert!(validate(&serde_json::to_vec(&value).unwrap(), "server").is_err());
}
#[test]
fn available_update_bypasses_fresh_cache_missing_the_target_and_keeps_offline_fallback() {
let dir = tempfile::tempdir().unwrap();
let feed = |version: &str| {
serde_json::to_vec(&serde_json::json!({
"schema":1,"component":"manager","repository":"Corfirean/coa-server-manager",
"releases":[{"version":version,"tag":format!("v{version}"),"date":"2026-10-30",
"notes":["Visible update notes"]}]
}))
.unwrap()
};
std::fs::write(dir.path().join("manager.json"), feed("0.9.4")).unwrap();
let value =
load_with_remote("manager", dir.path(), Some("0.9.5"), || Ok(feed("0.9.5"))).unwrap();
assert_eq!(value["source"], "remote");
assert_eq!(value["releases"][0]["version"], "0.9.5");
let cached = load_with_remote("manager", dir.path(), Some("0.9.5"), || {
panic!("fresh target is cached")
})
.unwrap();
assert_eq!(cached["source"], "cache");
let offline = load_with_remote("manager", dir.path(), Some("0.9.6"), || {
Err("offline".into())
})
.unwrap();
assert_eq!(offline["releases"][0]["version"], "0.9.5");
}
#[test]
fn fresh_valid_cache_is_available_without_network() {
let dir = std::env::temp_dir().join(format!("coa-history-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("manager.json"), br#"{"schema":1,"component":"manager","repository":"Corfirean/coa-server-manager","releases":[]}"#).unwrap();
let result = load("manager", &dir).unwrap();
assert_eq!(result["source"], "cache");
std::fs::remove_file(dir.join("manager.json")).unwrap();
std::fs::remove_dir(dir).unwrap();
}
}
+152 -4
View File
@@ -96,7 +96,7 @@ pub fn qualify_upgrade(
pkgsource::fetch_manifest(&pkgsource::Source::Dir(base.into()), trusted_key)?;
let (source_manifest, source_bytes) =
pkgsource::fetch_manifest(&pkgsource::Source::Dir(source.into()), trusted_key)?;
let (candidate_manifest, _) =
let (candidate_manifest, candidate_bytes) =
pkgsource::fetch_manifest(&pkgsource::Source::Dir(candidate.into()), trusted_key)?;
if candidate_manifest.kind != Kind::Update
|| !matches!(source_manifest.kind, Kind::Base | Kind::Update)
@@ -149,6 +149,7 @@ pub fn qualify_upgrade(
}
env.ensure_stopped()
};
let mut migration_audit = None;
install::with_scratch_ports(fixture, || {
if source_manifest.kind == Kind::Update {
apply(source)?;
@@ -157,6 +158,7 @@ pub fn qualify_upgrade(
let user_bytes = b"Qualification.UserSetting = 7391\r\n";
fsx::atomic_write(&user_file, user_bytes)?;
apply(candidate)?;
migration_audit = Some(audit_migrations(fixture, &candidate_manifest.migrations)?);
if std::fs::read(&user_file)?.as_slice() != user_bytes {
return Err(Error::Invalid(
"The update changed a user configuration file.".into(),
@@ -175,9 +177,10 @@ pub fn qualify_upgrade(
})?;
Ok(serde_json::json!({
"schema": 1, "result": "passed", "fromVersion": source_manifest.version,
"toVersion": candidate_manifest.version, "fromManifestSha256": fsx::sha256_bytes(&source_bytes),
"toVersion": candidate_manifest.version, "toManifestSha256": fsx::sha256_bytes(&candidate_bytes),
"migrationInventorySha256": migrations::inventory_sha256(&candidate_manifest.migrations)?, "migrations": migration_audit, "fromManifestSha256": fsx::sha256_bytes(&source_bytes),
"fromSchemaSha256": source_manifest.files.iter().find(|file| file.path == schema_check::CONTRACT).map(|file| &file.sha256),
"checks": ["manager-transaction", "recovery-backed-database-update", "database-schema", "private-auth-world-startup", "existing-identities", "user-file-preservation"],
"checks": ["legacy-race-start-data", "migration-ledger", "manager-transaction", "recovery-backed-database-update", "database-schema", "private-auth-world-startup", "existing-identities", "user-file-preservation"],
}))
}
@@ -238,6 +241,15 @@ pub fn qualify_install(
package: &Path,
fixture: &Path,
trusted_key: &str,
) -> Result<serde_json::Value> {
qualify_install_against(package, None, fixture, trusted_key)
}
pub fn qualify_install_against(
package: &Path,
update: Option<&Path>,
fixture: &Path,
trusted_key: &str,
) -> Result<serde_json::Value> {
use crate::update::Env;
if !cfg!(windows)
@@ -254,6 +266,21 @@ pub fn qualify_install(
let package = fsx::canonicalize_lenient(package)?;
let (manifest, bytes) =
pkgsource::fetch_manifest(&pkgsource::Source::Dir(package.clone()), trusted_key)?;
let expected_update = update
.map(|path| pkgsource::fetch_manifest(&pkgsource::Source::Dir(path.into()), trusted_key))
.transpose()?;
if let Some((expected, _)) = &expected_update {
if expected.kind != Kind::Update
|| expected.version != manifest.version
|| expected.core.commit != manifest.core.commit
|| expected.bots.as_ref().and_then(|b| b.commit.as_ref())
!= manifest.bots.as_ref().and_then(|b| b.commit.as_ref())
{
return Err(Error::Invalid(
"Clean installation image does not match the selected release.".into(),
));
}
}
let registry_dir = tempfile::tempdir()?;
let registry = crate::registry::Registry::at(registry_dir.path().join("registry.json"));
let installed = install::install_base(
@@ -280,13 +307,84 @@ pub fn qualify_install(
"Clean installation did not finish at the packaged release.".into(),
));
}
let migration_audit = expected_update
.as_ref()
.map(|(expected, _)| audit_migrations(&fixture, &expected.migrations))
.transpose()?;
env.ensure_stopped()?;
crate::mysql_snapshot::stop(&fixture)?;
let inventory = expected_update
.as_ref()
.map(|(expected, _)| migrations::inventory_sha256(&expected.migrations))
.transpose()?;
let mut checks = vec![
"clean-install",
"signed-full-package",
"credential-rotation",
"schema-contract",
"private-auth-world-startup",
];
if expected_update.is_some() {
checks.push("migration-ledger");
checks.push("legacy-race-start-data");
}
Ok(
serde_json::json!({ "schema": 1, "result": "passed", "version": installed.version,
"manifestSha256": fsx::sha256_bytes(&bytes),
"checks": ["clean-install", "signed-full-package", "credential-rotation", "schema-contract", "private-auth-world-startup"] }),
"checks": checks, "migrationInventorySha256": inventory, "migrations": migration_audit }),
)
}
fn audit_migrations(
root: &Path,
list: &[Migration],
) -> Result<std::collections::BTreeMap<String, migrations::Audit>> {
install::with_scratch_ports(root, || {
backup::with_database(root, |db| {
crate::realms::state(root)?
.modes()
.into_iter()
.map(|mode| {
if mode == crate::realms::Mode::Coa {
let rows = db
.clone()
.for_realm(mode)
.query("SELECT race,class FROM acore_world.playercreateinfo;")?;
let missing = missing_legacy_starts(&rows);
if !missing.is_empty() {
return Err(Error::Invalid(format!(
"Release is missing legacy race starting data: {}",
missing.join(", ")
)));
}
}
Ok((
mode.name().to_string(),
migrations::audit_applied(&db.clone().for_realm(mode), list)?,
))
})
.collect()
})
})
}
fn missing_legacy_starts(rows: &str) -> Vec<String> {
let pairs: std::collections::BTreeSet<(u32, u32)> = rows
.lines()
.filter_map(|line| line.split_once('\t'))
.filter_map(|(race, class)| Some((race.parse().ok()?, class.parse().ok()?)))
.collect();
let mut missing = Vec::new();
for (race, parent) in [(33, 1), (45, 8)] {
for &(source, class) in &pairs {
if source == parent && !pairs.contains(&(race, class)) {
missing.push(format!("race {race} / class {class}"));
}
}
}
missing
}
pub fn collect(core: &Path, bots: Option<&Path>, repairs: Option<&Path>) -> Result<Vec<SqlFile>> {
let mut files = release::collect_core_sql(core)?;
if let Some(bots) = bots {
@@ -617,6 +715,56 @@ mod tests {
use base64::{engine::general_purpose::STANDARD, Engine};
use ed25519_dalek::{Signer, SigningKey};
#[test]
#[ignore = "Requires the disposable current-release installation audit fixture"]
fn real_current_image_is_blocked_until_legacy_start_data_is_restored() {
let root = std::path::PathBuf::from(std::env::var_os("COA_RELEASE_AUDIT_FIXTURE").unwrap());
assert_eq!(
root.file_name().unwrap(),
"coa-schema-fixture-latest-install-audit-20261030"
);
assert!(root.join(".release-schema-fixture").is_file());
assert!(!root.join("legacy-release-gate-probe-started").exists());
fsx::atomic_write(
&root.join("legacy-release-gate-probe-started"),
b"disposable regression test",
)
.unwrap();
let candidate =
std::path::PathBuf::from(std::env::var_os("COA_RELEASE_AUDIT_PACKAGE").unwrap());
let (manifest, _) = pkgsource::fetch_manifest(
&pkgsource::Source::Dir(candidate),
crate::signing::EMBEDDED_PUBLIC_KEY,
)
.unwrap();
let failure = audit_migrations(&root, &manifest.migrations).unwrap_err();
assert!(failure.to_string().contains("race 33 / class 12"));
assert!(failure.to_string().contains("race 45 / class 30"));
println!("PASS: signed current image is blocked for missing legacy starts despite a complete migration ledger");
let sql =
fs::read_to_string(std::env::var_os("COA_RELEASE_AUDIT_CORRECTION").unwrap()).unwrap();
install::with_scratch_ports(&root, || backup::with_database(&root, |db| {
let before = db.query("SELECT * FROM acore_characters.characters ORDER BY guid;")?;
db.query(&format!("USE acore_world;\n{sql}"))?;
let once = db.query("SELECT * FROM acore_world.playercreateinfo WHERE race IN (33,45) ORDER BY race,class;")?;
db.query(&format!("USE acore_world;\n{sql}"))?;
assert_eq!(once, db.query("SELECT * FROM acore_world.playercreateinfo WHERE race IN (33,45) ORDER BY race,class;")?);
assert_eq!(before, db.query("SELECT * FROM acore_characters.characters ORDER BY guid;")?);
Ok(())
})).unwrap();
let audits = audit_migrations(&root, &manifest.migrations).unwrap();
println!("PASS: corrected data passes the release gate; characters unchanged; correction idempotent; audit={}", serde_json::to_string(&audits).unwrap());
}
#[test]
fn release_rejects_missing_legacy_starts_even_without_existing_characters() {
assert_eq!(
missing_legacy_starts("1\t12\n8\t30\n"),
["race 33 / class 12", "race 45 / class 30"]
);
assert!(missing_legacy_starts("1\t12\n8\t30\n33\t12\n45\t30\n").is_empty());
}
#[test]
#[ignore = "Requires a composed disposable installation image"]
fn real_full_package_installs_the_current_version_without_an_update_transaction() {
+57 -7
View File
@@ -95,13 +95,42 @@ pub struct Problem {
/// Keep all differences for support; never change a database to match a contract automatically.
pub fn check_with_report(db: &Db, root: &Path) -> Result<Vec<Problem>> {
let problems = check(db, root)?;
if problems.is_empty() {
check_update_with_report(db, root, None)
}
/// Only a hash-verified pre-update baseline may downgrade unchanged missing starts to warnings.
pub fn check_update_with_report(
db: &Db,
root: &Path,
baseline: Option<&crate::character_start_check::Baseline>,
) -> Result<Vec<Problem>> {
let mut preexisting = BTreeMap::new();
let before = match baseline {
Some(b) if b.schema == 1 => Some(b.realms.get(db.realm().name()).ok_or_else(|| {
crate::Error::Invalid("The character baseline does not contain this realm.".into())
})?),
Some(_) => {
return Err(crate::Error::Invalid(
"Unsupported character start baseline.".into(),
))
}
None => None,
};
let problems = check_inner(db, root, before, &mut preexisting)?;
let existing: usize = preexisting.values().sum();
let preexisting_details: Vec<_> = preexisting.into_iter().map(|((race, class), count)| serde_json::json!({"race": race, "class": class, "count": count})).collect();
if existing > 0 {
tracing::warn!(realm = db.realm().name(), characters = existing, "Unchanged pre-update characters with missing starting data retained; no character records were repaired or deleted");
}
if problems.is_empty() && existing == 0 {
return Ok(problems);
}
let report = serde_json::json!({
"schema": 1, "checkedAt": chrono::Utc::now().to_rfc3339(),
"realm": db.realm().name(), "problems": problems,
"preexistingUnsupportedCharacters": existing,
"preexistingCharacterStarts": preexisting_details,
"note": "Unchanged pre-update missing starts are reported separately. New missing character starts and all schema errors still block the update.",
});
let path = crate::registry::metadata_dir_for(root)?
.join("diagnostics")
@@ -245,6 +274,15 @@ pub(crate) fn repair_missing_defaults(
}
pub fn check(db: &Db, root: &Path) -> Result<Vec<Problem>> {
check_inner(db, root, None, &mut BTreeMap::new())
}
fn check_inner(
db: &Db,
root: &Path,
before: Option<&BTreeSet<crate::character_start_check::MissingStart>>,
existing: &mut BTreeMap<(u32, u32), usize>,
) -> Result<Vec<Problem>> {
let contract = if root.join(CONTRACT).is_file() {
let contract: Contract = fsx::read_json(&root.join(CONTRACT))?;
if contract.schema != 1 {
@@ -367,12 +405,24 @@ pub fn check(db: &Db, root: &Path) -> Result<Vec<Problem>> {
}
// Check owned characters too, including legacy classes and Wildcard characters. Their rows
// must not silently disappear from character selection after an otherwise healthy update.
let missing = db.query("SELECT c.race,c.class,COUNT(*) FROM acore_characters.characters c LEFT JOIN acore_world.playercreateinfo p ON p.race=c.race AND p.class=c.class WHERE p.race IS NULL GROUP BY c.race,c.class;")?;
for row in missing.lines() {
let fields: Vec<_> = row.split('\t').collect();
if fields.len() == 3 {
problems.push(Problem { database: "world".into(), table: "playercreateinfo".into(), column: String::new(), detail: format!("{} existing characters have no starting data for race {} / class {} and would be hidden from character selection", fields[2], fields[0], fields[1]) });
let current = crate::character_start_check::missing(db)?;
let blocking = if let Some(before) = before {
let introduced = crate::character_start_check::introduced(&current, before);
for character in current.intersection(before) {
*existing
.entry((character.race, character.class))
.or_default() += 1;
}
introduced
} else {
current
};
let mut counts = BTreeMap::<(u32, u32), usize>::new();
for character in blocking {
*counts.entry((character.race, character.class)).or_default() += 1;
}
for ((race, class), count) in counts {
problems.push(Problem { database: "world".into(), table: "playercreateinfo".into(), column: String::new(), detail: format!("{count} existing characters have no starting data for race {race} / class {class} and would be hidden from character selection") });
}
Ok(problems)
}
+165
View File
@@ -0,0 +1,165 @@
use std::{fs, path::Path};
use crate::{
config::{parser::ConfFile, Scope},
error::{Error, Result},
fsx,
};
fn transform(bytes: &[u8], preset: &str) -> Result<String> {
let level = match preset {
"normal" => 4,
"errors" => 2,
"off" => 0,
_ => return Err(Error::Invalid("Unknown server logging preset.".into())),
};
let mut conf = ConfFile::parse_bytes(bytes)?;
let entries: Vec<_> = conf
.entries()
.map(|(key, value)| (key.to_string(), value.to_string()))
.collect();
for (key, value) in entries {
if key.starts_with("Logger.") {
let Some((_, appenders)) = value.split_once(',') else {
continue;
};
let value = if preset == "normal"
&& matches!(
key.as_str(),
"Logger.network" | "Logger.sql.sql" | "Logger.entities.player"
) {
2
} else {
level
};
conf.set(&key, &format!("{value},{appenders}"), &[]);
} else if key.starts_with("Appender.") {
let mut fields: Vec<_> = value.split(',').map(str::to_string).collect();
if fields.len() >= 3 {
fields[1] = if key == "Appender.Errors" && preset == "normal" {
"2".into()
} else {
level.to_string()
};
conf.set(&key, &fields.join(","), &[]);
}
}
}
Ok(conf.to_text())
}
pub fn apply(root: &Path, meta: &Path, preset: &str) -> Result<()> {
let _operation = crate::update::operation_lock(meta)?;
crate::update::ensure_recovered(meta)?;
fs::create_dir_all(root.join(".state"))?;
let lock = fs::OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(false)
.open(root.join(".state/control.lock"))?;
if !fs4::fs_std::FileExt::try_lock_exclusive(&lock)? {
return Err(Error::Invalid(
"Another start/stop action is in progress.".into(),
));
}
let mut originals = Vec::new();
let mut texts = Vec::new();
for prefix in ["", ".realms/secondary/", ".realms/reborn/"] {
for name in [
"Settings/worldserver.conf.template",
"Settings/authserver.conf.template",
"Core/configs/worldserver.conf",
"Core/configs/authserver.conf",
] {
let path = fsx::ensure_within(root, &root.join(format!("{prefix}{name}")))?;
if path.is_file() {
let bytes = fs::read(&path)?;
texts.push(transform(&bytes, preset)?);
originals.push((path, bytes));
}
}
let marker = root.join(format!("{prefix}.state/debug-logs.json"));
if marker.is_file() {
originals.push((marker.clone(), fs::read(marker)?));
texts.push("{\"enabled\":false}\n".into());
}
}
if originals.is_empty() {
return Err(Error::Invalid(
"Server configuration files were not found.".into(),
));
}
crate::config::take_snapshot(
meta,
Scope::Server,
"before changing server logging",
&originals,
)?;
for (index, (path, _)) in originals.iter().enumerate() {
if let Err(error) = fsx::atomic_write(path, texts[index].as_bytes()) {
for (path, bytes) in originals.iter().take(index) {
let _ = fsx::atomic_write(path, bytes);
}
return Err(error);
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn changes_auth_world_and_templates_in_all_realms_with_restorable_snapshots() {
let temp = tempfile::tempdir().unwrap();
let root = temp.path().join("server");
let meta = temp.path().join("meta");
fs::create_dir_all(&root).unwrap();
let mut files = Vec::new();
for prefix in ["", ".realms/secondary/", ".realms/reborn/"] {
for name in [
"Settings/worldserver.conf.template",
"Settings/authserver.conf.template",
"Core/configs/worldserver.conf",
"Core/configs/authserver.conf",
] {
let path = root.join(format!("{prefix}{name}"));
fs::create_dir_all(path.parent().unwrap()).unwrap();
let bytes =
b"Logger.root=6,Console\r\nAppender.Console=1,6,0\r\nKeep = unchanged\r\n"
.to_vec();
fs::write(&path, &bytes).unwrap();
files.push((path, bytes));
}
}
apply(&root, &meta, "errors").unwrap();
for (path, _) in &files {
assert!(fs::read_to_string(path)
.unwrap()
.contains("Logger.root=2,Console\r\n"));
}
let snapshots = crate::config::list_snapshots(&meta);
assert_eq!(snapshots.len(), 1);
crate::config::restore_snapshot(&meta, &snapshots[0].id).unwrap();
for (path, bytes) in files {
assert_eq!(fs::read(path).unwrap(), bytes);
}
}
#[test]
fn presets_control_dispatch_and_appenders_and_can_restore_useful_logs() {
let original = b"Logger.root=6,Console Server\r\nLogger.sql.sql=6,Console Server\r\nAppender.Console=1,6,0,\"1 9 3 6 5 8\"\r\nAppender.Errors=2,2,0,Errors.log,w\r\nOther = keep\r\n";
let off = transform(original, "off").unwrap();
assert!(off.contains("Logger.root=0,Console Server\r\n"));
assert!(off.contains("Appender.Errors=2,0,0,Errors.log,w\r\n"));
let normal = transform(off.as_bytes(), "normal").unwrap();
assert!(normal.contains("Logger.root=4,Console Server\r\n"));
assert!(normal.contains("Logger.sql.sql=2,Console Server\r\n"));
assert!(normal.contains("Appender.Errors=2,2,0,Errors.log,w\r\n"));
assert!(normal.contains("Other = keep\r\n"));
assert_eq!(transform(normal.as_bytes(), "normal").unwrap(), normal);
assert!(transform(original, "unsupported").is_err());
}
}
+260 -25
View File
@@ -22,6 +22,8 @@ use crate::pkgsource::{fetch_manifest, fetch_parts, Source};
use crate::registry::{InstallMeta, MetaDir};
const STAGED_PREFIX: &str = "_migrations/";
const CHARACTER_BASELINE: &str = "character-start-baseline.json";
const CHARACTER_BASELINE_HASH: &str = "@character-starts";
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
@@ -106,6 +108,9 @@ pub trait Env {
fn verify_snapshot(&self, _id: &str) -> Result<()> {
Ok(())
}
fn character_start_baseline(&self) -> Result<Option<crate::character_start_check::Baseline>> {
Ok(None)
}
fn snapshot(&self) -> Result<String>;
fn restore_snapshot(&self, id: &str) -> Result<()>;
fn migrate(&self, manifest: &Manifest, staged_migrations: &Path) -> Result<ApplyReport>;
@@ -223,11 +228,12 @@ fn read_journal(path: &Path) -> Result<Txn> {
"Update journal contains invalid recovery hashes.".into(),
));
}
for key in txn
.recovery_hashes
.keys()
.filter(|key| !matches!(key.as_str(), "@install" | "@point"))
{
for key in txn.recovery_hashes.keys().filter(|key| {
!matches!(
key.as_str(),
"@install" | "@point" | CHARACTER_BASELINE_HASH
)
}) {
fsx::safe_join(path.parent().unwrap(), key)?;
}
if completed_legacy_repair {
@@ -397,7 +403,7 @@ pub fn plan(
match (fs::read_to_string(tree.join(&f.path)), fs::read(&target)) {
(Ok(signed), Ok(actual)) => {
fsx::sha256_bytes(signed.as_bytes()) == f.sha256
&& crate::driver::launcher_matches(&signed, &actual)
&& crate::legacy_launcher::launcher_matches(&signed, &actual)
}
_ => false,
}
@@ -412,7 +418,7 @@ pub fn plan(
let manager_launcher = f.path == "Scripts/manage.py"
&& recorded.is_some_and(|hash| {
fs::read(&target).is_ok_and(|bytes| {
crate::driver::launcher_matches_recorded(hash, &bytes)
crate::legacy_launcher::launcher_matches_recorded(hash, &bytes)
})
});
if f.path == "Core/worldserver.exe"
@@ -608,7 +614,7 @@ fn launcher_already_integrated(
if meta.original_hashes.get(&file.path) != Some(&fsx::sha256_bytes(&actual)) {
return Ok(false);
}
Ok(crate::driver::launcher_matches_recorded(
Ok(crate::legacy_launcher::launcher_matches_recorded(
&file.sha256,
&actual,
))
@@ -684,6 +690,7 @@ pub struct Params<'a> {
#[derive(Debug, Serialize)]
pub struct Outcome {
pub txn: Txn,
pub preexisting_character_count: usize,
pub migrations: Option<ApplyReport>,
}
@@ -816,6 +823,26 @@ pub fn apply(p: &Params, report: &dyn Fn(&str, u8)) -> Result<Outcome> {
.insert("@point".into(), fsx::sha256_file(&point_meta)?);
}
save(meta_dir, &txn)?;
// Capture before any new files or SQL are applied; retry must reuse these exact bytes.
let baseline = match p.env.character_start_baseline() {
Ok(baseline) => baseline,
Err(error) => {
txn.state = State::Failed;
txn.message = Some(format!("The update was not applied because the character baseline could not be captured: {error}"));
save(meta_dir, &txn)?;
return Err(error);
}
};
let preexisting_character_count = baseline
.as_ref()
.map_or(0, |b| b.realms.values().map(|r| r.len()).sum());
if let Some(baseline) = &baseline {
let path = tdir.join(CHARACTER_BASELINE);
fsx::atomic_write_json(&path, baseline)?;
txn.recovery_hashes
.insert(CHARACTER_BASELINE_HASH.into(), fsx::sha256_file(&path)?);
save(meta_dir, &txn)?;
}
txn.ops = items
.iter()
.filter(|i| i.action != Action::Skip)
@@ -909,6 +936,7 @@ pub fn apply(p: &Params, report: &dyn Fn(&str, u8)) -> Result<Outcome> {
save(meta_dir, &txn)?;
return Ok(Outcome {
txn,
preexisting_character_count,
migrations: migrated,
});
}
@@ -919,6 +947,7 @@ pub fn apply(p: &Params, report: &dyn Fn(&str, u8)) -> Result<Outcome> {
let _ = archive;
Ok(Outcome {
txn,
preexisting_character_count,
migrations: migrated,
})
}
@@ -939,7 +968,7 @@ fn finish(
fs::read_to_string(tree.join(&op.path)),
fs::read(root.join(&op.path)),
) {
(Ok(signed), Ok(actual)) if crate::driver::launcher_matches(&signed, &actual) => {
(Ok(signed), Ok(actual)) if crate::legacy_launcher::launcher_matches(&signed, &actual) => {
fsx::sha256_bytes(&actual)
}
_ => op.new_sha256.clone(),
@@ -1031,7 +1060,7 @@ pub fn retry_validation(
&& fs::read_to_string(dir.join("tree").join(&op.path))
.ok()
.filter(|s| fsx::sha256_bytes(s.as_bytes()) == file.sha256)
.is_some_and(|s| crate::driver::launcher_matches(&s, &bytes));
.is_some_and(|s| crate::legacy_launcher::launcher_matches(&s, &bytes));
if actual != file.sha256 && !launcher {
return Err(Error::Invalid(format!(
"{} changed since the update was applied; use repair or rollback.",
@@ -1039,6 +1068,7 @@ pub fn retry_validation(
)));
}
}
read_character_baseline(meta_dir, &txn)?;
env.ensure_stopped()?;
if let Err(error) = env.validate() {
txn.message = Some(format!(
@@ -1115,7 +1145,13 @@ fn restore_transaction(
txn: &mut Txn,
env: &dyn Env,
) -> Result<()> {
for (rel, expected) in &txn.recovery_hashes {
// This baseline is a validation input, not a recovery copy: corruption must block
// retry/commit, but must never prevent restoration of the verified safety backup.
for (rel, expected) in txn
.recovery_hashes
.iter()
.filter(|(key, _)| key.as_str() != CHARACTER_BASELINE_HASH)
{
let saved = match rel.as_str() {
"@install" => before.join("manager-install.json"),
"@point" => crate::backup::point_json(
@@ -1504,6 +1540,33 @@ fn prune(meta_dir: &Path, keep: usize) {
}
}
fn read_character_baseline(
meta: &Path,
txn: &Txn,
) -> Result<Option<crate::character_start_check::Baseline>> {
let path = txn_dir(meta, &txn.id)?.join(CHARACTER_BASELINE);
let Some(expected) = txn.recovery_hashes.get(CHARACTER_BASELINE_HASH) else {
if path.exists() {
return Err(Error::Invalid(
"An unverified character start baseline was found.".into(),
));
}
return Ok(None); // Older transactions remain strict; never learn a baseline after applying SQL.
};
if fsx::sha256_file(&path)? != *expected {
return Err(Error::Invalid(
"The saved character start baseline failed verification.".into(),
));
}
let baseline: crate::character_start_check::Baseline = fsx::read_json(&path)?;
if baseline.schema != 1 {
return Err(Error::Invalid(
"Unsupported character start baseline.".into(),
));
}
Ok(Some(baseline))
}
/// The real environment: a repack-shaped installation driven through its launcher.
pub struct RepackEnv<'a> {
pub root: &'a Path,
@@ -1511,6 +1574,12 @@ pub struct RepackEnv<'a> {
}
impl RepackEnv<'_> {
fn saved_character_baseline(&self) -> Result<Option<crate::character_start_check::Baseline>> {
match unfinished(self.meta_dir) {
Some(txn) => read_character_baseline(self.meta_dir, &txn),
None => Ok(None),
}
}
pub fn pending_migrations(&self, manifest: &Manifest) -> Result<usize> {
Ok(self
.pending_migrations_with(manifest, DatabaseAccess::Start)?
@@ -1527,9 +1596,9 @@ impl RepackEnv<'_> {
return Ok(Some(0));
}
let count = |db: &crate::db::Db| -> Result<usize> {
let db = db.clone().with_read_deadline(
std::time::Instant::now() + std::time::Duration::from_secs(15),
);
let db = db
.clone()
.with_read_deadline(std::time::Instant::now() + std::time::Duration::from_secs(15));
let realms = crate::realms::state(self.root)?;
let modes = realms.modes();
let mut count = 0;
@@ -1772,12 +1841,25 @@ impl Env for RepackEnv<'_> {
Ok(())
}
fn character_start_baseline(&self) -> Result<Option<crate::character_start_check::Baseline>> {
crate::backup::with_database(self.root, |db| {
crate::character_start_check::capture(db, self.root)
})
.map(Some)
}
fn migrate(&self, manifest: &Manifest, staged: &Path) -> Result<ApplyReport> {
crate::backup::with_database(self.root, |db| {
let identities = database_identities(db)?;
let result = migrate_databases(db, self.root, manifest, staged, &|| {
self.migration_snapshot()
})?;
let baseline = self.saved_character_baseline()?;
let result = migrate_databases(
db,
self.root,
manifest,
staged,
&|| self.migration_snapshot(),
baseline.as_ref(),
)?;
if result.failed.is_none() {
verify_database_identities(db, &identities)?;
}
@@ -1799,16 +1881,26 @@ impl RepackEnv<'_> {
crate::mysql_snapshot::stop(self.root)?;
self.ensure_stopped()?;
self.recover_validation()?;
let baseline = if check_schema {
self.saved_character_baseline()?
} else {
None
};
let result = (|| -> Result<()> {
crate::update_isolation::begin(self.root, self.meta_dir)?;
let database = crate::driver::run(self.root, crate::driver::Verb::StartMysql)?;
if !database.ok {
return Err(Error::Invalid(crate::driver::startup_failure(self.root, &database)));
}
use crate::process::{observe, ServiceState};
let identities = crate::backup::with_database(self.root, |db| {
if check_schema {
let modes = crate::realms::state(self.root)?.modes();
for mode in modes {
if let Some(p) = crate::schema_check::check_with_report(
if let Some(p) = crate::schema_check::check_update_with_report(
&db.clone().for_realm(mode),
self.root,
baseline.as_ref(),
)?
.first()
{
@@ -1851,8 +1943,7 @@ impl RepackEnv<'_> {
if o.mysql.state == ServiceState::Running
&& o.auth.state == ServiceState::Running
&& o.world.state == ServiceState::Running
&& o.extra_worlds()
.all(|s| s.state == ServiceState::Running)
&& o.extra_worlds().all(|s| s.state == ServiceState::Running)
{
let since = ready_since.get_or_insert_with(std::time::Instant::now);
if since.elapsed() >= std::time::Duration::from_secs(10) {
@@ -1869,7 +1960,26 @@ impl RepackEnv<'_> {
};
if healthy {
crate::backup::with_database(self.root, |db| {
verify_database_identities(db, &identities)
verify_database_identities(db, &identities)?;
if check_schema {
for mode in crate::realms::state(self.root)?.modes() {
if let Some(problem) = crate::schema_check::check_update_with_report(
&db.clone().for_realm(mode),
self.root,
baseline.as_ref(),
)?
.first()
{
return Err(Error::Invalid(format!(
"Database validation failed after startup on {}: {}: {}",
mode.name(),
problem.table,
problem.detail
)));
}
}
}
Ok(())
})?;
return Ok(());
}
@@ -1892,6 +2002,7 @@ fn migrate_databases(
manifest: &Manifest,
staged: &Path,
snapshot: &dyn Fn() -> Result<String>,
baseline: Option<&crate::character_start_check::Baseline>,
) -> Result<ApplyReport> {
let realms = crate::realms::state(root)?;
let modes = realms.modes();
@@ -1943,7 +2054,8 @@ fn migrate_databases(
return Ok(result);
}
crate::schema_check::repair_missing_defaults(&db, root, contract)?;
if let Some(p) = crate::schema_check::check_with_report(&db, root)?.first() {
if let Some(p) = crate::schema_check::check_update_with_report(&db, root, baseline)?.first()
{
return Err(Error::Invalid(format!(
"Database validation failed on {}: {}.{}: {}",
mode.name(),
@@ -2010,6 +2122,8 @@ mod tests {
use std::cell::{Cell, RefCell};
struct Fake {
character_baseline: RefCell<Option<crate::character_start_check::Baseline>>,
baseline_failed: Cell<bool>,
activation_expected: RefCell<Option<(PathBuf, String)>>,
activation_failed: Cell<bool>,
activated: Cell<bool>,
@@ -2027,6 +2141,8 @@ mod tests {
impl Fake {
fn ok() -> Fake {
Fake {
character_baseline: RefCell::new(None),
baseline_failed: Cell::new(false),
activation_expected: RefCell::new(None),
activation_failed: Cell::new(false),
activated: Cell::new(false),
@@ -2044,6 +2160,14 @@ mod tests {
}
impl Env for Fake {
fn character_start_baseline(
&self,
) -> Result<Option<crate::character_start_check::Baseline>> {
if self.baseline_failed.get() {
return Err(Error::Invalid("fixture baseline unavailable".into()));
}
Ok(self.character_baseline.borrow().clone())
}
fn activate(&self) -> Result<()> {
if let Some((meta, version)) = self.activation_expected.borrow().as_ref() {
ensure_recovered(meta)?;
@@ -2223,9 +2347,9 @@ mod tests {
fn legacy_launcher_world(import_patch: bool) -> World {
let w = world(&[("Scripts/manage.py", b"new release launcher")], false);
let mut source = crate::realms::patch_launcher(LEGACY_LAUNCHER).unwrap();
let mut source = crate::legacy_launcher::patch_launcher(LEGACY_LAUNCHER).unwrap();
if import_patch {
source = crate::driver::patch_launcher_imports(&source).unwrap();
source = crate::legacy_launcher::patch_launcher_imports(&source).unwrap();
}
write(&w.root, "Scripts/manage.py", source.as_bytes());
let (_, mut meta) = MetaDir::open(&w.meta).unwrap();
@@ -2452,7 +2576,7 @@ mod tests {
let w = world(&[("Scripts/manage.py", source)], false);
run(&w, &Fake::ok(), BTreeMap::new(), None).unwrap();
let integrated =
crate::driver::patch_launcher_imports(std::str::from_utf8(source).unwrap()).unwrap();
crate::legacy_launcher::patch_launcher_imports(std::str::from_utf8(source).unwrap()).unwrap();
write(&w.root, "Scripts/manage.py", integrated.as_bytes());
let (_, mut meta) = MetaDir::open(&w.meta).unwrap();
meta.original_hashes.insert(
@@ -3485,4 +3609,115 @@ mod tests {
.iter()
.any(|i| i.path == "Core/newfile.dll" && i.action == Action::Create));
}
fn baseline_fixture() -> crate::character_start_check::Baseline {
crate::character_start_check::Baseline {
schema: 1,
realms: BTreeMap::from([(
"coa".into(),
crate::character_start_check::parse_missing("1\t44\t14\n2\t44\t14\n3\t44\t14")
.unwrap(),
)]),
}
}
#[test]
fn character_baseline_is_captured_once_persisted_and_verified_for_retry() {
let w = world(&[], true);
let env = Fake::ok();
*env.character_baseline.borrow_mut() = Some(baseline_fixture());
env.healthy.set(false);
let out = run(&w, &env, BTreeMap::new(), None).unwrap();
assert_eq!(out.txn.state, State::NeedsDecision);
assert_eq!(out.preexisting_character_count, 3);
let baseline_path = txn_dir(&w.meta, &out.txn.id)
.unwrap()
.join(CHARACTER_BASELINE);
let original = fs::read(&baseline_path).unwrap();
assert_eq!(
read_character_baseline(&w.meta, &out.txn)
.unwrap()
.unwrap()
.realms["coa"]
.len(),
3
);
// A retry may not learn new gaps from an already modified database.
*env.character_baseline.borrow_mut() = None;
env.healthy.set(true);
fs::write(&baseline_path, b"{}").unwrap();
assert!(retry_validation(
&w.root,
&w.meta,
&out.txn.id,
&Source::Dir(w.pkg.clone()),
&w.key,
&env
)
.is_err());
fs::write(&baseline_path, original).unwrap();
let done = retry_validation(
&w.root,
&w.meta,
&out.txn.id,
&Source::Dir(w.pkg.clone()),
&w.key,
&env,
)
.unwrap();
assert_eq!(done.state, State::Committed);
}
#[test]
fn corrupt_character_baseline_does_not_prevent_safe_rollback() {
let w = world(&[], true);
let env = Fake::ok();
*env.character_baseline.borrow_mut() = Some(baseline_fixture());
env.healthy.set(false);
let out = run(&w, &env, BTreeMap::new(), None).unwrap();
fs::write(
txn_dir(&w.meta, &out.txn.id)
.unwrap()
.join(CHARACTER_BASELINE),
b"bad",
)
.unwrap();
let restored = rollback(&w.root, &w.meta, &out.txn.id, &env).unwrap();
assert_eq!(restored.state, State::RolledBack);
assert_eq!(read(&w, "Core/worldserver.exe"), b"world-v1");
}
#[test]
fn missing_or_unverified_character_baselines_fail_closed() {
let w = world(&[], true);
let env = Fake::ok();
env.healthy.set(false);
let out = run(&w, &env, BTreeMap::new(), None).unwrap();
assert!(read_character_baseline(&w.meta, &out.txn)
.unwrap()
.is_none());
let path = txn_dir(&w.meta, &out.txn.id)
.unwrap()
.join(CHARACTER_BASELINE);
fsx::atomic_write_json(&path, &baseline_fixture()).unwrap();
assert!(read_character_baseline(&w.meta, &out.txn).is_err());
let mut txn = out.txn;
txn.recovery_hashes.insert(
CHARACTER_BASELINE_HASH.into(),
fsx::sha256_file(&path).unwrap(),
);
fs::remove_file(path).unwrap();
assert!(read_character_baseline(&w.meta, &txn).is_err());
}
#[test]
fn baseline_capture_failure_precedes_file_and_database_changes() {
let w = world(&[], true);
let env = Fake::ok();
env.baseline_failed.set(true);
assert!(run(&w, &env, BTreeMap::new(), None).is_err());
assert_eq!(read(&w, "Core/worldserver.exe"), b"world-v1");
assert!(!env.calls.borrow().contains(&"migrate"));
assert!(!env.calls.borrow().contains(&"validate"));
assert!(unfinished(&w.meta).is_none());
}
}
+158 -19
View File
@@ -41,6 +41,24 @@ struct Saved {
sha256: Option<String>,
}
fn bot_files() -> Vec<String> {
["", ".realms/secondary/", ".realms/reborn/"]
.into_iter()
.flat_map(|prefix| {
[
"mod_coa_playerbots.conf",
"mod_coa_playerbots.conf.dist",
"playerbots.conf",
"playerbots.conf.dist",
"mod_playerbots.conf",
"mod_playerbots.conf.dist",
]
.into_iter()
.map(move |name| format!("{prefix}Core/configs/modules/{name}"))
})
.collect()
}
pub(crate) fn pending(meta: &Path) -> bool {
meta.join("validation-configs.json").exists()
}
@@ -52,15 +70,20 @@ pub(crate) fn begin(root: &Path, meta: &Path) -> Result<()> {
));
}
let mut saved = BTreeMap::new();
for rel in FILES {
let path = fsx::ensure_within(root, &fsx::safe_join(root, rel)?)?;
let modules = bot_files();
for rel in FILES
.iter()
.map(|rel| rel.to_string())
.chain(modules.iter().cloned())
{
let path = fsx::ensure_within(root, &fsx::safe_join(root, &rel)?)?;
let bytes = if path.exists() {
Some(fs::read(path)?)
} else {
None
};
let sha256 = bytes.as_ref().map(|b| fsx::sha256_bytes(b));
saved.insert(*rel, Saved { bytes, sha256 });
saved.insert(rel, Saved { bytes, sha256 });
}
let mut settings: serde_json::Value = fsx::read_json(&root.join("Settings/repack.json"))?;
let mut realm: Option<serde_json::Value> = if root.join("Settings/realm-profile.json").exists()
@@ -101,14 +124,14 @@ pub(crate) fn begin(root: &Path, meta: &Path) -> Result<()> {
}
}
let mut configs = Vec::new();
for rel in [
"Settings/worldserver.conf.template",
"Settings/authserver.conf.template",
"Core/configs/worldserver.conf",
"Core/configs/authserver.conf",
] {
for rel in FILES.iter().copied().filter(|rel| {
rel.ends_with("worldserver.conf.template")
|| rel.ends_with("authserver.conf.template")
|| rel.ends_with("worldserver.conf")
|| rel.ends_with("authserver.conf")
}) {
let path = root.join(rel);
if !path.exists() && rel.ends_with(".template") {
if !path.exists() && rel.ends_with(".template") && !rel.starts_with(".realms/") {
return Err(Error::Invalid(format!(
"Cannot isolate validation without {rel}."
)));
@@ -118,10 +141,34 @@ pub(crate) fn begin(root: &Path, meta: &Path) -> Result<()> {
conf.set("BindIP", "\"127.0.0.1\"", &[]);
if rel.contains("worldserver") {
conf.set("Ra.IP", "\"127.0.0.1\"", &[]);
conf.set("CoA.ValidationMode", "1", &[]);
}
configs.push((path, conf.to_text()));
}
}
for rel in modules {
let path = fsx::ensure_within(root, &fsx::safe_join(root, &rel)?)?;
if !path.exists() {
continue;
}
let mut conf = ConfFile::parse_bytes(&fs::read(&path)?)?;
let keys: &[&str] = if rel.contains("mod_coa_playerbots.") {
&[
"CoaBots.AutoLoginOnStartup",
"CoaBots.RandomSpawn.AutoLogin",
]
} else {
&[
"AiPlayerbot.RandomBotAutologin",
"AiPlayerbot.BotAutologin",
"AiPlayerbot.DeleteRandomBotAccounts",
]
};
for key in keys {
conf.set(key, "0", &[]);
}
configs.push((path, conf.to_text()));
}
fsx::atomic_write_json(&meta.join("validation-configs.json"), &saved)?;
fsx::atomic_write_json(&root.join("Settings/repack.json"), &settings)?;
if let Some(state) = realm {
@@ -139,16 +186,20 @@ pub(crate) fn restore(root: &Path, meta: &Path) -> Result<()> {
}
let journal = meta.join("validation-configs.json");
let saved: BTreeMap<String, Saved> = fsx::read_json(&journal)?;
// Previous managers could journal only the first two profiles. Recover those
// journals too, while continuing to reject missing or unknown legacy entries.
let legacy = saved.len() == FILES.len() - 1
let modules = bot_files();
let complete_core = FILES.iter().all(|rel| saved.contains_key(*rel));
let legacy_core = FILES
.iter()
.filter(|rel| **rel != "Settings/realm-profiles/reborn.json")
.all(|rel| saved.contains_key(*rel));
let current = complete_core
&& saved.len() == FILES.len() + modules.len()
&& modules.iter().all(|rel| saved.contains_key(rel));
let previous = complete_core && saved.len() == FILES.len();
let legacy = legacy_core
&& saved.len() == FILES.len() - 1
&& !saved.contains_key("Settings/realm-profiles/reborn.json");
let required = if legacy {
&FILES[..FILES.len() - 1]
} else {
FILES
};
if saved.len() != required.len() || required.iter().any(|rel| !saved.contains_key(*rel)) {
if !(current || previous || legacy) {
return Err(Error::Invalid(
"Isolated validation configuration journal is incomplete.".into(),
));
@@ -263,4 +314,92 @@ mod tests {
assert!(!pending(&meta));
assert_eq!(fs::read(root.join(FILES[0])).unwrap(), before);
}
#[test]
fn bot_population_is_suppressed_in_all_realms_and_restored_exactly() {
let (_dir, root, meta) = fixture();
let companion = b"[worldserver]\r\n# owner settings\r\nCoaBots.Enable = 1\r\nCoaBots.AutoLoginOnStartup = 1\r\nCoaBots.RandomSpawn.AutoLogin = 1\r\nCoaBots.AutoLogin.MaxCount = 2000\r\n";
let squid = b"[worldserver]\nAiPlayerbot.Enabled = 1\nAiPlayerbot.RandomBotAutologin = 1\nAiPlayerbot.BotAutologin = 1\nAiPlayerbot.DeleteRandomBotAccounts = 1\n";
for rel in bot_files() {
fsx::atomic_write(
&root.join(&rel),
if rel.contains("mod_coa_playerbots.") {
companion
} else {
squid
},
)
.unwrap();
}
begin(&root, &meta).unwrap();
for rel in bot_files() {
let conf = ConfFile::parse_bytes(&fs::read(root.join(&rel)).unwrap()).unwrap();
if rel.contains("mod_coa_playerbots.") {
assert_eq!(conf.get("CoaBots.Enable"), Some("1"));
assert_eq!(conf.get("CoaBots.AutoLoginOnStartup"), Some("0"));
assert_eq!(conf.get("CoaBots.RandomSpawn.AutoLogin"), Some("0"));
assert_eq!(conf.get("CoaBots.AutoLogin.MaxCount"), Some("2000"));
} else {
assert_eq!(conf.get("AiPlayerbot.Enabled"), Some("1"));
assert_eq!(conf.get("AiPlayerbot.RandomBotAutologin"), Some("0"));
assert_eq!(conf.get("AiPlayerbot.BotAutologin"), Some("0"));
assert_eq!(conf.get("AiPlayerbot.DeleteRandomBotAccounts"), Some("0"));
}
}
restore(&root, &meta).unwrap();
for rel in bot_files() {
assert_eq!(
fs::read(root.join(&rel)).unwrap(),
if rel.contains("mod_coa_playerbots.") {
companion.as_slice()
} else {
squid.as_slice()
}
);
}
}
#[test]
fn validation_removes_only_module_configs_created_during_the_check() {
let (_dir, root, meta) = fixture();
let dist = root.join("Core/configs/modules/mod_coa_playerbots.conf.dist");
let active = root.join("Core/configs/modules/mod_coa_playerbots.conf");
let original = b"CoaBots.AutoLoginOnStartup = 1\n";
fsx::atomic_write(&dist, original).unwrap();
begin(&root, &meta).unwrap();
fs::copy(&dist, &active).unwrap();
restore(&root, &meta).unwrap();
assert!(!active.exists());
assert_eq!(fs::read(dist).unwrap(), original);
}
#[test]
fn previous_manager_journals_remain_recoverable() {
for without_reborn in [false, true] {
let (_dir, root, meta) = fixture();
begin(&root, &meta).unwrap();
let journal = meta.join("validation-configs.json");
let mut saved: BTreeMap<String, Saved> = fsx::read_json(&journal).unwrap();
saved.retain(|key, _| FILES.contains(&key.as_str()));
if without_reborn {
saved.remove("Settings/realm-profiles/reborn.json");
}
fsx::atomic_write_json(&journal, &saved).unwrap();
restore(&root, &meta).unwrap();
assert!(!pending(&meta));
}
}
#[test]
fn incomplete_bot_journal_blocks_restoration_before_writing() {
let (_dir, root, meta) = fixture();
begin(&root, &meta).unwrap();
let journal = meta.join("validation-configs.json");
let mut saved: BTreeMap<String, Saved> = fsx::read_json(&journal).unwrap();
saved.remove(&bot_files()[0]);
fsx::atomic_write_json(&journal, &saved).unwrap();
let before = fs::read(root.join(FILES[2])).unwrap();
assert!(restore(&root, &meta).is_err());
assert_eq!(fs::read(root.join(FILES[2])).unwrap(), before);
}
}
+15
View File
@@ -0,0 +1,15 @@
[package]
name = "coa-launcher"
description = "The CoA repack launcher (Start_All_Server.bat and friends) without Python"
version.workspace = true
edition.workspace = true
license.workspace = true
[[bin]]
name = "coa-launcher"
path = "src/main.rs"
[dependencies]
coa-core = { path = "../coa-core" }
serde_json = "1"
windows-sys = { version = "0.60", features = ["Win32_Foundation", "Win32_System_Console"] }
+222
View File
@@ -0,0 +1,222 @@
//! `coa-launcher.exe`: the repack launcher, the same commands as `Scripts/manage.py`.
//!
//! It lives in `<server>/Scripts/` next to manage.py (the server folder is its parent), or takes `--root <folder>`.
//! Errors are printed as `ERROR: <message>` on stderr with exit code 1, exactly like manage.py, because the
//! Manager reads them.
use std::io::{BufRead, Write};
use std::path::{Path, PathBuf};
use std::time::Duration;
use coa_core::launcher::ops::{self, Action};
use coa_core::launcher::{services, settings::Settings, state, world};
const ACTIONS: [&str; 18] = [
"start-all", "start-mysql", "start-auth", "start-world", "stop-all", "force-stop-all", "status", "status-json", "create-account",
"create-account-once", "console", "ra-once", "prepare", "watch-world", "relay-worker", "debug-logs-on",
"debug-logs-off", "debug-logs-status",
];
fn say(text: &str) {
println!("{text}");
let _ = std::io::stdout().flush();
}
fn usage() -> String {
format!("usage: coa-launcher [--root <server>] [--port-offset N] {{{}}}", ACTIONS.join(","))
}
struct Args {
root: PathBuf,
offset: i32,
action: String,
}
fn parse() -> Result<Args, String> {
let mut root: Option<PathBuf> = None;
let mut offset = 0;
let mut action = None;
let mut it = std::env::args().skip(1);
while let Some(a) = it.next() {
match a.as_str() {
"--root" => root = Some(PathBuf::from(it.next().ok_or_else(usage)?)),
"--port-offset" => offset = it.next().and_then(|v| v.parse().ok()).ok_or_else(usage)?,
_ if ACTIONS.contains(&a.as_str()) && action.is_none() => action = Some(a),
_ => return Err(usage()),
}
}
let root = match root {
Some(r) => r,
None => {
// <server>/Scripts/coa-launcher.exe -> <server>
let exe = std::env::current_exe().map_err(|e| e.to_string())?;
exe.parent().and_then(Path::parent).map(Path::to_path_buf).ok_or("cannot find the server folder")?
}
};
Ok(Args { root, offset, action: action.ok_or_else(usage)? })
}
fn read_line(prompt: &str) -> std::io::Result<String> {
print!("{prompt}");
std::io::stdout().flush()?;
let mut line = String::new();
std::io::stdin().lock().read_line(&mut line)?;
Ok(line.trim_end_matches(['\r', '\n']).to_string())
}
/// Read a line without showing it (passwords).
fn read_secret(prompt: &str) -> std::io::Result<String> {
#[cfg(windows)]
unsafe {
use windows_sys::Win32::System::Console::{GetConsoleMode, GetStdHandle, SetConsoleMode, ENABLE_ECHO_INPUT, STD_INPUT_HANDLE};
let h = GetStdHandle(STD_INPUT_HANDLE);
let mut mode = 0;
if GetConsoleMode(h, &mut mode) != 0 {
SetConsoleMode(h, mode & !ENABLE_ECHO_INPUT);
let line = read_line(prompt);
SetConsoleMode(h, mode);
println!();
return line;
}
}
read_line(prompt)
}
fn valid_login(text: &str) -> bool {
(1..=16).contains(&text.len()) && text.bytes().all(|b| b.is_ascii_alphanumeric())
}
fn ra(cfg: &Settings, root: &Path, command: &str) -> Result<String, String> {
if !services::ready(root, "world", cfg.ra_port) {
return Err("Start this repack's worldserver first.".into());
}
let mut console = coa_core::ra::Ra::connect_to(cfg.ra_port, &cfg.ra_username, &cfg.ra_password).map_err(|e| e.to_string())?;
console.run(command).map_err(|e| e.to_string())
}
fn run(args: Args) -> Result<(), String> {
let root = args.root.as_path();
let e = |x: coa_core::Error| x.to_string();
match args.action.as_str() {
"watch-world" => {
let me = std::env::current_exe().map_err(|x| x.to_string())?;
return world::watch_world(root, Some(&me), &|m| say(m)).map_err(e);
}
"relay-worker" => return coa_core::launcher::relay::worker(root).map_err(e),
"debug-logs-status" => {
let on = services::status(root)["debugLogs"].as_bool().unwrap_or(false);
say(&format!("Detailed server logging is {}.", if on { "ON" } else { "off" }));
if on {
say("Every AzerothCore logger is forced to Trace level in Core/Logs (Server.log, Auth.log, world-console.log, auth-console.log). Expect much larger, faster-growing log files.");
}
say("Run Debug_Logs_On.bat / Debug_Logs_Off.bat, then restart the affected service(s) to apply.");
return Ok(());
}
"debug-logs-on" | "debug-logs-off" => {
let on = args.action == "debug-logs-on";
let changed = {
let _lock = state::ControlLock::acquire(root, &args.action, Duration::from_secs(30), &|m| say(m)).map_err(e)?;
world::debug_logs(root, on).map_err(e)?
};
if changed.is_empty() {
say(&format!("Detailed logging was already {}.", if on { "on" } else { "off" }));
} else {
say(&format!("{} detailed logging in: {}", if on { "Enabled" } else { "Restored" }, changed.join(", ")));
}
say("Restart the affected service(s) (Stop_All_Server.bat then Start_All_Server.bat) to apply this.");
return Ok(());
}
_ => {}
}
let cfg = Settings::load(root, args.offset).map_err(e)?;
match args.action.as_str() {
"console" => {
say("World console. Enter a server command, or exit to close this window.");
loop {
let command = read_line("AC> ").map_err(|x| x.to_string())?;
let command = command.trim();
if command.eq_ignore_ascii_case("exit") || command.eq_ignore_ascii_case("quit") {
return Ok(());
}
if !command.is_empty() {
say(&ra(&cfg, root, command)?);
}
}
}
"create-account" => {
let name = read_line("New account name (letters and digits, up to 16): ").map_err(|x| x.to_string())?;
let name = name.trim();
let password = read_secret("New account password (letters and digits, up to 16): ").map_err(|x| x.to_string())?;
let again = read_secret("Repeat password: ").map_err(|x| x.to_string())?;
if !valid_login(name) || !valid_login(&password) {
return Err("Use 1-16 letters or digits for the account name and password.".into());
}
if password != again {
return Err("Passwords do not match.".into());
}
say(&ra(&cfg, root, &format!("account create {name} {password}"))?);
if read_line("Give this account GM permissions? [y/N]: ").map_err(|x| x.to_string())?.trim().eq_ignore_ascii_case("y") {
say(&ra(&cfg, root, &format!("account set gmlevel {name} 3 -1"))?);
}
return Ok(());
}
"ra-once" => {
let command = read_line("").map_err(|x| x.to_string())?;
let command = command.trim();
if command.is_empty() {
return Err("No command given.".into());
}
say(&ra(&cfg, root, command)?);
return Ok(());
}
"create-account-once" => {
let line = read_line("").map_err(|x| x.to_string())?;
let request: serde_json::Value = serde_json::from_str(&line).map_err(|x| x.to_string())?;
let name = request.get("username").and_then(|v| v.as_str()).unwrap_or("").trim().to_string();
let password = request.get("password").and_then(|v| v.as_str()).unwrap_or("").to_string();
if !valid_login(&name) || !valid_login(&password) {
return Err("Use 1-16 letters or digits for the account name and password.".into());
}
let mut messages = vec![ra(&cfg, root, &format!("account create {name} {password}"))?];
if request.get("gm").and_then(|v| v.as_bool()).unwrap_or(false) {
messages.push(ra(&cfg, root, &format!("account set gmlevel {name} 3 -1"))?);
}
say(&serde_json::json!({ "messages": messages }).to_string());
return Ok(());
}
_ => {}
}
match args.action.as_str() {
"status" | "status-json" => {
let _lock = state::ControlLock::acquire(root, &args.action, Duration::from_secs(30), &|m| say(m)).map_err(e)?;
if args.action == "status-json" {
say(&services::status(root).to_string());
} else {
for name in ["mysql", "auth", "world", "relay"] {
let line = match state::running(root, name) {
Some(r) => format!("{name:12} running (PID {})", r.pid),
None => format!("{name:12} stopped"),
};
say(&line);
}
}
return Ok(());
}
_ => {}
}
let action = Action::parse(&args.action).ok_or_else(usage)?;
let me = world::Supervisor::Launcher(std::env::current_exe().map_err(|x| x.to_string())?);
ops::run(root, &cfg, args.offset, action, Some(&me), &|m| say(m)).map_err(e)?;
if args.action.starts_with("start-") {
say("Use Stop_All_Server.bat to shut down this repack safely.");
}
Ok(())
}
fn main() {
let result = parse().and_then(run);
if let Err(message) = result {
eprintln!("ERROR: {message}");
std::process::exit(1);
}
}
+2 -1
View File
@@ -94,8 +94,9 @@ fn run() -> Result<(), String> {
.map_err(e)?;
}
"qualify-install" => {
let report = coa_core::release_schema::qualify_install(
let report = coa_core::release_schema::qualify_install_against(
&PathBuf::from(need(&a, "package")?),
Some(&PathBuf::from(need(&a, "update")?)),
&PathBuf::from(need(&a, "fixture")?),
coa_core::signing::EMBEDDED_PUBLIC_KEY,
)
+18
View File
@@ -1,6 +1,24 @@
{
"schema": 1,
"modules": [
{
"id": "dungeon-clear",
"name": "Dungeon Clear",
"description": {
"en": "Dungeon tactics for SQUID bots. Requires SQUID bots to be enabled.",
"ru": "Тактика подземелий для SQUID bots. Работает только при включённых SQUID bots.",
"de": "Dungeon-Taktiken für SQUID-Bots. Erfordert aktivierte SQUID-Bots.",
"fr": "Tactiques de donjon pour les bots SQUID. Nécessite les bots SQUID activés.",
"es": "Tácticas de mazmorra para bots SQUID. Requiere activar los bots SQUID.",
"zh": "为 SQUID 机器人提供地下城战术。需要启用 SQUID 机器人。"
},
"repo": "https://github.com/Zyth45/mod-dungeon-clear",
"conf": "mod_dungeon_clear.conf",
"enable_key": "DungeonClear.Enable",
"default_on": false,
"status": "early",
"icon": "bot"
},
{
"id": "companions",
"name": "CoA Companions",
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "coa-server-manager",
"version": "0.9.0",
"version": "0.9.10",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "coa-server-manager",
"version": "0.9.0",
"version": "0.9.10",
"dependencies": {
"@tauri-apps/api": "^2.12.0",
"@tauri-apps/plugin-dialog": "^2.8.0",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "coa-server-manager",
"private": true,
"version": "0.9.0",
"version": "0.9.10",
"license": "AGPL-3.0-only",
"type": "module",
"scripts": {
+1
View File
@@ -16,6 +16,7 @@ tauri = { version = "2", features = ["tray-icon"] }
tauri-plugin-dialog = "2"
tauri-plugin-updater = "2"
tauri-plugin-process = "2"
tauri-plugin-single-instance = "2"
tauri-plugin-opener = "2"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
+52
View File
@@ -0,0 +1,52 @@
use std::path::Path;
pub fn enabled(dir: &Path) -> coa_core::Result<bool> {
match std::fs::read(dir.join("public-server-browsing.json")) {
Ok(bytes) => Ok(serde_json::from_slice(&bytes)?),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(true),
Err(e) => Err(e.into()),
}
}
pub fn save(dir: &Path, enabled: bool) -> coa_core::Result<()> {
coa_core::fsx::atomic_write_json(&dir.join("public-server-browsing.json"), &enabled)
}
pub fn require_enabled(dir: &Path) -> coa_core::Result<()> {
if enabled(dir)? {
Ok(())
} else {
Err(coa_core::Error::Invalid(
"Public server browsing is disabled in Settings.".into(),
))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn disabled_and_corrupt_preferences_block_browsing() {
let dir = std::env::temp_dir().join(format!(
"coa-browse-prefs-{}-{}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
));
std::fs::create_dir_all(&dir).unwrap();
assert!(enabled(&dir).unwrap());
save(&dir, false).unwrap();
assert!(!enabled(&dir).unwrap());
assert!(require_enabled(&dir).is_err());
save(&dir, true).unwrap();
assert!(require_enabled(&dir).is_ok());
let file = dir.join("public-server-browsing.json");
std::fs::write(&file, b"broken").unwrap();
assert!(require_enabled(&dir).is_err());
std::fs::remove_file(file).unwrap();
std::fs::remove_dir(dir).unwrap();
}
}
+205 -37
View File
@@ -5,7 +5,9 @@ use std::collections::HashSet;
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
mod browse_preferences;
mod docker_install;
mod window_preferences;
use coa_core::backup::{self, Kind, RecoveryPoint, Trigger, VerifyReport};
use coa_core::config::{self, Scope, SettingsView};
@@ -28,6 +30,16 @@ use tauri::{AppHandle, Emitter, Manager, State};
mod control_cmds;
/// Informational release notes only; never used to select or authorize an update.
#[tauri::command]
async fn release_history(component: String, target: Option<String>) -> std::result::Result<Value, String> {
tauri::async_runtime::spawn_blocking(move || {
coa_core::release_history::load_for_target(&component, &data_dir().join("release-history"), target.as_deref())
})
.await
.map_err(|e| e.to_string())?
}
struct AppState {
registry: Registry,
/// Installation ids with a start/stop currently running (one action at a time per server).
@@ -291,10 +303,39 @@ fn installation_source(custom: Option<String>) -> Result<Source> {
.ok()
.filter(|value| !value.trim().is_empty())
});
select_installation_source(custom, || update_source(None))
}
fn select_installation_source(
custom: Option<String>,
latest: impl FnOnce() -> Result<Source>,
) -> Result<Source> {
if custom.is_some() {
return Ok(package_source(custom));
}
Ok(Source::Installation(Box::new(update_source(None)?)))
Ok(Source::Installation(Box::new(latest()?)))
}
#[cfg(test)]
mod installation_source_tests {
use super::*;
#[test]
fn fresh_install_uses_the_selected_current_release_full_image() {
let source = select_installation_source(None, || {
Ok(Source::Url("https://example.test/releases/current".into()))
}).unwrap();
assert!(matches!(source, Source::Installation(inner)
if matches!(*inner, Source::Url(ref url) if url.ends_with("/current"))));
}
#[test]
fn unavailable_current_release_does_not_fall_back_to_an_old_base() {
let result = select_installation_source(None, || {
Err(Error::PackageNotPublished("current unavailable".into()))
});
assert!(matches!(result, Err(Error::PackageNotPublished(_))));
}
}
#[derive(Serialize)]
@@ -612,7 +653,10 @@ async fn start_server(
&& coa_core::friends::load(&meta).mode != coa_core::friends::Mode::Local
{
let extra = coa_core::realms::state(&root)?.extra_world_ports();
if let Err(e) = coa_core::firewall::ensure_rules_with_extra(&layout::read_ports(&root), &extra) {
if let Err(e) = coa_core::firewall::ensure_rules_with_extra(
&layout::read_ports(&root),
&extra,
) {
tracing::warn!("firewall rules for the running worlds were not added: {e}");
}
}
@@ -624,6 +668,16 @@ async fn start_server(
Ok(out)
}
#[tauri::command]
async fn force_stop_server(
state: State<'_, AppState>,
id: String,
) -> std::result::Result<DriverOutcome, UiError> {
let root = path_of(&state, &id)?;
let _guard = BusyGuard::acquire(&state, &id)?;
blocking(move || driver::force_stop(&root)).await
}
#[tauri::command]
async fn stop_server(
state: State<'_, AppState>,
@@ -669,6 +723,20 @@ async fn get_settings(
blocking(move || config::load(&root, scope)).await
}
#[tauri::command]
async fn server_logging_preset(
state: State<'_, AppState>,
id: String,
preset: String,
) -> std::result::Result<(), UiError> {
let root = path_of(&state, &id)?;
let _guard = BusyGuard::acquire(&state, &id)?;
blocking(move || {
let meta = meta_dir(&root)?;
coa_core::server_logging::apply(&root, &meta, &preset)
}).await
}
#[tauri::command]
async fn save_settings(
state: State<'_, AppState>,
@@ -1030,14 +1098,10 @@ async fn create_account(
password: String,
administrator: bool,
) -> std::result::Result<(), UiError> {
let _guard = BusyGuard::acquire(&state, &id)?;
let root = path_of(&state, &id)?;
blocking(move || {
coa_core::ra::validate_account(&username, &password)?;
let mut ra = Ra::connect(&root)?;
ra.create_account(&username, &password)?;
if administrator {
ra.make_administrator(&username)?;
}
coa_core::accounts::create(&root, &username, &password, administrator)?;
tracing::info!(%username, administrator, "account created");
Ok(())
})
@@ -1987,6 +2051,34 @@ fn client_of(root: &std::path::Path) -> Result<(PathBuf, InstallMeta, Option<Pat
Ok((dir, meta, Some(client)))
}
#[tauri::command]
fn client_graphics(
state: State<'_, AppState>,
id: String,
) -> std::result::Result<coa_core::client_graphics::Graphics, UiError> {
Ok(coa_core::client_graphics::status(
&client_context(&state, &id)?.require()?,
)?)
}
#[tauri::command]
fn client_set_graphics(
state: State<'_, AppState>,
id: String,
name: String,
disabled: bool,
) -> std::result::Result<coa_core::client_graphics::Graphics, UiError> {
let job = state.client_cancel.lock().unwrap();
if job.is_some() {
return Err(Error::Invalid("Wait for the client operation to finish.".into()).into());
}
Ok(coa_core::client_graphics::set(
&client_context(&state, &id)?.require()?,
&name,
disabled,
)?)
}
#[tauri::command]
fn client_info(
state: State<'_, AppState>,
@@ -2482,7 +2574,7 @@ async fn report_context(
.into_iter()
.flatten()
.collect::<Vec<String>>()
.join(" · ");
.join(" В· ");
Ok(ReportContext {
manager_version: coa_core::MANAGER_VERSION.to_string(),
windows: windows_version(),
@@ -2782,30 +2874,69 @@ async fn console_command(
.await
}
#[tauri::command]
fn manager_installing(enabled: bool) {
QUIT_REQUESTED.store(enabled, std::sync::atomic::Ordering::SeqCst);
}
#[tauri::command]
fn close_manager(app: AppHandle) -> std::result::Result<(), UiError> {
if window_preferences::close_to_tray(&data_dir()).unwrap_or(false) {
QUIT_REQUESTED.store(false, std::sync::atomic::Ordering::SeqCst);
if let Some(window) = app.get_webview_window("main") {
window.hide().map_err(|e| Error::Invalid(e.to_string()))?;
}
} else {
QUIT_REQUESTED.store(true, std::sync::atomic::Ordering::SeqCst);
app.exit(0);
}
Ok(())
}
#[tauri::command]
fn close_to_tray() -> std::result::Result<bool, UiError> {
Ok(window_preferences::close_to_tray(&data_dir())?)
}
#[tauri::command]
fn set_close_to_tray(enabled: bool) -> std::result::Result<(), UiError> {
Ok(window_preferences::save(&data_dir(), enabled)?)
}
fn show_main_window(app: &AppHandle) {
let handle = app.clone();
if let Err(error) = app.run_on_main_thread(move || {
if let Some(window) = handle.get_webview_window("main") {
let result = window
.unminimize()
.and_then(|_| window.show())
.and_then(|_| window.set_focus());
if let Err(error) = result {
tracing::error!(%error, "Could not restore the Manager window");
}
} else {
tracing::error!("The Manager main window is missing");
}
}) {
tracing::error!(%error, "Could not schedule Manager window restoration");
}
}
static QUIT_REQUESTED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
pub fn run() {
let dir = data_dir();
let _ = coa_core::logging::init(&dir.join("logs").join("manager.log"));
// Crash safety: recover any unfinished client realmlist overrides from previous abnormal termination
let _ = coa_core::client::revert_realmlist_override(&dir);
let portable = start_portable(&dir);
let (control, host_control) = control_cmds::start(&dir, portable.clone());
tauri::Builder::default()
.plugin(tauri_plugin_single_instance::init(|app, _, _| {
show_main_window(app)
}))
.plugin(tauri_plugin_dialog::init())
.plugin(tauri_plugin_updater::Builder::new().build())
.plugin(tauri_plugin_process::init())
.manage(AppState {
registry: Registry::at(dir.join("installs.json")),
busy: Mutex::new(HashSet::new()),
install_cancel: Mutex::new(None),
client_cancel: Mutex::new(None),
portable,
realm_registry: start_realm_registry(&dir),
control,
host_control,
})
.invoke_handler(tauri::generate_handler![
server_logging_preset,
release_history,
default_install_dir,
game_data_folder,
set_game_data_folder,
@@ -2817,6 +2948,7 @@ pub fn run() {
server_status,
start_server,
stop_server,
force_stop_server,
get_settings,
save_settings,
list_presets,
@@ -2881,6 +3013,8 @@ pub fn run() {
remote_connection,
remote_connect,
client_info,
client_graphics,
client_set_graphics,
set_client,
client_realmlist,
client_install_addon,
@@ -2921,6 +3055,12 @@ pub fn run() {
portable_launch,
registry_status,
portable_preflight_remote,
manager_installing,
close_manager,
close_to_tray,
set_close_to_tray,
browse_enabled,
browse_set_enabled,
browse_list,
browse_detail,
module_catalog,
@@ -2941,18 +3081,43 @@ pub fn run() {
])
.on_window_event(|window, event| {
if let tauri::WindowEvent::CloseRequested { api, .. } = event {
api.prevent_close();
let _ = window.hide();
if window.label() != "main" {
return;
}
if window_preferences::close_to_tray(&data_dir()).unwrap_or(false) {
api.prevent_close();
if let Err(error) = window.hide() {
tracing::warn!(%error, "Could not hide the Manager window");
}
} else {
QUIT_REQUESTED.store(true, std::sync::atomic::Ordering::SeqCst);
}
}
})
.setup(|app| {
let dir = data_dir();
// Crash safety: recover any unfinished client realmlist overrides from previous abnormal termination
let _ = coa_core::client::revert_realmlist_override(&dir);
let portable = start_portable(&dir);
let (control, host_control) = control_cmds::start(&dir, portable.clone());
app.manage(AppState {
registry: Registry::at(dir.join("installs.json")),
busy: Mutex::new(HashSet::new()),
install_cancel: Mutex::new(None),
client_cancel: Mutex::new(None),
portable,
realm_registry: start_realm_registry(&dir),
control,
host_control,
});
#[cfg(desktop)]
{
use tauri::menu::{Menu, MenuItem};
use tauri::tray::{MouseButton, MouseButtonState, TrayIconBuilder, TrayIconEvent};
use tauri::Manager;
let show = MenuItem::with_id(app, "show", "Open CoA Server Manager", true, None::<&str>)?;
let show =
MenuItem::with_id(app, "show", "Open CoA Server Manager", true, None::<&str>)?;
let quit = MenuItem::with_id(app, "quit", "Exit", true, None::<&str>)?;
let menu = Menu::with_items(app, &[&show, &quit])?;
@@ -2962,11 +3127,7 @@ pub fn run() {
.show_menu_on_left_click(false)
.on_menu_event(|app, event| match event.id.as_ref() {
"show" => {
if let Some(window) = app.get_webview_window("main") {
let _ = window.show();
let _ = window.unminimize();
let _ = window.set_focus();
}
show_main_window(app);
}
"quit" => {
QUIT_REQUESTED.store(true, std::sync::atomic::Ordering::SeqCst);
@@ -2982,11 +3143,7 @@ pub fn run() {
} = event
{
let app = tray.app_handle();
if let Some(window) = app.get_webview_window("main") {
let _ = window.show();
let _ = window.unminimize();
let _ = window.set_focus();
}
show_main_window(app);
}
});
@@ -3046,6 +3203,7 @@ async fn portable_preflight_remote(
}
fn browse_client() -> std::result::Result<coa_core::realm_registry::BrowseClient, UiError> {
browse_preferences::require_enabled(&data_dir())?;
let settings = coa_core::realm_registry::settings::load(&data_dir().join("registry"))?;
let url = std::env::var("COA_REGISTRY_URL")
.ok()
@@ -3054,6 +3212,16 @@ fn browse_client() -> std::result::Result<coa_core::realm_registry::BrowseClient
Ok(coa_core::realm_registry::BrowseClient::new(&url)?)
}
#[tauri::command]
fn browse_enabled() -> std::result::Result<bool, UiError> {
Ok(browse_preferences::enabled(&data_dir())?)
}
#[tauri::command]
fn browse_set_enabled(enabled: bool) -> std::result::Result<(), UiError> {
Ok(browse_preferences::save(&data_dir(), enabled)?)
}
fn browse_error(e: coa_core::realm_registry::ClientError) -> UiError {
Error::Invalid(e.to_string()).into()
}
+13
View File
@@ -0,0 +1,13 @@
use std::path::Path;
pub fn close_to_tray(dir: &Path) -> coa_core::Result<bool> {
match std::fs::read(dir.join("close-to-tray.json")) {
Ok(bytes) => Ok(serde_json::from_slice(&bytes)?),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(false),
Err(e) => Err(e.into()),
}
}
pub fn save(dir: &Path, enabled: bool) -> coa_core::Result<()> {
coa_core::fsx::atomic_write_json(&dir.join("close-to-tray.json"), &enabled)
}
+1 -1
View File
@@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "CoA Server Manager",
"version": "0.9.0",
"version": "0.9.10",
"identifier": "com.coa.servermanager",
"build": {
"beforeDevCommand": "npm run dev",
+1 -1
View File
@@ -15,7 +15,7 @@ const buttonVariants = cva(
size: {
sm: "h-9 px-3 text-sm",
md: "h-11 px-5 text-[15px]",
xl: "h-16 px-10 text-lg tracking-wide",
xl: "h-12 px-6 text-base",
},
},
defaultVariants: { variant: "secondary", size: "md" },
+15
View File
@@ -0,0 +1,15 @@
import { Button, type ButtonProps } from "./button";
/** Two explicit actions, each with its own enabled state and keyboard focus. */
export function SplitButton({ label, primary, secondary }: {
label: string;
primary: ButtonProps;
secondary: ButtonProps;
}) {
return <div role="group" aria-label={label} className="inline-flex max-w-full items-stretch rounded-md">
<Button type="button" variant="primary" {...primary}
className="h-auto min-h-12 min-w-0 rounded-r-none px-5 py-2 text-sm whitespace-normal" />
<Button type="button" variant="secondary" {...secondary}
className="h-auto min-h-12 min-w-0 rounded-l-none border-l border-l-gold/30 px-4 py-2 text-sm whitespace-normal" />
</div>;
}
Loaded 100 of 147 files, more files were not shown because too many files have changed in this diff. Show more