Compare commits

..
Author SHA1 Message Date
Дмитрий 74473471db fix(companions): reuse offline bot pool before spawning and preserve AutoLogin.MaxCount 2026-11-18 10:38:31 +05:00
ДмитрийandClaude Sonnet 5.5 7cdf854eb0 feat(client): drop built-in client download, point players to the community launcher
The community moved the game client behind its official launcher (account
sign-in, signed manifest, its own CDN), so the public manifest now answers 404
and the Manager must not pose as the launcher. Remove the client download and
update path (clientdl, plan/sync/download/cancel commands, update job and
progress UI, version tracking) and reduce "Set up the game client" to: open
coa-development.org for the launcher, or pick a folder that already has the
game. Linking a folder, realmlist switch, companion addon and the custom-race
patch are unchanged.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-17 10:03:13 +05:00
Дмитрий 0f0f9e6fe2 feat(sdk): SDK v0.3.2 hardening, artifact provenance, and realm-bound GitHub analyzer 2026-11-01 16:00:05 +05:00
Дмитрий e97fe52ab3 feat(analyzer): implement Analyzer v0.2.1 and Adapter Generator v0.1 2026-10-31 15:45:43 +05:00
Дмитрий 4e73c28f7b feat(analyzer): implement Module Analyzer v0.2 with evidence-driven rules 2026-10-31 12:53:31 +05:00
Дмитрий 28af9e2907 feat(analyzer): implement Module Compatibility Analyzer v0.1 in coa-core 2026-10-31 12:16:42 +05:00
Дмитрий 68e9d7d0cf fix(csm_plugins): handle password and env_remove properly in reconcile_squid 2026-10-31 11:56:06 +05:00
Дмитрий 873db420c0 feat(csm_plugins): support live mysql query in reconcile_squid command 2026-10-31 11:49:59 +05:00
Дмитрий b2572d4f7c wip(realms): checkpoint work-in-progress files on branch for clean build provenance 2026-10-31 11:47:51 +05:00
Дмитрий aff7659625 fix(plugins): trigger after_config_edit crash injection regardless of enable_key presence 2026-10-31 10:42:11 +05:00
Дмитрий 49d1ae75ab feat(plugins): implement durable transaction journal, crash recovery, and multiworld reference safety 2026-10-31 10:34:37 +05:00
Дмитрий cf94868fd9 feat(plugins): harden FV1 RC with dual-source SQL reconciliation, TxGuard rollback, and multiworld isolation 2026-10-31 09:53:34 +05:00
Дмитрий 90f93074c2 feat(plugins): implement CoA Dynamic Plugin Architecture (FV1) in CSM 2026-10-31 09:23:10 +05:00
Дмитрий c5eac64477 Fix custom races transactions with linked addons on another volume 2026-10-23 08:54:00 +05:00
Дмитрий 039c40da06 Separate SQUID bots from advertised online players 2026-10-23 08:53:52 +05:00
Дмитрий b3bb0fdc19 feat: portable play settings, improved offline messaging, and system tray support 2026-10-23 08:53:48 +05:00
269 changed files with 5858 additions and 12077 deletions

No files matched your search

-13
View File
@@ -51,16 +51,3 @@ Server promotion uses the persistent Windows PC and the shared workflow's verifi
production databases; run applicable local acceptance in disposable fixtures. Record the actual passed,
failed and unrun checks. Verify both GitHub Latest and the public signed stable pointer before reporting
that users can update. Leave the durable handoff described in the runbook for the next agent.
## Public documentation languages
Maintain the public README and every player/server-owner guide in all six Manager languages:
English, Russian, German, French, Spanish and Simplified Chinese. English stays at `README.md`
and the player-facing `docs/*.md`; translated READMEs use `README.<locale>.md`, with guides in
`docs/<locale>/` (`ru`, `de`, `fr`, `es`, `zh-CN`). Language switches open the same page.
When changing a public guide, update its counterparts in the same change. Write naturally for
players in each language rather than translating word for word. Keep steps, feature limits and
experimental Portable Characters warnings equivalent. Use actual UI labels; retain English labels
where the released UI falls back to English. English screenshots stay in `docs/screenshots/`; localized images use its `ru`, `de`, `fr`, `es` and `zh-CN` subfolders. Keep the interface and annotation language consistent with each guide.
The public guide index is `docs/README.md`; internal protocol specifications and audits are not
player guides. Keep canonical release histories in English and link to them instead of making copies.
-69
View File
@@ -8,75 +8,6 @@ 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.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.**
- Installs the verified CoA Custom 1.9.2 client patches and quest safety addon, while recognizing existing 1.9.1 installations.
- Server updates preserve the order of database migrations introduced during merges, preventing older snapshots from overwriting newer progression.
[Release](https://github.com/Corfirean/coa-server-manager/releases/tag/v0.8.2) · [Source changes](https://github.com/Corfirean/coa-server-manager/compare/v0.8.1...v0.8.2)
## 0.8.1 — 2026-10-25
**Portable Characters are experimental and may contain bugs.**
- Install the matching CoA Custom 1.9.1 client files.
[Release](https://github.com/Corfirean/coa-server-manager/releases/tag/v0.8.1) · [Source changes](https://github.com/Corfirean/coa-server-manager/compare/v0.8.0...v0.8.1)
## 0.8.0 — 2026-10-24
**Portable Characters are experimental and may contain bugs.**
- Server owners can allow portable characters per realm.
- Allowing portable characters also prepares the server for portable sessions.
- Managers stay compatible with the public connection service.
- Relay connections recover and use the ports of the installed server.
- Portable progress resumes after reconnecting or restarting the Manager.
- Older copies on another host may require maintenance before returning.
[Release](https://github.com/Corfirean/coa-server-manager/releases/tag/v0.8.0) · [Source changes](https://github.com/Corfirean/coa-server-manager/compare/v0.7.3...v0.8.0)
## 0.7.3 — 2026-10-23
**Portable Characters are experimental and may contain bugs.**
- Portable characters open again after using an experimental Manager.
[Release](https://github.com/Corfirean/coa-server-manager/releases/tag/v0.7.3) · [Source changes](https://github.com/Corfirean/coa-server-manager/compare/v0.7.2...v0.7.3)
## 0.7.2 — 2026-10-23
- Advanced settings cover creature melee damage, spell damage and health by rank.
- Internet sharing accepts existing port forwards to the same server.
- The Auction House Bot card has a single switch.
- More character and server browser controls now use your selected language.
- Online player counts correctly separate random bots from players.
- Custom races work with shared addon folders on another drive.
- Configure the day and night cycle from the module settings.
- A stalled database inspection no longer blocks server maintenance indefinitely.
[Release](https://github.com/Corfirean/coa-server-manager/releases/tag/v0.7.2) · [Source changes](https://github.com/Corfirean/coa-server-manager/compare/v0.7.1...v0.7.2)
## 0.7.1 — 2026-10-22
Close the game, then open Modules → Custom Races → Repair Client Patch to update existing patches, or Install Client Patch for a new installation. Updating the Manager does not automatically replace game files or update your server.
Generated
+3 -3
View File
@@ -586,7 +586,7 @@ dependencies = [
[[package]]
name = "coa-core"
version = "0.9.1"
version = "0.7.1"
dependencies = [
"base64 0.22.1",
"chrono",
@@ -634,7 +634,7 @@ dependencies = [
[[package]]
name = "coa-release"
version = "0.9.1"
version = "0.7.1"
dependencies = [
"chrono",
"coa-core",
@@ -643,7 +643,7 @@ dependencies = [
[[package]]
name = "coa-server-manager"
version = "0.9.1"
version = "0.7.1"
dependencies = [
"coa-control-proto",
"coa-core",
+1 -1
View File
@@ -4,7 +4,7 @@ members = ["crates/coa-core", "crates/coa-release", "crates/coa-registry-proto",
exclude = ["services/coa-registry", "services/coa-registry-e2e", "services/coa-coordinator", "services/coa-relay"]
[workspace.package]
version = "0.9.1"
version = "0.7.1"
edition = "2021"
license = "AGPL-3.0-only"
-228
View File
@@ -1,228 +0,0 @@
# Per-race availability audit
Date: 2026-10-27. This is an internal implementation audit, not a supported-feature guide.
## Frozen sources
Separate `feat/per-race-toggles` branches and checkouts:
| Component | Checkout | Fetched base |
| --- | --- | --- |
| Manager | `C:/games/source/per-race-manager` | `origin/master`, `925a81f` |
| Core | `C:/games/source/per-race-core` | `origin/coa-bots`, `1c658cab46d5057a8972cebd84c840aa6fbc4a91` |
| CoA Companions | `C:/games/source/per-race-companions` | `origin/master`, `6a289fc2230ce9425924ca86dee02d0bb8d3d344` |
| Build | `C:/games/source/per-race-build` | `origin/main`, `89795b6` |
The build runbook explicitly selects `Corfirean/azerothcore-wotlk-coa:coa-bots`, not its `main`.
The old `C:/games/source/server/azerothcore-wotlk-coa` checkout instead tracks jealous-sound upstream
and has local modifications. It must not be used as the feature's release base.
The primary Manager and Companions checkouts also contain unrelated work and remain untouched.
SQUID is a separate repository, `Zyth45/mod-playerbots`, not `Corfirean/mod-coa-playerbots`.
Existing research checkout: `C:/games/source/squid-playerbots`. Its current local branch is
`fix/custom-races-existing-bots`, one commit ahead of `origin/coa`. Build policy selects the highest
stable numeric tag, so that local branch must not silently become the shipped dependency.
## Manager integration points
- `crates/coa-core/src/custom_races.rs`: package version `1.9.2`, release URLs, MPQ/root/addon lists,
hash manifests, client status, install, enable/disable and uninstall.
- `PatchTransaction`, `SavedFile`, `recover_patch_transaction`: shared client-relative journal in
`.coa-races-transaction/journal.json`, saved files and `committed` marker. Uncommitted changes roll back.
Paths use `fsx::safe_join`; file moves handle cross-volume addon locations.
- `patch_lock`: exclusive OS file lock on `.coa-races.lock`. The empty file's existence is normal and
does not prove another operation is active. Do not delete it as a stale-lock workaround.
- Client mutations reject `client::is_running`; reuse this gate and lock for availability changes.
- `patch_files`, `matches_patch`, `preserve_original`: ownership and preservation depend on manifests
and hashes, not just a filename. Availability overlay ownership needs its own verified record.
- `modules/catalog.json`: `custom-races` uses `coa_custom_races.conf` and `CoACustomRaces.Enable`.
Companions use `mod_coa_playerbots.conf` / `CoaBots.Enable`; SQUID uses
`playerbots.conf` / `AiPlayerbot.Enabled`.
- `crates/coa-core/src/modules.rs`: `toggle`, `settings_in`, `save_settings_in` write current module
configuration. Bot switches enforce stopped servers and the existing control lock.
- `src/screens/ModulesPage.tsx`: Custom Races card, master toggle, install/progress/status UI.
- `src/lib/api.ts` and `src-tauri/src/lib.rs`: existing `custom_races_status`,
`custom_races_install`, `custom_races_uninstall`, `custom_races_toggle_client` commands.
There is no per-race command or verified availability status yet.
- `src-tauri/src/lib.rs::play`: local launch reads `realms::state`, calls `client::sync_realm`, then
launches. Remote launch has a separate realmlist override path; it cannot infer a remote race policy.
- `crates/coa-core/src/realms.rs`: modes CoA, Wildcard and Warcraft Reborn; current configs are captured
under `Settings/realm-profiles/<mode>.json`. Use this mechanism rather than a parallel realm store.
Existing bot restrictions for non-CoA modes must remain effective.
- `crates/coa-core/src/clientdl.rs::apply`: manifest-based client updates, `keep_modified`, staging,
preservation of replaced files. No availability-overlay invalidation or rebuild exists today.
### Confirmed reconciliation risk
`custom_races.rs::sync_bot_races_config` writes a replacement `AiPlayerbot.ExcludedBotRaces` value:
recommended full exclusions or experimental `65,72,77,80,81`. It does not preserve arbitrary user
exclusions. `modules.rs` calls it from the master switch and BotsEnable saving; some callers discard
errors. Per-race integration cannot rely on this overwrite behavior.
`playerbots_conf_paths` can also copy a `.dist` file when no active config exists; it is not a purely
read-only discovery API. Status inspection should avoid adding more implicit writes.
## Core gates and bypasses
- `modules/mod-coa-custom-races/src/mod_coa_custom_races.cpp`: `WorldScript` loads the master switch;
`AccountScript::CanAccountCreateCharacter` accepts stock IDs 1–8, 10, 11 or an enabled master switch.
No disabled-ID list is implemented. Stock ID 9 is deliberately not included.
- `modules/mod-coa-custom-races/conf/coa_custom_races.conf.dist`: Enable and BotsEnable exist;
DisabledRaceIds does not.
- `src/server/game/Handlers/CharacterHandler.cpp`: normal character creation invokes
`sScriptMgr->CanAccountCreateCharacter` inside its finalization callback and rejects with
`CHAR_CREATE_DISABLED`. A packet from an unpatched client reaches that gate too.
- `src/server/game/Scripting/ScriptDefines/AccountScript.cpp`: hook aggregation must be preserved.
- `src/server/game/DataStores/DBCStores.cpp::LoadDBCStores`: chooses `DataDir/dbc_races/<file>` if
the master switch is enabled and that file exists, otherwise `DataDir/dbc/<file>`.
Per-race creation policy must not remove DBC rows or change login data.
- `.agents/docs/systems/ascension-character-creation.md`: native client compatibility depends on
`CharBaseInfo.dbc`; race button indices are not RaceIDs. Existing race/class checks must stay intact.
## Both bot systems
### CoA Companions
`module/src/BotSpawnRandom.cpp::GetValidBotRaces` reads the global and bot custom-race switches,
`CoaBots.CustomRaces.Enable`, and both AiPlayerbot/CoaBots exclusion lists. It checks DBC presence.
Its experimental defaults apply only when the combined exclusion set is empty: adding an owner list
to that set would silently remove those defaults. Keep those policies independent.
`CreateBotClone`, `CreateOneRandomBot`, and leveled spawning clone SQL character data directly;
they bypass the account creation hook. Enforce new-character policy at the common clone creation
entry as well as random selection. Preserve existing bots and faction selection via
`Player::TeamIdForRace`.
Additional confirmed callers: `module/src/BotBattlegroundFill.cpp::QueueBotForSide` and
`module/src/BotLfgFill.cpp` call `CreateOneRandomBot` after trying to reuse an existing bot.
The existing-bot reuse path must remain separate from creation restrictions.
`tools/offline_bot_factory.py` is another direct-SQL creation path. Its main loop chooses a
template by class and faction, then copies `template.race` into the new character overrides.
It currently does not read the custom-race creation policy. Reject or filter prohibited
templates before generating new accounts, GUIDs or SQL; do not rewrite their races.
### SQUID Playerbots
`src/PlayerbotAIConfig.cpp` loads `AiPlayerbot.ExcludedBotRaces` and adds
`AiPlayerbot.CrashingBotRaces`; it reads BotsEnable. `src/CoaBotRacePolicy.h` implements
`IsCoaBotRaceAllowed`. `src/Bot/Factory/RandomPlayerbotFactory.cpp::CreateRandomBot` applies
that policy before faction and race/class selection.
The same predicate also appears in `src/Bot/RandomPlayerbotMgr.cpp` and
`src/Bot/PlayerbotMgr.cpp`, including existing-character admission. Do not append owner creation
restrictions globally to this shared exclusion vector: that would also affect existing bots.
The predicate currently does not itself require `CoACustomRaces.Enable`.
`RandomPlayerbotFactory.cpp` calls `Player::Create` directly without the account hook.
Use a creation-only check in this factory, leaving existing-character admission unchanged.
## Portable Characters
Manager import code is under `crates/coa-core/src/portable/realm/`.
`import.rs` validates identity namespaces and race/class start data (`UnknownRaceClass`).
Availability policy must not become an import rejection or an identity rewrite. The inspected
creation hook is in the normal packet handler, not this importer. In the core,
`src/server/coa/CoAPortableImport.cpp` checks `GetPlayerInfo(model.Race, model.Class)` and writes
`model.Race` to the imported character and character cache. It does not invoke the account
creation hook. Preserve this separation. Live compatibility is still untested.
## Client experiment, actual observations
The owner updated `C:/games/Ascension` from 1.9.1 to 1.9.2 during this audit; its manifest now says
`# CoA Custom 1.9.2`. A separate physical client copy is being prepared under
`C:/games/source/per-race-evidence/client`; game assets are outside Git. The copy completed:
25646 files copied, zero failures. The separate server file copy also completed, but has not
been configured or started. No database service has been started for this task.
Read-only MPQ membership probing found ChrRaces in patch-ZZZF, ZZZE, ZZZC, ZZZ, ZZW, ZZV, ZZU,
ZZS, T, M and several locale archives. CharacterCreate.lua has multiple owners too.
The old `mpqprobe.py` precedence model explicitly admits an inference for Ascension multi-letter
archives. Therefore `patch-ZZZF.MPQ` is a candidate source, not runtime-confirmed effective data.
`patch-ZZZZ.MPQ` exists already; no overlay filename has been qualified.
Extracted from `patch-ZZZF.MPQ`:
- WDBC, 95 records, 69 fields, record size 276, string block 2428, total bytes 28668.
- SHA-256 `b78635b08bf0bd63d2898fce97c1fb162c8a9c41632703172eefa88bae79061f`.
- Actual rows: Sethrak 82, Gnoll 83, Saberon 97. Their Flags are 12.
- String block starts with `Hu`, not NUL; imposing an initial empty-string invariant incorrectly
rejects this real table. String boundaries and referenced offsets still need validation.
- Sethrak experiment changes only Flags 12 → 13. All other bytes compare equal.
- One generated MPQ was read back through StormLib; its DBC equals the expected patched bytes.
- The installed `pympq` Python extension crashed during interpreter finalization. The experimental
tool instead uses the installed Unicode StormLib DLL directly. It is not a runtime dependency
proposal for Manager or its users.
`tools/race_availability_poc.py` requires an explicit source archive and creates output only in a new
directory. It does not select an archive order, install an overlay or assert in-game success.
`tools/test_race_availability_poc.py` uses synthetic bytes only.
### Background verification after interactive testing was deferred
The owner requested no screen capture/input and no client/server/MySQL launches while other bot
tests run. These restrictions remain active. The owner reported that the copied client launches;
this does not confirm creation behavior or effective DBC loading.
- 17 DBC/fingerprint tests and 8 synthetic MPQ integration tests pass (25 total, none skipped).
- Native tests use the explicitly selected existing Unicode StormLib DLL, with no new install.
- Output is built and verified in a temporary directory before publishing the offline result folder.
Failures leave no published result; this is not the future client transaction implementation.
- One and fifty disabled races both produce one MPQ. StormLib adds an internal `(listfile)`;
the sole game payload is `DBFilesClient/ChrRaces.dbc`.
- Every referenced localized race-name offset is bounds-checked; invalid UTF-8 is rejected.
- The experimental fingerprint includes original DBC SHA-256, normalized IDs, algorithm version
and explicitly recorded profile. A profile label does not prove client compatibility.
- The real three-race offline experiment is in
`C:/games/source/per-race-evidence/multiple-races-offline/report.json`.
Source MPQ SHA-256: `40eac695cfcafb598b8376f3b9a61ecc037e4d445b87279cfe387a91edad32c3`.
Generated DBC SHA-256: `243fb36837b76ebd6943da574cc095be548b4530be7f06487debea6703db10d3`.
The first copy launch showed a missing-critical-files message and subsequently crashed on exit.
The crash report identifies `AMDXN32.DLL` in the AMD graphics driver at the fault address; this
does not establish the root cause. EXE, Extensions, dinput8, d3d9, dxgi, EsteriaAppearance and
patch-ZZZF hashes matched the primary client during comparison. The experimental overlay was
not installed. No graphics-driver or client-runtime changes were made to work around the crash.
## Reference implementations and update preservation
Inspected read-only reference clones:
- `aspollon/AFK-Realm` at `ea9c5bf691c98cace8cc03c06183c161022946de`.
- `aspollon/mod-custom-races` at `5a8f2ff8a0d494ffadf64e677a438aa7f5a6671b`.
`mod-custom-races/afk-realm.json` declares client patch generation and GlueXML Lua insertion.
`client/CustomRaces.lua` extends and lays out buttons, using race names/files and configured IDs.
This is a reference, not evidence of compatibility with the current CoA/Esteria UI or a reason
to replace CSM's prebuilt-server distribution.
`crates/coa-core/src/config/merge.rs` performs additive `.dist` merging: missing keys are added,
existing user values and unknown keys are retained. A new DisabledRaceIds key should use this
path. Existing realm snapshots already capture module `.conf` files. Neither mechanism currently
coordinates an availability overlay with client update/repair; that remains implementation work.
## Open gates
Update after the owner found the existing Hide Races panel: see
[existing-filter research](docs/PER_RACE_EXISTING_FILTER_RESEARCH.md). The inspected Lua already
supports personal name/index-based hiding, but it is not a realm-scoped RaceID policy. Nine
offline Lua 5.1 probes confirmed key behavior and limitations. Reusing its layout/UI is now a
candidate to investigate before choosing a production DBC implementation. This is not evidence
that the DBC approach failed, and it does not qualify client support.
The owner subsequently confirmed the GlueXML probe: restricted races disappeared from selection
and were grey, unchecked and disabled in Hide Races. The production client integration should
reuse this filter; changing DBC flags is no longer the selected implementation path.
Server controls, strict catalog-bound configuration, the core creation hook and both bot factory
guards are implemented and have passed offline checks and native builds. Existing-bot admission
and user/crashing exclusions remain separate from the new creation policy.
Remaining gates:
1. Integrate automatic client reconciliation, ownership and recovery with realm settings.
2. Qualify client update/repair and shared-client PLAY behavior.
3. Verify live creation rejection/re-enable, existing-character login, imports and both bot systems
when the owner's database test environment becomes available.
Status: **PARTIAL** — server implementation and builds pass; live server acceptance and production
client synchronization remain pending. See docs/PER_RACE_TOGGLES_TESTS.md for exact scope.
No existing character data, production service, release channel, or primary client archive was changed.
-84
View File
@@ -1,84 +0,0 @@
# CoA Server Manager
[English](README.md) · [Русский](README.ru.md) · **Deutsch** · [Français](README.fr.md) · [Español](README.es.md) · [简体中文](README.zh-CN.md)
**Portable Characters sind experimentell.** Die Funktion wird noch entwickelt und kann Fehler enthalten.
Eine Windows-Anwendung, mit der du deinen eigenen **Conquest of Azeroth**-Server auf Basis von AzerothCore mit wenigen Schritten einrichtest und betreibst. Konsole, manuelle Konfigurationsdateien und separate Datenbankprogramme sind dafür nicht nötig. Entwickelt mit Tauri 2, Rust und React.
![Dein Server im Überblick](docs/screenshots/de/overview.jpg)
## Funktionen
- **Portable Characters — experimentell.** Bewahre Charaktere samt gespeicherten Versionen im Manager auf und übernimm vorhandene Charaktere von Realms, auf die du Zugriff hast. [Zur Anleitung](docs/de/PORTABLE-CHARACTERS.md).
- **Realms entdecken.** Vergleiche öffentlich gelistete Realms nach Spielmodus, Höchststufe, Raten, Modulen und Spielerzahl.
- **Einfache Einrichtung.** Der Manager lädt ein signiertes Serverpaket herunter, prüft die Dateien, richtet die Datenbank ein und erstellt dein erstes Konto. Downloads lassen sich fortsetzen; vorhandene Server kannst du ebenfalls einbinden.
- **Starten, stoppen, spielen.** Steuere Datenbank, Auth- und Weltserver gemeinsam. Status, Laufzeit und Spielerzahl siehst du direkt. Beim Spielstart wird die passende Realmlist verwendet.
- **Spielclient verwalten.** Verwende deinen vorhandenen Client oder lade ihn über den Manager herunter: etwa 43 GB, fortsetzbar und dateiweise geprüft. Verwaltete Clients erhalten Update-Hinweise; selbst veränderte Dateien werden nur mit deiner Zustimmung ersetzt.
- **Serverupdates.** Der Manager sucht beim Start und alle fünf Minuten nach Updates. Ed25519-Signaturen schützen die Pakete. Vor dem Update wird eine Sicherung erstellt; eigene Änderungen bleiben erhalten und ein Rollback ist möglich.
- **Sicherungen.** Sichere Charaktere, Konten und Einstellungen bei Bedarf oder automatisch vor Updates. Prüfen und Wiederherstellen geht direkt in der Anwendung.
- **CoA, Wildcard und Warcraft Reborn.** Wähle den Realm unter Übersicht. Die Serverversion muss den gewählten Modus unterstützen. Beim ersten Wechsel entstehen eine eigene Welt und eine leere Charakterdatenbank. Konten werden geteilt, Charaktere und Moduleinstellungen bleiben getrennt. Ein laufender Server speichert die Charaktere und startet beim Wechsel neu. Schließe vorher den Client; bei geöffnetem Client wird die Realm-Auswahl erst beim nächsten Start über den Manager übernommen. Bots sind auf Wildcard und Warcraft Reborn nicht verfügbar; andere Zusatzmodule sind dort experimentell. Sicherungen und Datenbankupdates berücksichtigen alle angelegten Realms. CoA und Wildcard können gemeinsam laufen. [Wildcard](docs/de/WILDCARD.md) · [Warcraft Reborn](docs/de/WARCRAFT-REBORN.md).
- **Begleiter-Bots.** Erstelle Bots mit passender Stufe, verfolge den Fortschritt, pausiere die Erstellung oder melde Bots ab. Entferne bei Bedarf eine bestimmte Anzahl, um den Server zu entlasten, und lege die Zahl beim Serverstart fest.
- **Realmlists wechseln.** Speichere benannte Verbindungen wie Solo oder PTR und wähle sie neben der Spiel-Schaltfläche. Die zuvor verwendete Datei wird gesichert.
- **Konten und Einstellungen.** Verwalte Namen, Passwörter und Zugriffsrechte. Für Server und Bots gibt es verständliche Optionen und Voreinstellungen, außerdem eine Serverkonsole und eine Spielerliste mit Kontoverwaltung.
- **Module.** Aktiviere Zusatzfunktionen, öffne ihre Einstellungen oder die GitHub-Seite des jeweiligen Projekts.
- **Mit Freunden spielen.** Erreichbarkeit prüfen, Firewall und UPnP einrichten und Verbindungen über LAN, direkte Adressen oder private Netze/Tailscale vorbereiten. Anleitungen und ein Paket mit Verbindungsdaten helfen deinen Freunden beim Beitritt.
- **Probleme melden.** Bereite einen GitHub-Fehlerbericht mit automatisch eingetragenen Versionsangaben vor.
- **Managerupdates.** Sie werden im Hintergrund geladen und beim Schließen installiert. Deine Server werden dabei weder angehalten noch verändert.
- **Sprachen:** Englisch, Russisch, Deutsch, Französisch, Spanisch und vereinfachtes Chinesisch.
## Screenshots und Anleitungen
| Portable Characters — experimentell | Öffentliche Realms |
|---|---|
| ![Portable Characters](docs/screenshots/de/portable.jpg) | ![Öffentliche Realms](docs/screenshots/de/realms.jpg) |
| Begleiter | Sicherungen |
|---|---|
| ![Begleiter](docs/screenshots/de/bots.jpg) | ![Sicherungen](docs/screenshots/de/backups.jpg) |
[Zur Galerie](docs/de/SCREENSHOTS.md) · [Alle Anleitungen](docs/de/README.md). Die Galerie zeigt auch Einrichtung, Module, Spielclient, Verbindungen mit Freunden und die Übernahme eines vorhandenen Charakters.
## Installation
Lade das Installationsprogramm von der [Release-Seite](https://github.com/Corfirean/coa-server-manager/releases/latest) herunter und starte es. Für den Server brauchst du etwa 10 GB freien Speicher. Der Spielclient benötigt zusätzlich etwa 43 GB: Wähle einen vorhandenen Client oder lade ihn über den Manager.
## Änderungen
[Manager-Changelog](CHANGELOG.md) · [Server-Changelog](https://github.com/Corfirean/coa-server-build/blob/main/CHANGELOG.md). Manager und Server haben getrennte Versionsverläufe. Ein Managerupdate aktualisiert nicht den Server.
## Projektstatus
**In aktiver Entwicklung.** Fehler sind weiterhin möglich. Wenn du ein Problem findest, [erstelle bitte ein Issue](https://github.com/Corfirean/coa-server-manager/issues/new/choose).
### Bekannte Einschränkungen
- Der Ascension-Client 3.3.5 nimmt keine Zugangsdaten über die Kommandozeile an. Gib dein Passwort selbst ein oder verknüpfe ein bestehendes Konto.
- Windows schützt vertrauliche Daten mit DPAPI (`CryptProtectData`) und zusätzlicher Entropie zur Domänentrennung. Linux/macOS verwenden Dateien mit den Zugriffsrechten `0600`.
- Eine bestehende direkte TCP-Verbindung lässt sich nicht während der Sitzung auf einen Relay umstellen. Nach einem Verbindungsabbruch wird beim nächsten Beitritt automatisch auf die Ausweichroute zurückgegriffen.
- Für sichere entfernte Importe portabler Charaktere muss `CharacterDatabase.WorkerThreads = 1` bleiben; das ist der Standardwert.
## Entwicklung
```sh
npm install
cargo test --workspace
npx tsc --noEmit
node tools/check-i18n.mjs
npx vite
cargo build -p coa-server-manager
```
Die Befehle installieren Abhängigkeiten, führen Tests aus, prüfen Typen und Übersetzungen, starten die Browseransicht mit Testdaten und bauen die native Anwendung. Der Debug-Build verwendet `http://localhost:1420`.
Die Programmlogik liegt in `crates/coa-core`, Paket- und Signaturwerkzeuge in `crates/coa-release`, native Befehle in `src-tauri` und die Oberfläche in `src`.
`cargo run -p coa-core --example scan -- <folder>` prüft eine vorhandene Installation nur lesend. Verwende für Start-/Stopp-Tests ausschließlich eine entbehrliche Testkopie: `tools/make-fixture.ps1` erstellt `C:\games\coa-fixture` aus der unveränderten Paketdatenbank mit anderen Ports. Teste niemals an einem genutzten Server. `tests/e2e/cdp.mjs` steuert das echte Fenster über WebView2 mit `WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS=--remote-debugging-port=9222`.
## Lizenz
Der Manager ist freie Software unter der [GNU AGPL v3.0](LICENSE), Kennung `AGPL-3.0-only`.
- Der installierte Server basiert auf einem öffentlichen [AzerothCore-Fork](https://github.com/Corfirean/azerothcore-wotlk-coa). Für von MaNGOS übernommene Teile gilt GPL-2.0-or-later, für eigene AzerothCore-Teile AGPL-3.0. [mod-coa-playerbots](https://github.com/Corfirean/mod-coa-playerbots) steht unter AGPL-3.0. Die exakten Quellstände stehen im Paketmanifest, damit der passende Quellcode auffindbar bleibt.
- Das mitgelieferte MySQL behält seine GPL-2.0-Lizenz; der Lizenztext liegt im Paket unter `Licenses`.
- Die Spieldaten in `Data` (`dbc`, `maps`, `vmaps`, `mmaps`) stammen aus dem Client des eingestellten Ascension-Realms Conquest of Azeroth. Sie fallen **nicht** unter die Lizenz des Managers.
-84
View File
@@ -1,84 +0,0 @@
# CoA Server Manager
[English](README.md) · [Русский](README.ru.md) · [Deutsch](README.de.md) · [Français](README.fr.md) · **Español** · [简体中文](README.zh-CN.md)
**Los personajes portátiles son una función experimental.** Sigue en desarrollo y puede contener errores.
Una aplicación para Windows con la que instalar y gestionar tu propio servidor de **Conquest of Azeroth**, basado en AzerothCore, en pocos pasos. No necesitas usar la consola, editar archivos de configuración a mano ni manejar programas de bases de datos. Creada con Tauri 2, Rust y React.
![Tu servidor de un vistazo](docs/screenshots/es/overview.jpg)
## Funciones
- **Personajes portátiles — experimental.** Guarda personajes y sus distintas versiones en el Manager, o convierte en portátil un personaje que ya tengas en un reino al que puedas acceder. [Ver la guía](docs/es/PORTABLE-CHARACTERS.md).
- **Buscador de reinos.** Compara reinos públicos por modo de juego, nivel máximo, multiplicadores, módulos y población.
- **Instalación sencilla.** Descarga un paquete de servidor firmado, comprueba los archivos, prepara la base de datos y crea tu primera cuenta. Las descargas se pueden reanudar. También puedes importar un servidor existente.
- **Iniciar, detener y jugar.** Controla conjuntamente la base de datos y los servidores de autenticación y mundo. Consulta su estado, tiempo de actividad y jugadores conectados. Al abrir el juego se utiliza la realmlist correcta.
- **Cliente de juego.** Usa el que ya tengas o descárgalo desde el Manager: unos 43 GB, con descarga reanudable y verificación de archivos. Los clientes gestionados reciben avisos de actualización; los archivos que hayas modificado solo se sustituyen con tu permiso.
- **Actualizaciones del servidor.** Se buscan al iniciar y cada cinco minutos. Los paquetes se verifican mediante firmas Ed25519, se crea una copia antes de actualizar, se conservan tus cambios y es posible volver atrás.
- **Copias de seguridad.** Guarda personajes, cuentas y ajustes cuando quieras o automáticamente antes de una actualización. Comprueba y restaura las copias desde la aplicación.
- **CoA, Wildcard y Warcraft Reborn.** Elige el reino en Resumen. La versión del servidor debe admitir el modo seleccionado. El primer cambio crea un mundo independiente y una base de personajes vacía. Las cuentas son compartidas; los personajes y los ajustes de módulos se mantienen separados. Si el servidor está encendido, guarda los personajes y se reinicia al cambiar. Cierra el cliente antes del cambio; si está abierto, el nuevo reino se aplicará la próxima vez que lo abras desde el Manager. No hay bots en Wildcard ni en Warcraft Reborn; los demás módulos opcionales son experimentales allí. Las copias y las actualizaciones cubren todos los reinos creados. CoA y Wildcard pueden funcionar a la vez. [Wildcard](docs/es/WILDCARD.md) · [Warcraft Reborn](docs/es/WARCRAFT-REBORN.md).
- **Bots compañeros.** Llena el mundo con bots de nivel adecuado, sigue su creación, ponla en pausa o desconecta los bots. Elimina una cantidad concreta para reducir la carga y decide cuántos se conectan al iniciar el servidor.
- **Cambio de realmlist.** Guarda conexiones con nombres como Solo o PTR y selecciónalas junto al botón de jugar. El archivo anterior se guarda antes de sustituirlo.
- **Cuentas y ajustes.** Gestiona nombres, contraseñas y permisos. Configura el servidor y los bots con opciones explicadas y ajustes predefinidos. También tienes una consola de servidor y una lista de jugadores con herramientas de cuentas.
- **Módulos.** Activa funciones adicionales, cambia sus ajustes o abre el repositorio de sus autores desde la misma página.
- **Jugar con amigos.** Comprueba si pueden acceder, configura el cortafuegos y UPnP, y prepara conexiones por LAN, dirección directa o red privada/Tailscale. Incluye guías y un paquete con los datos de conexión para compartir.
- **Informar de problemas.** Prepara un informe para GitHub con las versiones ya rellenadas.
- **Actualizaciones del Manager.** Se descargan en segundo plano y se instalan al cerrar la aplicación. No detienen ni modifican tus servidores.
- **Idiomas:** inglés, ruso, alemán, francés, español y chino simplificado.
## Capturas y guías
| Personajes portátiles — experimental | Reinos públicos |
|---|---|
| ![Personajes portátiles](docs/screenshots/es/portable.jpg) | ![Reinos públicos](docs/screenshots/es/realms.jpg) |
| Compañeros | Copias de seguridad |
|---|---|
| ![Compañeros](docs/screenshots/es/bots.jpg) | ![Copias de seguridad](docs/screenshots/es/backups.jpg) |
[Galería completa](docs/es/SCREENSHOTS.md) · [Todas las guías](docs/es/README.md). También encontrarás la instalación, los módulos, el cliente, las conexiones con amigos y cómo convertir un personaje existente en portátil.
## Instalación
Descarga el instalador desde la [página de versiones](https://github.com/Corfirean/coa-server-manager/releases/latest) y ejecútalo. Necesitas unos 10 GB libres para el servidor. El cliente se instala por separado y ocupa unos 43 GB: indica tu carpeta existente o descárgalo con el Manager.
## Historial de cambios
[Cambios del Manager](CHANGELOG.md) · [Cambios del servidor](https://github.com/Corfirean/coa-server-build/blob/main/CHANGELOG.md). Sus versiones se siguen por separado. Actualizar el Manager no actualiza el servidor.
## Estado del proyecto
**En desarrollo activo.** Todavía puede haber errores. Si encuentras un problema, [abre una incidencia](https://github.com/Corfirean/coa-server-manager/issues/new/choose).
### Limitaciones conocidas
- El cliente Ascension 3.3.5 no acepta credenciales por línea de comandos. Introduce la contraseña manualmente o vincula una cuenta existente.
- En Windows, los secretos se protegen con DPAPI (`CryptProtectData`) y entropía para separar dominios. Linux/macOS usan archivos con permisos `0600`.
- Una conexión TCP directa ya establecida no puede pasar a un relé a mitad de sesión. Tras una interrupción, la ruta alternativa se selecciona automáticamente en la siguiente conexión.
- Para importar personajes portátiles de forma remota con seguridad, mantén `CharacterDatabase.WorkerThreads = 1`, su valor predeterminado.
## Desarrollo
```sh
npm install
cargo test --workspace
npx tsc --noEmit
node tools/check-i18n.mjs
npx vite
cargo build -p coa-server-manager
```
Estos comandos instalan dependencias, ejecutan pruebas, comprueban tipos y traducciones, abren la interfaz en el navegador con datos de prueba y compilan la aplicación nativa. La versión de depuración utiliza `http://localhost:1420`.
La lógica está en `crates/coa-core`, las herramientas de empaquetado y firma en `crates/coa-release`, los comandos nativos en `src-tauri` y la interfaz en `src`.
`cargo run -p coa-core --example scan -- <folder>` inspecciona una instalación sin modificarla. Para probar el inicio y la parada, usa solo una copia desechable: `tools/make-fixture.ps1` crea `C:\games\coa-fixture` a partir de la base intacta del paquete y con puertos diferentes. No hagas estas pruebas en un servidor en uso. `tests/e2e/cdp.mjs` controla la ventana real mediante WebView2 con `WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS=--remote-debugging-port=9222`.
## Licencia
El Manager es software libre bajo [GNU AGPL v3.0](LICENSE), identificador `AGPL-3.0-only`.
- El servidor instalado procede de un [fork público de AzerothCore](https://github.com/Corfirean/azerothcore-wotlk-coa). Las partes heredadas de MaNGOS usan GPL-2.0-or-later y las propias de AzerothCore, AGPL-3.0. [mod-coa-playerbots](https://github.com/Corfirean/mod-coa-playerbots) utiliza AGPL-3.0. El manifiesto de cada paquete indica los commits exactos para localizar el código fuente correspondiente.
- MySQL conserva su licencia GPL-2.0; el texto se incluye en la carpeta `Licenses` del paquete.
- Los datos de juego de `Data` (`dbc`, `maps`, `vmaps`, `mmaps`) se extrajeron del cliente del antiguo reino Ascension Conquest of Azeroth. **No** están cubiertos por la licencia del Manager.
-84
View File
@@ -1,84 +0,0 @@
# CoA Server Manager
[English](README.md) · [Русский](README.ru.md) · [Deutsch](README.de.md) · **Français** · [Español](README.es.md) · [简体中文](README.zh-CN.md)
**Les personnages portables sont une fonctionnalité expérimentale.** Elle est encore en développement et peut présenter des bugs.
Une application Windows pour installer et gérer votre propre serveur **Conquest of Azeroth**, basé sur AzerothCore, en quelques étapes. Pas besoin de console, de modifier les fichiers de configuration à la main ou d'utiliser un outil de base de données. L'application utilise Tauri 2, Rust et React.
![Votre serveur en un coup d'œil](docs/screenshots/fr/overview.jpg)
## Fonctionnalités
- **Personnages portables — expérimental.** Conservez vos personnages et leurs sauvegardes dans le Manager, ou rendez portable un personnage déjà présent sur un royaume auquel vous avez accès. [Voir le guide](docs/fr/PORTABLE-CHARACTERS.md).
- **Découverte des royaumes.** Comparez les royaumes publics selon leur mode de jeu, niveau maximal, taux de progression, modules et population.
- **Installation simplifiée.** Le Manager télécharge un paquet serveur signé, vérifie les fichiers, configure la base de données et crée votre premier compte. Les téléchargements peuvent reprendre après une interruption. Vous pouvez aussi importer un serveur existant.
- **Démarrer, arrêter, jouer.** Une commande suffit pour gérer la base de données et les serveurs d'authentification et de monde. L'état, la durée de fonctionnement et les joueurs connectés restent visibles. Le lancement du jeu utilise la bonne realmlist.
- **Gestion du client de jeu.** Utilisez votre client ou téléchargez-le depuis l'application : environ 43 Go, avec reprise et vérification des fichiers. Un client géré reçoit des mises à jour ; vos fichiers modifiés ne sont remplacés qu'avec votre accord.
- **Mises à jour du serveur.** Recherche au démarrage et toutes les cinq minutes, vérification des signatures Ed25519, sauvegarde préalable, conservation des modifications personnelles et possibilité de revenir en arrière.
- **Sauvegardes.** Enregistrez personnages, comptes et paramètres à la demande ou automatiquement avant les mises à jour. Vérifiez et restaurez les sauvegardes dans l'application.
- **CoA, Wildcard et Warcraft Reborn.** Choisissez le royaume dans Vue d'ensemble. La version du serveur doit prendre en charge le mode choisi. Le premier changement crée un monde distinct et une base de personnages vide. Les comptes sont partagés, mais personnages et réglages des modules restent séparés. Un serveur en cours d'exécution sauvegarde les personnages puis redémarre lors du changement. Fermez le client avant de changer de royaume ; s'il est ouvert, le choix prendra effet au prochain lancement depuis le Manager. Les bots sont indisponibles sur Wildcard et Warcraft Reborn ; les autres modules optionnels y sont expérimentaux. Sauvegardes et mises à jour couvrent tous les royaumes créés. CoA et Wildcard peuvent fonctionner ensemble. [Wildcard](docs/fr/WILDCARD.md) · [Warcraft Reborn](docs/fr/WARCRAFT-REBORN.md).
- **Bots compagnons.** Peuplez le monde avec des bots de niveau adapté, suivez leur création, mettez-la en pause ou déconnectez les bots. Retirez un nombre choisi de bots pour alléger le serveur et réglez combien se connectent au démarrage.
- **Changement de realmlist.** Enregistrez des connexions nommées, comme Solo et PTR, et choisissez-les à côté du bouton de jeu. Le fichier précédent est sauvegardé avant remplacement.
- **Comptes et réglages.** Gérez noms, mots de passe et droits d'accès. Configurez serveur et bots avec des options expliquées et des préréglages. Une console serveur et une liste des joueurs avec gestion des comptes sont également disponibles.
- **Modules.** Activez les fonctions supplémentaires, modifiez leurs réglages ou consultez leur projet GitHub depuis une même page.
- **Jouer avec des amis.** Vérifiez l'accessibilité du serveur, configurez pare-feu et UPnP, préparez une connexion en réseau local, directe ou via un réseau privé/Tailscale. Des guides et un paquet de connexion facilitent l'arrivée des amis.
- **Signalement des problèmes.** Préparez un rapport GitHub avec les versions déjà renseignées.
- **Mises à jour du Manager.** Téléchargées en arrière-plan, elles s'installent à la fermeture. Elles n'arrêtent pas vos serveurs et ne les modifient pas.
- **Langues :** anglais, russe, allemand, français, espagnol et chinois simplifié.
## Captures et guides
| Personnages portables — expérimental | Royaumes publics |
|---|---|
| ![Personnages portables](docs/screenshots/fr/portable.jpg) | ![Royaumes publics](docs/screenshots/fr/realms.jpg) |
| Compagnons | Sauvegardes |
|---|---|
| ![Compagnons](docs/screenshots/fr/bots.jpg) | ![Sauvegardes](docs/screenshots/fr/backups.jpg) |
[Galerie complète](docs/fr/SCREENSHOTS.md) · [Tous les guides](docs/fr/README.md). La galerie présente aussi l'installation, les modules, le client, les connexions entre amis et la création d'un personnage portable.
## Installation
Téléchargez et lancez l'installateur depuis les [publications GitHub](https://github.com/Corfirean/coa-server-manager/releases/latest). Prévoyez environ 10 Go libres pour le serveur. Le client de jeu est séparé et demande environ 43 Go : indiquez un dossier existant ou téléchargez-le avec le Manager.
## Historique des versions
[Changelog du Manager](CHANGELOG.md) · [Changelog du serveur](https://github.com/Corfirean/coa-server-build/blob/main/CHANGELOG.md). Leurs versions sont suivies séparément : mettre à jour le Manager ne met pas à jour le serveur.
## État du projet
**En développement actif.** Des bugs restent possibles. Si vous rencontrez un problème, [ouvrez une issue](https://github.com/Corfirean/coa-server-manager/issues/new/choose).
### Limites connues
- Le client Ascension 3.3.5 n'accepte pas les identifiants en ligne de commande. Saisissez votre mot de passe ou associez un compte existant.
- Windows protège les secrets avec DPAPI (`CryptProtectData`) et une entropie de séparation de domaine. Sous Linux/macOS, ils sont conservés dans des fichiers aux permissions `0600`.
- Une connexion TCP directe déjà établie ne peut pas basculer vers un relais en cours de session. Après une coupure, le repli automatique intervient à la connexion suivante.
- Pour importer à distance des personnages portables en sécurité, conservez `CharacterDatabase.WorkerThreads = 1`, la valeur par défaut.
## Développement
```sh
npm install
cargo test --workspace
npx tsc --noEmit
node tools/check-i18n.mjs
npx vite
cargo build -p coa-server-manager
```
Ces commandes installent les dépendances, exécutent les tests, contrôlent les types et les traductions, ouvrent l'interface dans le navigateur avec des données de test, puis compilent l'application native. En mode debug, celle-ci utilise `http://localhost:1420`.
La logique se trouve dans `crates/coa-core`, les outils de paquetage et de signature dans `crates/coa-release`, les commandes natives dans `src-tauri` et l'interface dans `src`.
`cargo run -p coa-core --example scan -- <folder>` inspecte une installation sans la modifier. Pour tester démarrage et arrêt, utilisez uniquement une copie jetable : `tools/make-fixture.ps1` crée `C:\games\coa-fixture` depuis la base intacte du paquet, avec des ports distincts. Ne testez jamais sur un serveur utilisé par des joueurs. `tests/e2e/cdp.mjs` pilote la véritable fenêtre via WebView2 avec `WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS=--remote-debugging-port=9222`.
## Licence
Le Manager est un logiciel libre sous [GNU AGPL v3.0](LICENSE), identifiant `AGPL-3.0-only`.
- Le serveur installé provient d'un [fork public d'AzerothCore](https://github.com/Corfirean/azerothcore-wotlk-coa). Les parties héritées de MaNGOS relèvent de GPL-2.0-or-later et les parties propres à AzerothCore d'AGPL-3.0. [mod-coa-playerbots](https://github.com/Corfirean/mod-coa-playerbots) utilise AGPL-3.0. Les commits exacts figurent dans le manifeste de chaque paquet pour retrouver les sources correspondantes.
- MySQL conserve sa licence GPL-2.0 ; son texte est fourni dans le dossier `Licenses` du paquet.
- Les données de jeu dans `Data` (`dbc`, `maps`, `vmaps`, `mmaps`) proviennent du client de l'ancien royaume Ascension Conquest of Azeroth. Elles ne sont **pas** couvertes par la licence du Manager.
-2
View File
@@ -1,7 +1,5 @@
# CoA Server Manager
**English** · [Русский](README.ru.md) · [Deutsch](README.de.md) · [Français](README.fr.md) · [Español](README.es.md) · [简体中文](README.zh-CN.md)
**Portable characters are experimental.** This feature is in active development and may contain bugs.
A Windows app that installs and runs your own **Conquest of Azeroth** server (AzerothCore) with a few clicks:
-84
View File
@@ -1,84 +0,0 @@
# CoA Server Manager
[English](README.md) · **Русский** · [Deutsch](README.de.md) · [Français](README.fr.md) · [Español](README.es.md) · [简体中文](README.zh-CN.md)
**Переносимые персонажи — экспериментальная функция.** Она ещё развивается и может работать с ошибками.
Приложение для Windows, с которым можно установить и запустить свой сервер **Conquest of Azeroth** на базе AzerothCore за несколько шагов. Управляйте сервером через интерфейс, без консоли, ручного редактирования конфигов и отдельных программ для базы данных. Менеджер написан на Tauri 2, Rust и React.
![Главное окно менеджера](docs/screenshots/ru/overview.jpg)
## Возможности
- **Переносимые персонажи — экспериментально.** Храните персонажей и историю сохранений в менеджере, делайте переносимыми уже существующих персонажей с доступных вам реалмов. [Как это работает](docs/ru/PORTABLE-CHARACTERS.md).
- **Каталог реалмов.** Сравнивайте публичные серверы по режиму игры, максимальному уровню, рейтам, модулям и числу игроков.
- **Простая установка.** Менеджер скачивает подписанный пакет сервера, проверяет файлы, настраивает базу данных и создаёт первый аккаунт. Прерванную загрузку можно продолжить. Можно также подключить уже установленный сервер.
- **Запуск, остановка и игра.** Управляйте базой данных и обоими серверными процессами одной кнопкой. На главном экране видны состояние, время работы и игроки онлайн. Кнопка запуска игры выбирает нужный realmlist.
- **Игровой клиент.** Подключите свой клиент или скачайте его через менеджер — около 43 ГБ, с продолжением загрузки и проверкой файлов. Для управляемого клиента доступны обновления; ваши изменения заменяются только с вашего согласия.
- **Обновления сервера.** Проверка выполняется при запуске и каждые пять минут. Пакеты защищены подписью Ed25519; перед установкой создаётся резервная копия. Пользовательские изменения сохраняются, предусмотрен откат.
- **Резервные копии.** Сохраняйте персонажей, аккаунты и настройки вручную или автоматически перед обновлениями. Проверка и восстановление доступны в приложении.
- **CoA, Wildcard и Warcraft Reborn.** Выбирайте реалм в разделе «Обзор». Нужна серверная сборка с поддержкой выбранного режима. При первом переключении создаются отдельный мир и пустая база персонажей. Аккаунты общие, персонажи и настройки модулей раздельные. Переключение работающего сервера сохраняет персонажей и перезапускает его. Закройте клиент перед переключением; если он открыт, новый реалм будет выбран при следующем запуске через менеджер. Боты недоступны в Wildcard и Warcraft Reborn, остальные дополнительные модули там экспериментальны. Копии и обновления охватывают все созданные реалмы. Одновременно можно запускать CoA и Wildcard. [Гайд по Wildcard](docs/ru/WILDCARD.md) · [Warcraft Reborn](docs/ru/WARCRAFT-REBORN.md).
- **Компаньоны-боты.** Заселяйте мир ботами подходящего уровня, следите за созданием, приостанавливайте его, отключайте ботов или удаляйте нужное количество для снижения нагрузки. Можно задать число ботов при старте сервера.
- **Список подключений.** Сохраняйте несколько realmlist с понятными названиями, например Solo и PTR, и переключайте их рядом с кнопкой игры. Предыдущий файл сохраняется.
- **Аккаунты и настройки.** Управляйте именами, паролями и уровнями доступа. Настраивайте сервер и ботов через понятные параметры и готовые наборы; доступны консоль сервера и список игроков.
- **Модули.** Включайте дополнительные возможности, меняйте их настройки и переходите в репозитории авторов с одной страницы.
- **Игра с друзьями.** Проверка доступности, настройка брандмауэра и UPnP, подключение по локальной сети, напрямую или через частную сеть/Tailscale. Внутри есть пошаговые инструкции и пакет с данными подключения для друзей.
- **Сообщения об ошибках.** Менеджер помогает подготовить issue на GitHub и подставляет версии программ.
- **Обновление менеджера.** Загружается в фоне и устанавливается при закрытии приложения. Ваши серверы при этом не останавливаются и не изменяются.
- **Языки:** английский, русский, немецкий, французский, испанский и упрощённый китайский.
## Скриншоты и гайды
| Переносимые персонажи — экспериментально | Публичные реалмы |
|---|---|
| ![Переносимые персонажи](docs/screenshots/ru/portable.jpg) | ![Публичные реалмы](docs/screenshots/ru/realms.jpg) |
| Компаньоны | Резервные копии |
|---|---|
| ![Компаньоны](docs/screenshots/ru/bots.jpg) | ![Резервные копии](docs/screenshots/ru/backups.jpg) |
[Все скриншоты](docs/ru/SCREENSHOTS.md) · [Гайды для игроков и владельцев серверов](docs/ru/README.md). В галерее также показаны установка, модули, клиент, подключение друзей и создание переносимого персонажа.
## Установка
Скачайте установщик со страницы [релизов](https://github.com/Corfirean/coa-server-manager/releases/latest) и запустите его. Для сервера нужно около 10 ГБ свободного места. Клиент устанавливается отдельно и занимает около 43 ГБ: укажите существующую папку или скачайте его через менеджер.
## Что изменилось
[Ченджлог менеджера](CHANGELOG.md) · [Ченджлог сервера](https://github.com/Corfirean/coa-server-build/blob/main/CHANGELOG.md). Это отдельные продукты с отдельной историей версий: обновление менеджера не обновляет сервер.
## Состояние проекта
**Проект активно развивается.** Ошибки ещё возможны. Если встретили проблему, [создайте issue](https://github.com/Corfirean/coa-server-manager/issues/new/choose).
### Известные ограничения
- Клиент Ascension 3.3.5 не принимает логин и пароль через командную строку. Введите пароль вручную или привяжите существующий аккаунт.
- В Windows секреты защищены DPAPI (`CryptProtectData`) с отдельной энтропией домена. На Linux/macOS используются файлы с правами `0600`.
- Уже открытое прямое TCP-соединение нельзя переключить на ретранслятор без разрыва. Резервный маршрут выбирается при следующем подключении.
- Для безопасного удалённого импорта переносимых персонажей оставьте `CharacterDatabase.WorkerThreads = 1` — это значение по умолчанию.
## Разработка
```sh
npm install
cargo test --workspace
npx tsc --noEmit
node tools/check-i18n.mjs
npx vite
cargo build -p coa-server-manager
```
Команды устанавливают зависимости, запускают тесты, проверяют типы и переводы, открывают браузерный интерфейс с тестовыми данными и собирают нативное приложение. В отладочном режиме оно использует `http://localhost:1420`.
`crates/coa-core` содержит основную логику, `crates/coa-release` — упаковку и подписи, `src-tauri` — команды приложения, `src` — интерфейс.
Проверить существующую сборку без изменений можно командой `cargo run -p coa-core --example scan -- <folder>`. Для проверок запуска и остановки используйте только отдельную тестовую копию: `tools/make-fixture.ps1` создаёт `C:\games\coa-fixture` из чистой базы пакета, с другими портами. Не проводите такие проверки на сервере, которым пользуются игроки. `tests/e2e/cdp.mjs` управляет настоящим окном через WebView2 с `WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS=--remote-debugging-port=9222`.
## Лицензия
Менеджер — свободное ПО под [GNU AGPL v3.0](LICENSE), идентификатор `AGPL-3.0-only`.
- Устанавливаемый сервер основан на [форке AzerothCore](https://github.com/Corfirean/azerothcore-wotlk-coa): части, унаследованные от MaNGOS, используют GPL-2.0-or-later, собственные части AzerothCore — AGPL-3.0. Модуль [mod-coa-playerbots](https://github.com/Corfirean/mod-coa-playerbots) использует AGPL-3.0. Точные коммиты записываются в манифест пакета, чтобы можно было найти соответствующий исходный код.
- MySQL распространяется по собственной лицензии GPL-2.0; её текст находится в папке `Licenses` пакета.
- Данные игры в `Data` (`dbc`, `maps`, `vmaps`, `mmaps`) извлечены из клиента закрытого реалма Ascension Conquest of Azeroth. Лицензия менеджера на них **не распространяется**.
-84
View File
@@ -1,84 +0,0 @@
# CoA Server Manager
[English](README.md) · [Русский](README.ru.md) · [Deutsch](README.de.md) · [Français](README.fr.md) · [Español](README.es.md) · **简体中文**
**便携角色是一项实验性功能。** 目前仍在开发中,使用时可能遇到问题。
这是一款 Windows 应用,帮助你用几个简单步骤搭建和管理自己的 **Conquest of Azeroth** 服务器,服务端基于 AzerothCore。日常操作不需要使用控制台、手动修改配置文件或单独操作数据库。应用采用 Tauri 2、Rust 和 React 开发。
![服务器概览](docs/screenshots/zh-CN/overview.jpg)
## 主要功能
- **便携角色(实验性)。** 在管理器中保存角色及其历史存档,也可以将有权访问的服务器上的现有角色转换为便携角色。[查看使用指南](docs/zh-CN/PORTABLE-CHARACTERS.md)。
- **查找服务器。** 浏览公开服务器,对比游戏模式、等级上限、倍率、模块和在线人数。
- **轻松安装。** 下载带签名的服务端安装包,逐一校验文件,配置数据库并创建首个账号。下载支持断点续传,也可以导入已有服务器。
- **启动、停止和进入游戏。** 一处控制数据库、认证服务和世界服务,随时查看运行状态、运行时间和在线玩家。启动游戏时会自动使用对应的 realmlist。
- **管理游戏客户端。** 指定现有客户端,或通过管理器下载约 43 GB 的客户端。下载可以续传,文件会经过校验。受管理的客户端可以检查更新;自行修改的文件只有在你同意后才会被替换。
- **更新服务器。** 应用启动时及之后每五分钟检查一次更新。安装包通过 Ed25519 签名验证,更新前自动备份,保留用户修改,并支持回滚。
- **备份与恢复。** 手动备份角色、账号和设置,或在更新前自动备份。在应用中即可校验和恢复。
- **CoA、Wildcard 和 Warcraft Reborn。** 在概览中选择服务器模式,服务端版本必须支持所选模式。首次切换会创建独立的世界数据库和空的角色数据库。各模式共用账号,角色和模块设置相互独立。运行中切换会先保存角色,再重启服务器。切换前请关闭客户端;如果客户端仍开着,新选择会在下次通过管理器启动游戏时生效。Wildcard 和 Warcraft Reborn 不支持机器人,其他可选模块在这两种模式下也属于实验性支持。备份和数据库更新涵盖所有已创建的模式。目前支持 CoA 与 Wildcard 同时运行。[Wildcard 指南](docs/zh-CN/WILDCARD.md) · [Warcraft Reborn 指南](docs/zh-CN/WARCRAFT-REBORN.md)。
- **伙伴机器人。** 创建等级合适的机器人并查看进度,暂停创建、让机器人下线,或移除指定数量以减轻服务器负担。也可以设置开服时登录的机器人数量。
- **切换 realmlist。** 为不同连接保存名称,例如 Solo 和 PTR,在进入游戏按钮旁直接切换。替换前会保存原文件。
- **账号和设置。** 管理账号名称、密码和权限,通过说明清楚的选项及预设调整服务器和机器人。还提供世界服务器控制台,以及带账号管理功能的玩家列表。
- **模块管理。** 在同一页面启用可选功能、调整设置,或打开相应项目的 GitHub 页面。
- **好友联机。** 检查服务器是否可达,配置防火墙和 UPnP,支持局域网、直接连接及私有网络/Tailscale。应用提供分步说明,还能准备可分享的连接资料包。
- **报告问题。** 帮你准备 GitHub 问题报告,并自动填写版本信息。
- **管理器自身更新。** 在后台下载,关闭应用时安装。更新管理器不会停止或修改你的服务器。
- **支持语言:** 英语、俄语、德语、法语、西班牙语和简体中文。
## 截图与指南
| 便携角色(实验性) | 公开服务器 |
|---|---|
| ![便携角色](docs/screenshots/zh-CN/portable.jpg) | ![公开服务器](docs/screenshots/zh-CN/realms.jpg) |
| 伙伴机器人 | 备份 |
|---|---|
| ![伙伴机器人](docs/screenshots/zh-CN/bots.jpg) | ![备份](docs/screenshots/zh-CN/backups.jpg) |
[查看完整截图](docs/zh-CN/SCREENSHOTS.md) · [玩家与服主指南](docs/zh-CN/README.md)。图库还展示了初始设置、模块、客户端、朋友联机,以及将现有角色转换为便携角色的流程。
## 安装
从 [GitHub 发布页](https://github.com/Corfirean/coa-server-manager/releases/latest)下载安装程序并运行。服务器约需 10 GB 可用空间。游戏客户端单独安装,约占 43 GB;你可以指定已有客户端目录,也可以交给管理器下载。
## 更新记录
[管理器更新记录](CHANGELOG.md) · [服务器更新记录](https://github.com/Corfirean/coa-server-build/blob/main/CHANGELOG.md)。两者的版本和更新记录分别维护。更新管理器不会同时更新服务器。
## 项目状态
**正在积极开发中。** 仍可能存在问题。如果遇到故障,请[提交 issue](https://github.com/Corfirean/coa-server-manager/issues/new/choose)。
### 已知限制
- Ascension 3.3.5 客户端不支持通过命令行传入账号和密码。请自行输入密码,或关联现有账号。
- Windows 使用 DPAPI(`CryptProtectData`)及用于域隔离的额外熵来保护机密数据。Linux/macOS 使用权限为 `0600` 的文件。
- 已建立的直连 TCP 会话无法在不中断连接的情况下切换至中继。连接中断后,会在下一次加入服务器时自动尝试备用路径。
- 为保证远程导入便携角色的安全,请保留默认设置 `CharacterDatabase.WorkerThreads = 1`。
## 开发
```sh
npm install
cargo test --workspace
npx tsc --noEmit
node tools/check-i18n.mjs
npx vite
cargo build -p coa-server-manager
```
以上命令依次安装依赖、运行测试、检查类型与翻译、启动使用模拟数据的浏览器界面,以及编译原生应用。调试版应用连接 `http://localhost:1420`。
`crates/coa-core` 存放核心逻辑,`crates/coa-release` 提供打包和签名工具,`src-tauri` 处理原生命令,`src` 存放界面代码。
`cargo run -p coa-core --example scan -- <folder>` 可以只读检查现有安装。启动和停止测试必须使用可丢弃的独立副本:`tools/make-fixture.ps1` 会从安装包的原始数据库创建 `C:\games\coa-fixture`,并使用不同端口。不要在正在供玩家使用的服务器上进行此类测试。`tests/e2e/cdp.mjs` 可通过 WebView2 控制真实窗口,需设置 `WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS=--remote-debugging-port=9222`。
## 许可
管理器是自由软件,采用 [GNU AGPL v3.0](LICENSE),标识为 `AGPL-3.0-only`。
- 所安装的服务器来自公开的 [AzerothCore 分支](https://github.com/Corfirean/azerothcore-wotlk-coa)。继承自 MaNGOS 的部分采用 GPL-2.0-or-later,AzerothCore 自有部分采用 AGPL-3.0。[mod-coa-playerbots](https://github.com/Corfirean/mod-coa-playerbots) 采用 AGPL-3.0。每个安装包的清单都记录了准确的提交版本,便于查找对应源码。
- 随附的 MySQL 保留其 GPL-2.0 许可,许可文本位于安装包的 `Licenses` 目录。
- `Data` 中的游戏数据(`dbc`、`maps`、`vmaps`、`mmaps`)提取自已关闭的 Ascension Conquest of Azeroth 服务器客户端,**不属于**管理器许可的授权范围。
+56
View File
@@ -1,5 +1,39 @@
# TODO
## Подготовка 0.9.8, 2026-10-31
- Подготовлены исходники `C:/games/source/per-race-manager`, ветка `fix/launcher-validation-candidate-20261031`: изоляция bot configs на время проверки с точным восстановлением, повторное использование MySQL внутри validation, зависимость Dungeon Clear от SQUID, три режима логов и экспорт этапов launcher/control owner.
- Workspace: 840 тестов прошли, 60 ignored; последующие focused diagnostics: 11 прошли. Переводы новых заметок и UI подготовлены, web build/i18n/bridge/history checks прошли. Подробности и ограничения: `C:/games/source/candidate-preparation-20261031.md`.
- Не выпускать Manager до кандидата сервера. Installer ещё не собирался и не публиковался; подготовка источников не равна готовому кандидату.
## Приоритет: проверка установки и обновления (2026-10-31)
- **Локальные замеры массовых Companions (2026-10-31):** отчёт `C:/games/source/companions-benchmark-20261031/REPORT.md`, сырые выборки/qualification в той же папке. Native worldserver SHA `bd9f65ac7543fad8159231000d5ef6436a159aa009b65cbdc9541a0e9fe1ee7b`, Ryzen 7 7700X/32 GiB, `MapUpdate.Threads=1`, все CPU доступны. Перед условиями восстанавливался один снимок персонажей. Без записи логов медианы среднего тика: 0 ботов 4.5 ms; 500 — 39 ms; 1000 — 91 ms; 2000 — 246 ms, поздний замер 259 ms. С обычными логами: 500 — 43.5 ms; 1000 — 111 ms. Запуск 2000 с логами дал 1381 ms, последующий полный Logger-off 363 ms, но нагрузка хоста менялась; чистый множитель логирования этими числами не доказан. Всего 9 условий с подтверждённым online; исходная база 21 шаблон/0 тестовых аккаунтов восстановлена, тестовые процессы остановлены. Повтор 2000 с логами подготовлен, но НЕ выполнен: на C: осталось около 300 MiB. Соответствующий PDB для функционального профиля отсутствует.
- [ ] **Разобрать штатное завершение мира под большой популяцией**:
- В локальном бенчмарке ряд запусков (включая 2000 ботов и полностью отключённые логгеры) не завершились за 90 секунд после `server shutdown 1s 0`; пришлось завершать только тестовый процесс после сохранения измерений. Стек `2000-shutdown-stacks.txt` показывает ожидание `MSVCP140!Thrd_join`, точный ожидаемый поток без matching PDB не установлен. Не объявлять это доказанной причиной пользовательского control.lock или влиянием только логов.
- [ ] **Разобрать удержание control.lock после видимого запуска сервера**:
- Пользователь после hotfix v3 получил `Another start/stop action is in progress` при внешнем `with launcher["control_lock"]()`, хотя мир отвечал и Manager показывал работающий сервер. Не считать это доказательством «зависшего файла»: Windows блокирует диапазон живым дескриптором.
- На Python 3.14.7 точно воспроизведён конкурентный захват: второй лаунчер получает эту ошибку, после выхода владельца захват снова проходит. Причина долгого удержания у пользователя пока не установлена; нужны его свежие launch diagnostics.
- Добавить безопасную диагностику владельца (PID, время создания, действие, этап ожидания) и проверить сериализацию Start/Stop/Restart/validation/recovery. Различать реальную занятость и прочие OSError захвата, которые сейчас маскируются одним сообщением. Не удалять lock и не завершать чужие процессы ради обхода.
- **Проверка с ботами завершена (2026-10-31):** пользователь показал работающие MySQL/auth/world, 2000 Companions онлайн и вход своим клиентом в мир после обновления. Это подтверждает обычный запуск с ботами после hotfix, но не пригодность массового автологина для validation. Ранний снимок показывает около 11 тиков/с на 2m32s работы; результат замера после прогрева пока неизвестен.
- **Пользовательская проверка (2026-10-31):** после hotfix лаунчера v3 и отключения автологина Companions обновление завершилось успешно (server `0.261030.90`, Manager `0.9.7`). Отдельная проверка с включёнными ботами пока не завершена.
- [ ] **Сократить повторные запуски MySQL в установке/обновлении**:
- Пользователь после успешного обновления отметил большую длительность и многократные старты/остановки базы, в том числе на 85%. Проследить фактическую последовательность snapshot/SQL/schema/validation/recovery и повторно использовать уже запущенную, проверенную базу между совместимыми этапами.
- Не убирать остановки, необходимые для согласованного backup/restore, замены файлов и восстановления после отказа. Сохранить гарантии rollback и владения процессами. Записать число стартов/остановок и длительность этапов до/после; проверить обновление без ботов и восстановление после ошибки.
- [ ] **Временный конфиг проверки без массового запуска ботов**:
- Запрос владельца: грузить 2000 ботов ради проверки установки/обновления недопустимо. Облегчить все проверочные запуски, включая восстановление/повторную проверку, где применяется тот же путь запуска.
- Факты случая: этап обновления 85%, CoA Companions поставили в очередь 2000 ботов; пользователь сообщает об остановке продвижения на 519 за 6 минут. Логи показывают 518 уникальных имён в `ACTIVE_LIST`. Это не SQUID. Место зависания и причинная связь с автологином пока не установлены.
- Перед проверочным запуском временно отключать `CoaBots.AutoLoginOnStartup` и проверить другие пути автоматического входа/создания/заселения Companions, включая `CoaBots.RandomSpawn.AutoLogin`. Аналогично подавлять автоматическое заселение SQUID, если выбран этот модуль. Не подменять пользовательский выбор системы ботов и не отключать модуль целиком вместо проверки его инициализации.
- Сохранять исходные байты/отсутствие изменяемых конфигов в журнале восстановления; вернуть их до обычного запуска как при успехе, так и при ошибке, отмене, rollback и восстановлении после прерывания Manager. Не оставлять автологин выключенным пользователю. Проверить primary и дополнительные realms.
- Проверка должна подтверждать инициализацию ядра/выбранных модулей, SQL/schema, сервисы и отклик управляющего интерфейса; не ждать заполнения мира ботами и не создавать для этого тысячи персонажей. Вне validation обычный запуск сохраняет поведение пользовательских настроек.
- Проверить сценарии с Companions и лимитом 2000, SQUID, выключенными ботами; успех, отказ запуска, прерывание и восстановление исходных конфигов. Добавить регрессионные проверки и changelog после реализации.
- [ ] **Доставить исправление `manage.py` для PID 0 в согласованном серверном обновлении**:
- Серверная задача и готовый локальный hotfix описаны в `C:/games/coa-server-build/TODO.md`. Проверить импортируемый запуск через `runpy`/внешний вызов `main()` и штатный Manager update; диагностика должна работать при обоих способах загрузки.
## UI / UX
- [x] **Предупреждение о несохранённых изменениях при переходе между вкладками (Unsaved Changes Guard / Modal)**:
- Если у пользователя есть несохранённые изменения в настройках (`ModulesPage`, `SettingsPage` — сервер, боты и др.) и он переходит на другую вкладку (в боковом меню `Shell.tsx` или кнопками навигации), показывать pop-up диалог подтверждения.
@@ -27,3 +61,25 @@
4. Анализировать последние строки `Core/Logs/Server.log` и `Errors.log` на критические маркеры (потеря соединения с MySQL, нехватка RAM/OOM, ошибка бинда портов).
5. Проверять по встроенному словарю известных сигнатур (паттерны частых крашей с понятным описанием, например: «Сбой удаления объекта из сетки карты», «Ошибка запроса к базе данных», «Нехватка оперативной памяти»).
- *Fallback:* Если сигнатура не опознана в словаре известных проблем, показывать краткую техническую выжимку (код исключения + сработавший ассерт или вершина Call Stack) и кнопку разворота полного текста крашлога / копирования.
## Модули и контент
- [ ] **Следующий билд: переключатель Dungeon Clear только для SQUID** (запрос владельца 2026-10-31):
- Модуль: https://github.com/Zyth45/mod-dungeon-clear, ветка `coa`; серверная интеграция описана в `C:/games/coa-server-build/TODO.md`.
- Добавить в каталог отдельный модуль Dungeon Clear, по умолчанию выключенный. На старых серверах без модуля показывать недоступным.
- Разрешать включение только при установленном и включённом SQUID (`playerbots`). При выключенном SQUID блокировать переключатель и объяснять причину; CoA Companions не подходят.
- Проверять зависимость также в Rust backend при изменении модуля и его настроек. Отключение SQUID/переход на Companions отключает Dungeon Clear; обратное включение SQUID не включает Dungeon Clear автоматически.
- Проверить сохранение после перезапуска, ручные конфиги и отказ включения через API в обход UI. Серверный guard обязателен независимо от Manager.
- Все новые UI-тексты — на шести языках. После реализации добавить changelog fragments в соответствующие компоненты; пока это запланированная, не выпущенная возможность.
- [ ] **Внедрение модуля гильдхаусов (`mod-guildhouse`)**:
- **Репозиторий:** `https://github.com/azerothcore/mod-guildhouse`
- **Пайплайн сборки (`coa-server-build`):**
- Добавить checkout модуля в `.github/workflows/server-binaries.yml`, `build.yml` и `build-linux.yml` в директорию `modules/mod-guildhouse`.
- Добавить лицензию модуля и копирование в `scripts/assemble-tree.ps1` (`Licenses/` и `NOTICE.txt`).
- **Адаптация под Conquest of Azeroth (CoA):**
- В диалоге дворецкого (`mod_guildhouse_butler.cpp`) вместо 10 классических тренеров WotLK спавнить **Book of Ascension** (entry `499992`), которая открывает интерфейс `mod-spellbook` и заменяет всех тренеров для кастомных классов и прогрессии способностей.
- Оставить без изменений: профессии, порталы в столицы, банк, аукционы (включая нейтральный), почту, вендоров, парикмахера, горн и наковальню.
- **База данных:**
- Миграции модуля (`guild_house`, `guild_house_spawns`, `creature_template`, `gameobject_template`, `mod_guildhouse_locale`) подхватываются `coa-release` автоматически при валидации схемы контракта.
- **В игре:**
- Разместить NPC-продавца гильдхаусов (`.npc add 500030`) в ключевых хабах / столицах (Штормград, Оргриммар, Даларан).
@@ -1,7 +0,0 @@
---
area: manager
type: added
audience: admins
title: Advanced settings cover creature melee damage, spell damage and health by rank
---
Configure normal, elite, rare, rare elite and world boss creatures separately. Existing normal-creature settings now identify their scope clearly. Changes persist in the server template and require a world server restart.
@@ -1,7 +0,0 @@
---
area: manager
type: fixed
audience: admins
title: Internet sharing accepts existing port forwards to the same server
---
When a router rejects an already configured port forward, the Manager checks its destination. Matching enabled rules are accepted; conflicting rules report the affected TCP port and remain untouched.
@@ -1,7 +0,0 @@
---
area: manager
type: added
audience: admins
title: Choose Parallel or Global level scaling in module settings
---
Content Scaling progression can now be set to Parallel (Classic over 1 to the level cap, TBC and WotLK over 45 to the cap) or Global (all expansions over 1 to the cap) without editing the config file by hand.
@@ -1,7 +0,0 @@
---
area: manager
type: changed
audience: admins
title: The Auction House Bot card has a single switch
---
The separate "Post auctions" option is gone; turning the module on is enough. A server build with the single-switch Auction House Bot is needed, and an old EnableSeller line in the config is ignored.
@@ -1,7 +0,0 @@
---
area: manager
type: fixed
audience: players
title: More character and server browser controls now use your selected language
---
Completed missing German, French, Spanish and Simplified Chinese labels and improved Chinese font support.
@@ -1,7 +0,0 @@
---
area: manager
type: added
audience: admins
title: Configure the day and night cycle from the module settings
---
TimeIsTime now has a module card, an on/off switch and settings translated into all six Manager languages.
@@ -1,7 +0,0 @@
---
area: manager
type: fixed
audience: admins
title: A stalled database inspection no longer blocks server maintenance indefinitely
---
Update checks limit how long their database client can run and release the maintenance lock after a timeout. The Manager stops only its inspection client, keeps the database server running and reports that migration history could not be checked.
@@ -1,7 +0,0 @@
---
area: manager
type: added
audience: admins
title: Server owners can allow portable characters per realm
---
Portable admission is off until enabled by the realm owner. Export and import requests enforce the saved choice.
@@ -1,7 +0,0 @@
---
area: manager
type: fixed
audience: admins
title: Allowing portable characters also prepares the server for portable sessions
---
Stop the server before enabling access for the first time. The Manager enables portable sessions in the effective module configuration and preserves the required database setting across restarts. Existing configuration is backed up.
@@ -1,7 +0,0 @@
---
area: manager
type: fixed
audience: players
title: Portable characters open again after using an experimental Manager
---
Preserves saved characters and collections when opening a portable store upgraded by an experimental Manager.
@@ -1,7 +0,0 @@
---
area: manager
type: fixed
audience: admins
title: Managers stay compatible with the public connection service
---
Coordinator authentication no longer changes when portable messages change. The publishing card shows game relay status separately.
-7
View File
@@ -1,7 +0,0 @@
---
area: manager
type: fixed
audience: admins
title: Relay connections recover and use the ports of the installed server
---
Dropped or unresponsive relay links reconnect automatically. Abandoned game connections close, and tunnels refresh when local ports become available or change. Custom authentication ports are respected.
-7
View File
@@ -1,7 +0,0 @@
---
area: manager
type: fixed
audience: admins
title: Portable progress resumes after reconnecting or restarting the Manager
---
The player Manager now saves remote baselines, checkpoints and logout progress durably. Repeated logins stay monitored, and transfer retries preserve the same character and session.
-7
View File
@@ -1,7 +0,0 @@
---
area: manager
type: known-issue
audience: admins
title: Older copies on another host may require maintenance before returning
---
Experimental portable play blocks an outdated existing copy on another host. Automatic refresh while that remote worldserver runs is not available. Your canonical character remains saved in your Manager.
-7
View File
@@ -1,7 +0,0 @@
---
area: client
type: changed
audience: players
title: Install the matching CoA Custom 1.9.1 client files
---
The races installer verifies and installs all five client archives, including the new races and appearance corrections.
-7
View File
@@ -1,7 +0,0 @@
---
area: manager
type: changed
audience: players
title: Install the CoA Custom 1.9.2 client patches
---
Installs the updated Hozen and Centaur assets and quest safety addon. Existing CoA Custom 1.9.1 installations remain recognized when updating or removing patches.
@@ -1,7 +0,0 @@
---
area: manager
type: added
audience: admins
title: Report Content Scaling problems directly to its repository
---
The report form now includes a separate Content Scaling destination.
@@ -1,7 +0,0 @@
---
area: manager
type: added
audience: admins
title: Send custom race problem reports directly to their maintainer
---
The report form now includes Custom Races as a separate destination.
@@ -1,7 +0,0 @@
---
area: manager
type: fixed
audience: admins
title: Internet sharing restores the LAN address after server restarts
---
Friends on the local network receive the server's LAN address and network mask while internet players keep using its public address.
@@ -1,7 +0,0 @@
---
area: manager
type: fixed
audience: admins
title: Server updates preserve the order of database migrations added during merges
---
Older database snapshots no longer run after newer updates when preparing server packages. This prevents outdated Manastorm reward ranges from overwriting newer progression data.
@@ -1,7 +0,0 @@
---
area: manager
type: added
audience: admins
title: Configure custom race availability for new characters
---
Choose individual races in a compact table inside module settings using the installed server catalog. Saving requires a compatible server build and a stopped server. Client synchronization is not yet automatic.
@@ -1,7 +0,0 @@
---
area: manager
type: fixed
audience: admins
title: Public listing offers every realm that starts together, not just the main one
---
With Wildcard or Warcraft Reborn started next to Conquest of Azeroth, Settings now has one listing block per realm, each with its own name, description and access options.
@@ -1,7 +0,0 @@
---
area: manager
type: changed
audience: admins
title: Public listing is a short list of realms with a window for the details
---
Settings shows one line per realm with its state, and publishing opens a window. Publish all realms at once. Account creation and portable characters are chosen before publishing; portable characters are on by default.
@@ -1,7 +0,0 @@
---
area: manager
type: added
audience: admins
title: Configure profession and defense skill gains in server settings
---
Advanced rate settings now include prospecting and milling skill gains, plus the points gained from crafting, defense and gathering.
@@ -1,7 +0,0 @@
---
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.
@@ -1,7 +0,0 @@
---
area: manager
type: added
audience: admins
title: Control portable characters and keep Manager running in the system tray
---
Realm access settings can enable portable characters. Closing the window keeps Manager in the tray, with commands to reopen or exit. Offline realm messages explain why players cannot connect.
@@ -0,0 +1,7 @@
---
area: manager
type: changed
audience: players
title: The game client now comes from the community launcher, not from the Manager
---
The community moved the game client behind its official launcher (account sign-in), so the Manager can no longer download or update it. The built-in client download and update are removed. "Set up the game client" now sends you to coa-development.org to get the launcher; once the launcher has installed the game, choose "I already have a client" and pick its folder. Linking a folder, the server address switch and the companion addon work as before.
+1 -134
View File
@@ -112,8 +112,6 @@
"Corfirean/coa-server-manager:20261016-preserve-core-migration-history.md",
"Corfirean/coa-server-manager:20261016-shared-auth-migration-history.md",
"Corfirean/coa-server-manager:20261016-update-compatibility-wording.md",
"Corfirean/coa-server-manager:20261017-creature-difficulty-rates.md",
"Corfirean/coa-server-manager:20261017-existing-router-mapping.md",
"Corfirean/coa-server-manager:20261018-custom-races-client.md",
"Corfirean/coa-server-manager:20261019-portable-stop-diagnostics.md",
"Corfirean/coa-server-manager:20261019-remote-character-class-names.md",
@@ -122,34 +120,7 @@
"Corfirean/coa-server-manager:20261021-portable-experimental.md",
"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",
"Corfirean/coa-server-manager:20261023-shared-addons-links.md",
"Corfirean/coa-server-manager:20261023-time-is-time-settings.md",
"Corfirean/coa-server-manager:20261023-update-check-database-timeout.md",
"Corfirean/coa-server-manager:20261024-portable-admission.md",
"Corfirean/coa-server-manager:20261024-portable-owner-core-activation.md",
"Corfirean/coa-server-manager:20261024-portable-schema-nine.md",
"Corfirean/coa-server-manager:20261024-relay-authentication.md",
"Corfirean/coa-server-manager:20261024-relay-recovery.md",
"Corfirean/coa-server-manager:20261024-remote-progress.md",
"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-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-portable-settings-and-tray.md"
"Corfirean/coa-server-manager:20261022-custom-races-client.md"
],
"releases": [
{
@@ -652,110 +623,6 @@
"links": [
"[Guides and screenshots](https://github.com/Corfirean/coa-server-manager/blob/master/docs/README.md)"
]
},
{
"tag": "v0.7.2",
"version": "0.7.2",
"date": "2026-10-23",
"url": "https://github.com/Corfirean/coa-server-manager/releases/tag/v0.7.2",
"notes": [
"Advanced settings cover creature melee damage, spell damage and health by rank",
"Internet sharing accepts existing port forwards to the same server",
"The Auction House Bot card has a single switch",
"More character and server browser controls now use your selected language",
"Online player counts correctly separate random bots from players",
"Custom races work with shared addon folders on another drive",
"Configure the day and night cycle from the module settings",
"A stalled database inspection no longer blocks server maintenance indefinitely"
],
"commit": "4d59ce8cb1d4abd7f4992370e9a7ba4dc6bd02f7",
"compare": "https://github.com/Corfirean/coa-server-manager/compare/v0.7.1...v0.7.2"
},
{
"tag": "v0.7.3",
"version": "0.7.3",
"date": "2026-10-23",
"url": "https://github.com/Corfirean/coa-server-manager/releases/tag/v0.7.3",
"notes": [
"Portable characters open again after using an experimental Manager"
],
"commit": "2715170622665f62c396fe1a79f7ef6504713ef1",
"experimentalFeatures": [
"portable-characters"
],
"compare": "https://github.com/Corfirean/coa-server-manager/compare/v0.7.2...v0.7.3"
},
{
"tag": "v0.8.0",
"version": "0.8.0",
"date": "2026-10-24",
"url": "https://github.com/Corfirean/coa-server-manager/releases/tag/v0.8.0",
"notes": [
"Server owners can allow portable characters per realm",
"Allowing portable characters also prepares the server for portable sessions",
"Managers stay compatible with the public connection service",
"Relay connections recover and use the ports of the installed server",
"Portable progress resumes after reconnecting or restarting the Manager",
"Older copies on another host may require maintenance before returning"
],
"commit": "b00e732c7f53f33680aaf6bd520da64b70b26a5a",
"compare": "https://github.com/Corfirean/coa-server-manager/compare/v0.7.3...v0.8.0",
"experimentalFeatures": [
"portable-characters"
]
},
{
"tag": "v0.8.1",
"version": "0.8.1",
"date": "2026-10-25",
"url": "https://github.com/Corfirean/coa-server-manager/releases/tag/v0.8.1",
"notes": [
"Install the matching CoA Custom 1.9.1 client files"
],
"commit": "02e3a9e4e66870a627feeb0b4d3ec2d75a23973d",
"compare": "https://github.com/Corfirean/coa-server-manager/compare/v0.8.0...v0.8.1",
"experimentalFeatures": [
"portable-characters"
]
},
{
"tag": "v0.8.2",
"version": "0.8.2",
"date": "2026-10-27",
"url": "https://github.com/Corfirean/coa-server-manager/releases/tag/v0.8.2",
"notes": [
"Installs the verified CoA Custom 1.9.2 client patches and quest safety addon, while recognizing existing 1.9.1 installations",
"Server updates preserve the order of database migrations introduced during merges, preventing older snapshots from overwriting newer progression"
],
"commit": "81b040ef02763c7cf7a3a3da1424b73177e9d433",
"compare": "https://github.com/Corfirean/coa-server-manager/compare/v0.8.1...v0.8.2",
"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"
]
}
]
}
+1 -91
View File
@@ -15,15 +15,6 @@ pub const MAX_USERNAME: usize = 16;
pub const MIN_PASSWORD: usize = 8;
pub const MAX_PASSWORD: usize = 16;
pub const MAX_CHARACTERS: usize = 200;
pub const MAX_SESSION_BYTES: usize = 12 * 1024 * 1024;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SessionMessageKind {
Started,
Checkpoint,
Collection,
}
/// A game account name: 3 to 16 ASCII letters, digits or `_`, not beginning or ending with `_`.
pub fn valid_username(s: &str) -> bool {
@@ -118,15 +109,6 @@ pub enum Request {
total_size: usize,
collections: BTreeMap<String, Vec<u32>>,
},
OwnedTransferOffer {
transfer_id: Uuid,
character_id: Uuid,
ruleset: String,
canonical_revision: u64,
content_hash: String,
total_size: usize,
collections: BTreeMap<String, Vec<u32>>,
},
/// A chunk of the encoded portable character snapshot payload.
TransferChunk {
transfer_id: Uuid,
@@ -146,24 +128,6 @@ pub enum Request {
transfer_id: Uuid,
character_id: Uuid,
},
SessionPoll {
character_id: Uuid,
session_id: Uuid,
},
SessionRead {
character_id: Uuid,
session_id: Uuid,
message_hash: String,
offset: usize,
},
SessionAck {
character_id: Uuid,
session_id: Uuid,
message_hash: String,
offset: usize,
total_size: usize,
data: String,
},
/// Phase 13: Request a short-lived relay allocation for a relayed JOIN.
AllocateRelay {
player_id: Uuid,
@@ -208,22 +172,6 @@ pub struct CharacterEntry {
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "op", rename_all = "snake_case")]
pub enum Response {
SessionPending {
kind: SessionMessageKind,
total_size: usize,
content_hash: String,
},
SessionIdle {
closed: bool,
},
SessionData {
offset: usize,
data: String,
},
SessionAcked {
received_size: usize,
complete: bool,
},
Welcome {
realm_id: coa_registry_proto::RealmId,
automatic: bool,
@@ -299,10 +247,7 @@ pub fn decode_request(bytes: &[u8]) -> Result<Request> {
.map_err(|_| ControlError::Invalid("a request is not valid".into()))?;
if !matches!(
&r,
Request::TransferOffer { .. }
| Request::OwnedTransferOffer { .. }
| Request::TransferChunk { .. }
| Request::SessionAck { .. }
Request::TransferOffer { .. } | Request::TransferChunk { .. }
) && bytes.len() > MAX_CONTROL_REQUEST_BYTES
{
return Err(ControlError::Limit(
@@ -310,34 +255,6 @@ pub fn decode_request(bytes: &[u8]) -> Result<Request> {
));
}
match &r {
Request::SessionRead {
message_hash,
offset,
..
} => {
if message_hash.len() != 64
|| !message_hash.bytes().all(|b| b.is_ascii_hexdigit())
|| *offset > MAX_SESSION_BYTES
{
return invalid("invalid portable session read");
}
}
Request::SessionAck {
message_hash,
offset,
total_size,
data,
..
} => {
if message_hash.len() != 64
|| !message_hash.bytes().all(|b| b.is_ascii_hexdigit())
|| *total_size > MAX_SESSION_BYTES
|| *offset > *total_size
|| data.len() > 48 * 1024
{
return invalid("invalid portable session acknowledgement chunk");
}
}
Request::Provision {
desired, password, ..
} => {
@@ -363,13 +280,6 @@ pub fn decode_request(bytes: &[u8]) -> Result<Request> {
total_size,
collections,
..
}
| Request::OwnedTransferOffer {
ruleset,
content_hash,
total_size,
collections,
..
} => {
if !matches!(ruleset.as_str(), "coa" | "wildcard" | "reborn") {
return invalid("transfer ruleset must be coa, wildcard, or reborn");
+2 -14
View File
@@ -112,10 +112,6 @@ pub struct ProbeResponse {
pub all_reachable: bool,
}
/// Coordinator authentication is independent of the encrypted application protocol.
/// Changing portable messages must not invalidate deployed v1 host/player proofs.
pub const COORDINATOR_PROTOCOL_VERSION: u32 = 1;
pub fn challenge_nonce() -> String {
let mut n = [0u8; 32];
n[..16].copy_from_slice(Uuid::new_v4().as_bytes());
@@ -126,7 +122,7 @@ pub fn challenge_nonce() -> String {
fn host_input(realm: &RealmId, nonce: &str, ts: i64) -> Vec<u8> {
format!(
"coa-coord-host-v1\n{}\n{realm}\n{nonce}\n{ts}",
COORDINATOR_PROTOCOL_VERSION
crate::CONTROL_PROTOCOL_VERSION
)
.into_bytes()
}
@@ -134,7 +130,7 @@ fn host_input(realm: &RealmId, nonce: &str, ts: i64) -> Vec<u8> {
fn player_input(player: &Uuid, public_key: &str, realm: &RealmId, nonce: &str, ts: i64) -> Vec<u8> {
format!(
"coa-coord-player-v1\n{}\n{}\n{public_key}\n{realm}\n{nonce}\n{ts}",
COORDINATOR_PROTOCOL_VERSION,
crate::CONTROL_PROTOCOL_VERSION,
player.hyphenated()
)
.into_bytes()
@@ -281,14 +277,6 @@ pub fn to_text(frame: &Frame) -> String {
mod tests {
use super::*;
#[test]
fn deployed_coordinator_proofs_stay_v1_when_application_protocol_changes() {
let realm = RealmId::new();
let player = Uuid::now_v7();
assert_eq!(host_input(&realm, "nonce", 42), format!("coa-coord-host-v1\n1\n{realm}\nnonce\n42").into_bytes());
assert_eq!(player_input(&player, "public", &realm, "nonce", 42), format!("coa-coord-player-v1\n1\n{player}\npublic\n{realm}\nnonce\n42").into_bytes());
}
fn key(n: u8) -> SigningKey {
SigningKey::from_bytes(&[n; 32])
}
-75
View File
@@ -1,75 +0,0 @@
//! Live check of the client download path against the community launcher's public server:
//! reads the manifest and downloads the few smallest files into a temp folder (never a real client).
//! Usage: cargo run -p coa-core --example client_probe (PROBE_SKIP=n skips the n smallest files)
use coa_core::clientdl::{self, Apply, Manifest};
use coa_core::download::{Cancel, HttpTransport};
fn main() {
let full = clientdl::fetch_latest().expect("manifest");
println!(
"version {} · {} files · {:.1} GB",
full.version,
full.files.len(),
full.total_bytes() as f64 / 1e9
);
let mut small = full.files.clone();
small.sort_by_key(|f| f.size);
let skip: usize = std::env::var("PROBE_SKIP")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(0);
let small: Vec<_> = small.into_iter().skip(skip).take(6).collect();
let manifest = Manifest {
version: full.version.clone(),
published_at: None,
files: small,
};
let dir = std::env::temp_dir().join(format!("coa-client-probe-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let cancel = Cancel::default();
let plan = clientdl::plan(&dir, &manifest, &Default::default(), &cancel, &|_| {}).unwrap();
println!(
"plan: {} files, {} bytes",
plan.items.len(),
plan.download_bytes
);
let transport = HttpTransport::new().unwrap();
clientdl::apply(
&Apply {
client: &dir,
manifest: &manifest,
plan: &plan,
keep_modified: false,
transport: &transport,
objects_url: clientdl::OBJECTS_URL,
cancel: &cancel,
},
&|s| {
println!(
"{} {}/{} {}",
s.phase,
s.done,
s.total,
s.file.unwrap_or_default()
)
},
)
.expect("apply");
let again = clientdl::plan(
&dir,
&manifest,
&clientdl::load_state(&dir).unwrap(),
&cancel,
&|_| {},
)
.unwrap();
println!(
"second plan: {} to do, {} up to date, version {:?}",
again.items.len(),
again.up_to_date_files,
clientdl::local(&dir).version
);
std::fs::remove_dir_all(&dir).unwrap();
}
File diff suppressed because it is too large. Load diff
+441
View File
@@ -0,0 +1,441 @@
//! CLI tool for CoA Server Manager plugin operations (testing, qualification and automation).
use std::collections::BTreeMap;
use std::fs;
use std::path::Path;
use coa_core::plugins::{self, PluginMetadata};
fn print_usage() {
eprintln!(
r#"csm_plugins CLI
Usage:
csm_plugins install <server> <id> <name> <version> <dll> [--pdb <pdb>] [--conf <dist_confs>] [--deps <deps>] [--enable] [--crash-at <point>]
csm_plugins update <server> <id> <name> <version> <dll> [--pdb <pdb>] [--conf <dist_confs>] [--crash-at <point>]
csm_plugins enable <server> <id> [--crash-at <point>]
csm_plugins disable <server> <id> [--crash-at <point>]
csm_plugins remove <server> <id> [--crash-at <point>]
csm_plugins repair <server> [--crash-at <point>]
csm_plugins recover <server>
csm_plugins prune <server>
csm_plugins list <server>
csm_plugins reconcile_squid <server> [char_schema]
csm_plugins multiworld <server> <second_root> [--allow <a,b>] [--crash-at <point>]
csm_plugins analyze <local_repository_path> [--json]
csm_plugins analyze-github <url> [--cache-dir <dir>] [--contract <v02|v03>] [--json]
csm_plugins verify-artifact-provenance <worldserver_path> [--sdk-json <path>] [--json]
"#
);
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let args: Vec<String> = std::env::args().collect();
if args.len() < 3 {
print_usage();
std::process::exit(1);
}
// Inspect for --crash-at argument
for i in 0..args.len() {
if args[i] == "--crash-at" && i + 1 < args.len() {
std::env::set_var("CSM_CRASH_AT", &args[i + 1]);
}
}
let cmd = &args[1];
let server = Path::new(&args[2]);
match cmd.as_str() {
"install" => {
if args.len() < 7 {
eprintln!("Usage: install <server> <id> <name> <version> <dll> [--pdb <pdb>] [--conf <dist_confs>] [--deps <deps>] [--enable]");
std::process::exit(1);
}
let id = &args[3];
let name = &args[4];
let version = &args[5];
let dll_path = Path::new(&args[6]);
let dll_bytes = fs::read(dll_path)?;
let digest = plugins::sha256_digest(&dll_bytes);
let mut pdb_bytes = None;
let mut conf_list = Vec::new();
let mut deps = Vec::new();
let mut enable = false;
let mut i = 7;
while i < args.len() {
match args[i].as_str() {
"--pdb" => {
i += 1;
if i < args.len() {
pdb_bytes = Some(fs::read(&args[i])?);
}
}
"--conf" => {
i += 1;
if i < args.len() {
for item in args[i].split(',') {
if !item.is_empty() {
let p = Path::new(item);
let file_name = p.file_name().unwrap().to_string_lossy().into_owned();
let bytes = fs::read(p)?;
conf_list.push((file_name, bytes));
}
}
}
}
"--deps" => {
i += 1;
if i < args.len() {
deps = args[i].split(',').filter(|s| !s.is_empty()).map(|s| s.to_string()).collect();
}
}
"--enable" => {
enable = true;
}
_ => {}
}
i += 1;
}
let conf_names: Vec<String> = conf_list.iter().map(|(n, _)| n.clone()).collect();
let dist_refs: Vec<(String, &[u8])> = conf_list.iter().map(|(n, b)| (n.clone(), b.as_slice())).collect();
let meta = PluginMetadata {
id: id.clone(),
name: name.clone(),
version: version.clone(),
description: BTreeMap::new(),
sha256: digest,
required: true,
deps,
conf_files: conf_names,
enable_key: None,
status: Some("release".into()),
icon: None,
};
plugins::install(server, meta, &dll_bytes, pdb_bytes.as_deref(), &dist_refs, enable)?;
println!("Installed plugin '{}' successfully (enabled: {})", id, enable);
}
"update" => {
if args.len() < 7 {
eprintln!("Usage: update <server> <id> <name> <version> <dll> [--pdb <pdb>] [--conf <dist_confs>]");
std::process::exit(1);
}
let id = &args[3];
let name = &args[4];
let version = &args[5];
let dll_path = Path::new(&args[6]);
let dll_bytes = fs::read(dll_path)?;
let digest = plugins::sha256_digest(&dll_bytes);
let mut pdb_bytes = None;
let mut conf_list = Vec::new();
let mut i = 7;
while i < args.len() {
match args[i].as_str() {
"--pdb" => {
i += 1;
if i < args.len() {
pdb_bytes = Some(fs::read(&args[i])?);
}
}
"--conf" => {
i += 1;
if i < args.len() {
for item in args[i].split(',') {
if !item.is_empty() {
let p = Path::new(item);
let file_name = p.file_name().unwrap().to_string_lossy().into_owned();
let bytes = fs::read(p)?;
conf_list.push((file_name, bytes));
}
}
}
}
_ => {}
}
i += 1;
}
let conf_names: Vec<String> = conf_list.iter().map(|(n, _)| n.clone()).collect();
let dist_refs: Vec<(String, &[u8])> = conf_list.iter().map(|(n, b)| (n.clone(), b.as_slice())).collect();
let meta = PluginMetadata {
id: id.clone(),
name: name.clone(),
version: version.clone(),
description: BTreeMap::new(),
sha256: digest,
required: true,
deps: vec![],
conf_files: conf_names,
enable_key: None,
status: Some("release".into()),
icon: None,
};
plugins::update(server, meta, &dll_bytes, pdb_bytes.as_deref(), &dist_refs)?;
println!("Updated plugin '{}' to version {} successfully", id, version);
}
"enable" => {
if args.len() < 4 {
eprintln!("Usage: enable <server> <id>");
std::process::exit(1);
}
let id = &args[3];
plugins::set_enabled(server, id, true)?;
println!("Enabled plugin '{}' successfully", id);
}
"disable" => {
if args.len() < 4 {
eprintln!("Usage: disable <server> <id>");
std::process::exit(1);
}
let id = &args[3];
plugins::set_enabled(server, id, false)?;
println!("Disabled plugin '{}' successfully", id);
}
"remove" => {
if args.len() < 4 {
eprintln!("Usage: remove <server> <id>");
std::process::exit(1);
}
let id = &args[3];
plugins::remove(server, id)?;
println!("Removed plugin '{}' successfully", id);
}
"repair" => {
let restored = plugins::repair(server)?;
println!("Repair complete. Restored {} plugin(s): {:?}", restored.len(), restored);
}
"recover" => {
plugins::ensure_durable_recovered(server)?;
println!("Durable transaction recovery complete (clean state restored).");
}
"prune" => {
let pruned = plugins::prune_store(server)?;
println!("Pruned {} unused store version(s): {:?}", pruned.len(), pruned);
}
"reconcile_squid" => {
let char_schema = if args.len() >= 4 { &args[3] } else { "acore_characters" };
let port_str = std::env::var("MYSQL_PORT").unwrap_or_else(|_| "3417".into());
let user = std::env::var("MYSQL_USER").unwrap_or_else(|_| "root".into());
let pass = std::env::var("MYSQL_PWD").unwrap_or_default();
let mysql_exe = std::env::var("MYSQL_EXE").unwrap_or_else(|_| "mysql".into());
let query_fn = |sql: &str| -> Result<String, coa_core::error::Error> {
let mut cmd = std::process::Command::new(&mysql_exe);
cmd.args(["-h", "127.0.0.1", "-P", &port_str, "-u", &user, "-e", sql]);
if !pass.is_empty() && pass != "trap" {
cmd.env("MYSQL_PWD", &pass);
} else {
cmd.env_remove("MYSQL_PWD");
}
let out = cmd.output().map_err(coa_core::error::Error::Io)?;
if !out.status.success() {
return Err(coa_core::error::Error::Invalid(String::from_utf8_lossy(&out.stderr).into_owned()));
}
Ok(String::from_utf8_lossy(&out.stdout).into_owned())
};
let audit = plugins::reconcile_squid_migrations(server, char_schema, Some(&query_fn))?;
println!("SQUID Reconciliation: status={:?}, applied={}", audit.db_status, audit.effective_applied);
}
"list" => {
let reg = plugins::load_registry(server)?;
println!("Plugins schema {}:", reg.schema);
for (id, p) in reg.plugins {
println!(
" - {}: enabled={}, version={}, sha256={}",
id, p.enabled, p.version, p.sha256
);
}
}
"multiworld" => {
if args.len() < 4 {
eprintln!("Usage: multiworld <server> <second_root> [--allow <a,b>]");
std::process::exit(1);
}
let second_root = Path::new(&args[3]);
let mut allowlist = None;
if args.len() >= 6 && args[4] == "--allow" {
allowlist = Some(args[5].split(',').filter(|s| !s.is_empty()).map(str::to_string).collect::<Vec<_>>());
}
plugins::prepare_multiworld_realm(server, second_root, allowlist.as_deref())?;
println!("Prepared multiworld realm at {} successfully", second_root.display());
}
"analyze" => {
let repo_path = Path::new(&args[2]);
let as_json = args.iter().any(|a| a == "--json");
let contract = if args.iter().any(|a| a == "--sdk-v02") {
coa_core::analyzer::SdkExportContract::v02()
} else {
coa_core::analyzer::SdkExportContract::v03()
};
let report = coa_core::analyzer::analyze_repository_with_contract(repo_path, &contract)?;
if as_json {
println!("{}", serde_json::to_string_pretty(&report)?);
} else {
println!("=== Module Compatibility Report v0.2 ===");
println!("Repository: {}", report.repository_name);
println!("Commit : {}", report.commit);
println!("License : {}", report.license_info.primary_license);
if let Some(ref lf) = report.license_info.license_file {
println!("License File: {}", lf);
}
if !report.license_info.vendored_licenses.is_empty() {
println!("Vendored Licenses: {:?}", report.license_info.vendored_licenses);
}
println!("Verdict : {:?}", report.classification);
println!("Status L0-L6: static={}, compile={}, link={}, contract={}, boot={}, gameplay={}, teardown={}",
report.verification_status.l0_static,
report.verification_status.l1_compile,
report.verification_status.l2_link,
report.verification_status.l3_contract,
report.verification_status.l4_engine_boot,
report.verification_status.l5_gameplay,
report.verification_status.l6_teardown);
println!("Hooks ({}):", report.hooks.len());
for h in &report.hooks {
println!(" - {} : {} ({}:{})", h.class_name, h.script_type, h.file, h.line);
}
println!("SQL Files ({}):", report.sql_files.len());
for s in &report.sql_files {
println!(" - {} [schema: {}] (create={}, alter={}, lines={})", s.file, s.target_schema, s.has_create_table, s.has_alter_table, s.line_count);
}
println!("Findings ({}):", report.findings.len());
for f in &report.findings {
println!(" [{:?}] {} (at {}:{}): {}", f.severity, f.rule_id, f.file, f.line, f.explanation);
println!(" Guidance: {}", f.recommended_action);
}
println!("Summary Reasons: {:?}", report.reasons);
}
}
"analyze-github" => {
let url = &args[2];
let mut cache_dir = None;
let mut json_out = false;
let mut i = 3;
while i < args.len() {
match args[i].as_str() {
"--cache-dir" => {
i += 1;
if i < args.len() {
cache_dir = Some(std::path::PathBuf::from(&args[i]));
}
}
"--json" => {
json_out = true;
}
_ => {}
}
i += 1;
}
match coa_core::analyzer::analyze_github_repository(url, cache_dir.as_deref()) {
Ok(report) => {
if json_out {
println!("{}", serde_json::to_string_pretty(&report)?);
} else {
println!("Repository: {}", report.repository_name);
println!("Classification: {:?}", report.classification);
println!("License: {}", report.license_info.primary_license);
println!("Cache Hit: {:?}", report.cache_hit);
println!("Tree Digest: {:?}", report.tree_digest);
println!("Commit: {:?}", report.commit);
println!("Loaders: {:?}", report.script_loaders);
println!("Hooks: {}", report.hooks.len());
println!("SQL Files: {}", report.sql_files.len());
println!("Findings: {}", report.findings.len());
}
}
Err(e) => {
eprintln!("ERROR: {}", e);
std::process::exit(1);
}
}
}
"generate-adapter" => {
let repo_path = Path::new(&args[2]);
let res = coa_core::analyzer::generate_adapter(repo_path)?;
match res {
coa_core::analyzer::AdapterGenerationResult::Success { canonical_loader, adapter_source, delegated_count } => {
println!("Canonical Master Loader: {} (delegates to {} scripts)", canonical_loader, delegated_count);
if let Some(pos) = args.iter().position(|a| a == "--output") {
if pos + 1 < args.len() {
let out_path = Path::new(&args[pos + 1]);
if let Some(p) = out_path.parent() {
std::fs::create_dir_all(p)?;
}
std::fs::write(out_path, &adapter_source)?;
println!("Adapter successfully written to: {}", out_path.display());
}
} else {
println!("--- Generated Adapter Source ---");
println!("{}", adapter_source);
}
}
coa_core::analyzer::AdapterGenerationResult::ManualAdapterRequired { reason, candidate_loaders } => {
eprintln!("MANUAL_ADAPTER_REQUIRED: {}", reason);
eprintln!("Candidate Loaders: {:?}", candidate_loaders);
std::process::exit(1);
}
coa_core::analyzer::AdapterGenerationResult::NoLoaderFound => {
eprintln!("NO_LOADER_FOUND: Unable to discover any Add*Scripts() functions.");
std::process::exit(1);
}
}
}
"verify-artifact-provenance" => {
let exe_path = Path::new(&args[2]);
let mut sdk_json = None;
let mut json_out = false;
let mut i = 3;
while i < args.len() {
match args[i].as_str() {
"--sdk-json" => {
i += 1;
if i < args.len() {
sdk_json = Some(Path::new(&args[i]));
}
}
"--json" => {
json_out = true;
}
_ => {}
}
i += 1;
}
match coa_core::provenance::verify_worldserver_provenance(exe_path, sdk_json) {
Ok(rec) => {
if json_out {
println!("{}", serde_json::to_string_pretty(&rec)?);
} else {
println!("Artifact: {}", rec.file_path);
println!("SHA-256: {}", rec.file_sha256);
println!("Arch: {}", rec.machine_architecture);
println!("Exports: {}", rec.total_export_count);
println!("Embedded ABI: {:?}", rec.embedded_abi_fingerprint);
println!("Status: {}", rec.provenance_status);
}
}
Err(e) => {
eprintln!("ERROR: {}", e);
std::process::exit(1);
}
}
}
_ => {
eprintln!("Unknown command: {}", cmd);
print_usage();
std::process::exit(1);
}
}
Ok(())
}
@@ -1,124 +0,0 @@
//! 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
}])
);
}
}
-921
View File
@@ -1,921 +0,0 @@
//! Download and update of the game client from the community launcher's public manifest.
//!
//! The manifest lists every file with its size and SHA-256; each file is fetched by hash and verified before it is
//! moved into place (`download::fetch_with`, resumable). The Manager keeps a small state file inside the client
//! folder (`.coa-manager/client-state.json`) so that later checks are cheap and so that files the player changed
//! are recognised: they are never overwritten without being asked, and a replaced file is moved aside, not deleted.
//! WTF, Cache, other addons, logs and `realmlist.wtf` are not part of what the Manager synchronises.
use std::collections::{BTreeMap, HashMap};
use std::fs::{self, File};
use std::io::Read;
use std::path::{Path, PathBuf};
use std::time::{Instant, UNIX_EPOCH};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use crate::download::{self, Cancel, HttpTransport, Job, Transport};
use crate::error::{Error, Result};
use crate::fsx;
pub const MANIFEST_URL: &str =
"https://launcher-api.coa-development.org/downloads/client/latest.json";
pub const OBJECTS_URL: &str = "https://launcher-api.coa-development.org/downloads/client/objects";
const STATE_DIR: &str = ".coa-manager";
const MAX_MANIFEST_BYTES: u64 = 16 * 1024 * 1024;
const MAX_FILE_BYTES: u64 = 16 * 1024 * 1024 * 1024;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ManifestFile {
pub path: String,
pub size: u64,
pub sha256: String,
}
#[derive(Debug, Clone, Serialize)]
pub struct Manifest {
pub version: String,
pub published_at: Option<String>,
pub files: Vec<ManifestFile>,
}
impl Manifest {
pub fn total_bytes(&self) -> u64 {
self.files.iter().map(|f| f.size).sum()
}
}
#[derive(Deserialize)]
struct RawManifest {
schema: u32,
version: String,
#[serde(rename = "publishedAt")]
published_at: Option<String>,
files: Vec<ManifestFile>,
}
/// Things the Manager never writes, even if a manifest lists them: logs, the realmlist, the player's own settings,
/// caches and the companion addon (those have their own safe paths).
fn is_excluded(path: &str) -> bool {
let p = path.replace('\\', "/").to_ascii_lowercase();
p.ends_with(".log")
|| p.rsplit('/').next() == Some("realmlist.wtf")
|| p.starts_with("wtf/")
|| p.starts_with("cache/")
|| p.starts_with("errors/")
|| p.starts_with("logs/")
|| p.starts_with(".coa-manager/")
|| p.starts_with("interface/addons/coabotui/")
}
/// Files players customise: graphics wrappers and their configuration. If one exists and differs from the published
/// file it is left exactly as it is, whatever the "keep my files" choice; it is only created when missing.
fn is_player_owned(path: &str) -> bool {
let name = path.rsplit('/').next().unwrap_or(path).to_ascii_lowercase();
matches!(
name.as_str(),
"d3d8.dll" | "d3d9.dll" | "d3d10core.dll" | "d3d11.dll" | "dxgi.dll" | "dxvk.conf"
) || matches!(
name.rsplit('.').next(),
Some("ini" | "conf" | "cfg" | "wtf")
)
}
pub fn parse_manifest(text: &str) -> Result<Manifest> {
let raw: RawManifest = serde_json::from_str(text)
.map_err(|e| Error::Invalid(format!("The client list could not be read: {e}")))?;
if raw.schema != 1 {
return Err(Error::Invalid(format!(
"The client list uses a newer format ({}); update the Manager.",
raw.schema
)));
}
if raw.version.trim().is_empty() || raw.version.len() > 64 {
return Err(Error::Invalid("The client list has no version.".into()));
}
let root = Path::new("client-root");
let mut files = Vec::with_capacity(raw.files.len());
for f in raw.files {
fsx::safe_join(root, &f.path)?;
let hash_ok = f.sha256.len() == 64 && f.sha256.bytes().all(|b| b.is_ascii_hexdigit());
if !hash_ok || f.size > MAX_FILE_BYTES {
return Err(Error::Invalid(format!(
"The client list has a bad entry for {}.",
f.path
)));
}
if is_excluded(&f.path) {
continue;
}
files.push(ManifestFile {
path: f.path.replace('\\', "/"),
size: f.size,
sha256: f.sha256.to_ascii_lowercase(),
});
}
if files.is_empty() {
return Err(Error::Invalid("The client list is empty.".into()));
}
Ok(Manifest {
version: raw.version,
published_at: raw.published_at,
files,
})
}
pub fn fetch_manifest(transport: &dyn Transport, url: &str) -> Result<Manifest> {
let mut reply = transport
.get(url, 0)
.map_err(|e| Error::Invalid(format!("Could not reach the client download server: {e}")))?;
if reply.status != 200 {
return Err(Error::Invalid(format!(
"The client download server answered {}.",
reply.status
)));
}
let mut text = String::new();
reply
.body
.by_ref()
.take(MAX_MANIFEST_BYTES)
.read_to_string(&mut text)
.map_err(|e| Error::Invalid(format!("Could not read the client list: {e}")))?;
parse_manifest(&text)
}
pub fn fetch_latest() -> Result<Manifest> {
download::check_url(MANIFEST_URL)?;
fetch_manifest(&HttpTransport::with_total_timeout(30)?, MANIFEST_URL)
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Entry {
pub size: u64,
pub mtime: u64,
pub sha256: String,
/// The player chose to keep this file although the manifest has a different one (this is the manifest hash
/// they were asked about; a newer manifest asks again).
#[serde(default)]
pub kept_against: Option<String>,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct State {
/// The manifest version this folder was brought to; None while a download is unfinished.
pub version: Option<String>,
pub files: BTreeMap<String, Entry>,
}
fn state_path(client: &Path) -> PathBuf {
client.join(STATE_DIR).join("client-state.json")
}
pub fn load_state(client: &Path) -> Option<State> {
fsx::read_json(&state_path(client)).ok()
}
fn save_state(client: &Path, state: &State) -> Result<()> {
fsx::atomic_write_json(&state_path(client), state)
}
#[derive(Debug, Clone, Serialize)]
pub struct Local {
/// The Manager downloaded or adopted this folder (a state file exists).
pub managed: bool,
pub version: Option<String>,
}
pub fn local(client: &Path) -> Local {
let s = load_state(client);
Local {
managed: s.is_some(),
version: s.and_then(|s| s.version),
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum Kind {
/// Not in the folder.
Missing,
/// Still as the Manager left it; the manifest has a newer file.
Changed,
/// Different from the manifest and not as the Manager left it (changed by the player or by something else).
Modified,
}
#[derive(Debug, Clone, Serialize)]
pub struct Item {
pub path: String,
pub size: u64,
pub kind: Kind,
#[serde(skip)]
sha256: String,
}
#[derive(Debug, Clone, Serialize)]
pub struct Plan {
pub version: String,
pub items: Vec<Item>,
pub download_bytes: u64,
pub total_files: usize,
pub up_to_date_files: usize,
pub kept_files: usize,
#[serde(skip)]
confirmed: BTreeMap<String, Entry>,
}
impl Plan {
pub fn modified(&self) -> Vec<&Item> {
self.items
.iter()
.filter(|i| i.kind == Kind::Modified)
.collect()
}
}
#[derive(Debug, Clone, Serialize)]
pub struct Step {
/// "scan" while comparing files, "download" while fetching, "finish" at the end.
pub phase: &'static str,
pub done: u64,
pub total: u64,
pub bytes_per_sec: u64,
pub file: Option<String>,
}
fn cancelled() -> Error {
Error::Invalid("Download cancelled.".into())
}
fn mtime_secs(m: &fs::Metadata) -> u64 {
m.modified()
.ok()
.and_then(|t| t.duration_since(UNIX_EPOCH).ok())
.map(|d| d.as_secs())
.unwrap_or(0)
}
fn hash_file(path: &Path, cancel: &Cancel, on_bytes: &mut dyn FnMut(u64)) -> Result<String> {
let mut f = File::open(path)?;
let mut hasher = Sha256::new();
let mut buf = vec![0u8; 1 << 20];
loop {
if cancel.is_set() {
return Err(cancelled());
}
let n = f.read(&mut buf)?;
if n == 0 {
return Ok(hex::encode(hasher.finalize()));
}
hasher.update(&buf[..n]);
on_bytes(n as u64);
}
}
/// Compare the folder with the manifest. Files are hashed only when their size or modification time no longer
/// matches what the state file recorded, so a routine check of a managed folder is quick.
pub fn plan(
client: &Path,
m: &Manifest,
state: &State,
cancel: &Cancel,
on_step: &dyn Fn(Step),
) -> Result<Plan> {
let total = m.total_bytes();
let mut done = 0u64;
let mut items = Vec::new();
let mut confirmed = BTreeMap::new();
let (mut up_to_date, mut kept) = (0usize, 0usize);
for f in &m.files {
if cancel.is_set() {
return Err(cancelled());
}
on_step(Step {
phase: "scan",
done,
total,
bytes_per_sec: 0,
file: Some(f.path.clone()),
});
let path = fsx::safe_join(client, &f.path)?;
let meta = match fs::metadata(&path) {
Ok(meta) if meta.is_file() => meta,
_ => {
items.push(Item {
path: f.path.clone(),
size: f.size,
kind: Kind::Missing,
sha256: f.sha256.clone(),
});
done += f.size;
continue;
}
};
let (size, mtime) = (meta.len(), mtime_secs(&meta));
let entry = state.files.get(&f.path);
let trusted = entry.filter(|e| e.size == size && e.mtime == mtime);
let local: Option<String> = if let Some(e) = trusted {
Some(e.sha256.clone())
} else if size == f.size || entry.map(|e| e.size == size).unwrap_or(false) {
let base = done;
let mut seen = 0u64;
let h = hash_file(&path, cancel, &mut |n| {
seen += n;
on_step(Step {
phase: "scan",
done: base + seen.min(f.size),
total,
bytes_per_sec: 0,
file: Some(f.path.clone()),
});
})?;
Some(h)
} else {
None
};
done += f.size;
if is_player_owned(&f.path) && local.as_deref() != Some(f.sha256.as_str()) {
let sha = match local {
Some(h) => h,
None => hash_file(&path, cancel, &mut |_| {})?,
};
kept += 1;
confirmed.insert(
f.path.clone(),
Entry {
size,
mtime,
sha256: sha,
kept_against: Some(f.sha256.clone()),
},
);
continue;
}
if local.as_deref() == Some(f.sha256.as_str()) {
up_to_date += 1;
confirmed.insert(
f.path.clone(),
Entry {
size,
mtime,
sha256: f.sha256.clone(),
kept_against: None,
},
);
continue;
}
let as_left = entry.filter(|e| local.as_deref() == Some(e.sha256.as_str()));
match as_left {
Some(e) if e.kept_against.as_deref() == Some(f.sha256.as_str()) => {
kept += 1;
confirmed.insert(
f.path.clone(),
Entry {
size,
mtime,
sha256: e.sha256.clone(),
kept_against: e.kept_against.clone(),
},
);
}
Some(e) if e.kept_against.is_none() => {
items.push(Item {
path: f.path.clone(),
size: f.size,
kind: Kind::Changed,
sha256: f.sha256.clone(),
});
}
_ => items.push(Item {
path: f.path.clone(),
size: f.size,
kind: Kind::Modified,
sha256: f.sha256.clone(),
}),
}
}
on_step(Step {
phase: "scan",
done: total,
total,
bytes_per_sec: 0,
file: None,
});
let download_bytes = items.iter().map(|i| i.size).sum();
Ok(Plan {
version: m.version.clone(),
items,
download_bytes,
total_files: m.files.len(),
up_to_date_files: up_to_date,
kept_files: kept,
confirmed,
})
}
pub struct Apply<'a> {
pub client: &'a Path,
pub manifest: &'a Manifest,
pub plan: &'a Plan,
/// Leave files the player changed alone (they are remembered, and asked about again only when the manifest changes).
pub keep_modified: bool,
pub transport: &'a dyn Transport,
pub objects_url: &'a str,
pub cancel: &'a Cancel,
}
fn blocked(path: &str, e: std::io::Error) -> Error {
Error::Invalid(format!("Could not replace {path}: {e}. Close the game and anything else using the client, then try again."))
}
/// Download what the plan lists. Progress is saved after every file, so an interrupted run resumes where it stopped.
pub fn apply(a: &Apply, on_step: &dyn Fn(Step)) -> Result<()> {
let mut state = State {
version: None,
files: a.plan.confirmed.clone(),
};
save_state(a.client, &state)?;
let mut todo = Vec::new();
for item in &a.plan.items {
if item.kind == Kind::Modified && a.keep_modified {
let path = fsx::safe_join(a.client, &item.path)?;
let meta = fs::metadata(&path)?;
let sha = hash_file(&path, a.cancel, &mut |_| {})?;
state.files.insert(
item.path.clone(),
Entry {
size: meta.len(),
mtime: mtime_secs(&meta),
sha256: sha,
kept_against: Some(item.sha256.clone()),
},
);
} else {
todo.push(item);
}
}
let total: u64 = todo.iter().map(|i| i.size).sum();
fsx::require_space(a.client, total)?;
let staging = a.client.join(STATE_DIR).join("staging");
let replaced = a
.client
.join(STATE_DIR)
.join("replaced")
.join(chrono::Utc::now().format("%Y%m%d-%H%M%S").to_string());
let mut done = 0u64;
let mut placed: HashMap<&str, PathBuf> = HashMap::new();
for item in todo {
if a.cancel.is_set() {
save_state(a.client, &state)?;
return Err(cancelled());
}
let target = fsx::safe_join(a.client, &item.path)?;
let started = Instant::now();
let staged = staging.join(&item.sha256);
let copy_from = placed.get(item.sha256.as_str()).cloned();
if copy_from.is_none() {
let job = Job {
url: format!("{}/{}", a.objects_url, item.sha256),
dest: staged.clone(),
sha256: item.sha256.clone(),
size: item.size,
};
let base = done;
let result = download::fetch_with(a.transport, &job, a.cancel, &|p| {
on_step(Step {
phase: "download",
done: base + p.downloaded,
total,
bytes_per_sec: p.bytes_per_sec,
file: Some(item.path.clone()),
});
});
if let Err(e) = result {
let _ = save_state(a.client, &state);
return Err(e);
}
}
if let Some(parent) = target.parent() {
fs::create_dir_all(parent)?;
}
if target.exists() {
if item.kind == Kind::Modified {
let keep = fsx::safe_join(&replaced, &item.path)?;
if let Some(parent) = keep.parent() {
fs::create_dir_all(parent)?;
}
fs::rename(&target, &keep).map_err(|e| blocked(&item.path, e))?;
} else {
fs::remove_file(&target).map_err(|e| blocked(&item.path, e))?;
}
}
match copy_from {
Some(src) => {
fs::copy(&src, &target).map_err(|e| blocked(&item.path, e))?;
}
None => fs::rename(&staged, &target).map_err(|e| blocked(&item.path, e))?,
}
placed.insert(&item.sha256, target.clone());
let meta = fs::metadata(&target)?;
state.files.insert(
item.path.clone(),
Entry {
size: meta.len(),
mtime: mtime_secs(&meta),
sha256: item.sha256.clone(),
kept_against: None,
},
);
save_state(a.client, &state)?;
done += item.size;
let secs = started.elapsed().as_secs_f64().max(0.001);
on_step(Step {
phase: "download",
done,
total,
bytes_per_sec: (item.size as f64 / secs) as u64,
file: Some(item.path.clone()),
});
}
state.version = Some(a.manifest.version.clone());
save_state(a.client, &state)?;
let _ = fs::remove_dir_all(&staging);
on_step(Step {
phase: "finish",
done: total,
total,
bytes_per_sec: 0,
file: None,
});
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::download::Reply;
use std::io::Cursor;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Mutex;
/// Serves objects by hash; remembers what was requested and can fail after N objects.
struct Server {
objects: Mutex<HashMap<String, Vec<u8>>>,
requested: Mutex<Vec<String>>,
cancel_after: Option<(AtomicUsize, Cancel)>,
}
impl Server {
fn new(files: &[(&str, &[u8])]) -> Self {
let s = Server {
objects: Default::default(),
requested: Default::default(),
cancel_after: None,
};
for (_, body) in files {
s.objects
.lock()
.unwrap()
.insert(fsx::sha256_bytes(body), body.to_vec());
}
s
}
}
impl Transport for Server {
fn get(&self, url: &str, from: u64) -> std::result::Result<Reply, String> {
let sha = url.rsplit('/').next().unwrap().to_string();
self.requested.lock().unwrap().push(sha.clone());
if let Some((left, cancel)) = &self.cancel_after {
if left.fetch_sub(1, Ordering::SeqCst) == 1 {
cancel.cancel();
}
}
let body = self
.objects
.lock()
.unwrap()
.get(&sha)
.cloned()
.ok_or("404")?;
let (status, start) = if from > 0 {
(206, from as usize)
} else {
(200, 0)
};
let cr = (from > 0).then(|| format!("bytes {from}-{}/{}", body.len() - 1, body.len()));
Ok(Reply {
status,
content_range: cr,
body: Box::new(Cursor::new(body[start..].to_vec())),
})
}
}
fn manifest(version: &str, files: &[(&str, &[u8])]) -> Manifest {
Manifest {
version: version.into(),
published_at: None,
files: files
.iter()
.map(|(p, b)| ManifestFile {
path: p.to_string(),
size: b.len() as u64,
sha256: fsx::sha256_bytes(b),
})
.collect(),
}
}
const V1: [(&str, &[u8]); 4] = [
("Wow.exe", b"exe-1"),
("Data/common.MPQ", b"common-mpq-data"),
("Data/patch-A.MPQ", b"patch-a-1"),
("Data/enUS/locale.MPQ", b"locale"),
];
fn sync(dir: &Path, m: &Manifest, server: &Server, keep: bool) -> Result<Plan> {
let state = load_state(dir).unwrap_or_default();
let cancel = Cancel::default();
let p = plan(dir, m, &state, &cancel, &|_| {})?;
apply(
&Apply {
client: dir,
manifest: m,
plan: &p,
keep_modified: keep,
transport: server,
objects_url: "https://x.invalid/objects",
cancel: &cancel,
},
&|_| {},
)?;
Ok(p)
}
#[test]
fn manifest_rejects_traversal_and_bad_entries_and_skips_personal_files() {
let ok = r#"{"schema":1,"version":"v1","files":[
{"path":"Wow.exe","size":3,"sha256":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"},
{"path":"Data/enUS/realmlist.wtf","size":3,"sha256":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"},
{"path":"WTF/Config.wtf","size":3,"sha256":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"},
{"path":"Interface/AddOns/CoABotUI/x.lua","size":3,"sha256":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"},
{"path":"MemoryBridge.log","size":3,"sha256":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}]}"#;
let m = parse_manifest(ok).unwrap();
assert_eq!(
m.files.iter().map(|f| f.path.as_str()).collect::<Vec<_>>(),
["Wow.exe"]
);
for bad in [
r#"{"schema":1,"version":"v","files":[{"path":"../evil.dll","size":1,"sha256":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}]}"#,
r#"{"schema":1,"version":"v","files":[{"path":"C:/evil.dll","size":1,"sha256":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}]}"#,
r#"{"schema":1,"version":"v","files":[{"path":"a.dll","size":1,"sha256":"short"}]}"#,
r#"{"schema":2,"version":"v","files":[]}"#,
r#"{"schema":1,"version":"v","files":[]}"#,
] {
assert!(parse_manifest(bad).is_err(), "{bad}");
}
}
#[test]
fn fresh_download_installs_every_file_verified_and_leaves_nothing_behind() {
let d = tempfile::tempdir().unwrap();
let (m, s) = (manifest("v1", &V1), Server::new(&V1));
let p = sync(d.path(), &m, &s, false).unwrap();
assert_eq!(p.items.len(), 4);
for (path, body) in V1 {
assert_eq!(fs::read(d.path().join(path)).unwrap(), body);
}
let st = load_state(d.path()).unwrap();
assert_eq!(st.version.as_deref(), Some("v1"));
assert_eq!(st.files.len(), 4);
assert!(!d.path().join(".coa-manager/staging").exists());
assert!(local(d.path()).managed);
}
#[test]
fn an_update_downloads_only_what_changed_and_a_second_check_is_empty() {
let d = tempfile::tempdir().unwrap();
sync(d.path(), &manifest("v1", &V1), &Server::new(&V1), false).unwrap();
let mut v2 = V1.to_vec();
v2[2] = ("Data/patch-A.MPQ", b"patch-a-2-longer");
v2.push(("Data/new.MPQ", b"brand new"));
let (m2, s2) = (manifest("v2", &v2), Server::new(&v2));
let p = sync(d.path(), &m2, &s2, false).unwrap();
let kinds: Vec<_> = p.items.iter().map(|i| (i.path.as_str(), i.kind)).collect();
assert_eq!(
kinds,
[
("Data/patch-A.MPQ", Kind::Changed),
("Data/new.MPQ", Kind::Missing)
]
);
assert_eq!(
s2.requested.lock().unwrap().len(),
2,
"unchanged files were not downloaded again"
);
assert_eq!(
fs::read(d.path().join("Data/patch-A.MPQ")).unwrap(),
b"patch-a-2-longer"
);
assert!(
!d.path().join(".coa-manager/replaced").exists(),
"a file the Manager itself wrote needs no backup"
);
let again = sync(d.path(), &m2, &s2, false).unwrap();
assert!(again.items.is_empty() && again.up_to_date_files == 5);
assert_eq!(load_state(d.path()).unwrap().version.as_deref(), Some("v2"));
}
#[test]
fn a_file_the_player_changed_is_asked_about_kept_when_told_to_and_saved_when_replaced() {
let d = tempfile::tempdir().unwrap();
sync(d.path(), &manifest("v1", &V1), &Server::new(&V1), false).unwrap();
fs::write(d.path().join("Wow.exe"), b"my patched exe").unwrap();
let mut v2 = V1.to_vec();
v2[0] = ("Wow.exe", b"exe-2");
let (m2, s2) = (manifest("v2", &v2), Server::new(&v2));
let p = sync(d.path(), &m2, &s2, true).unwrap();
assert_eq!(p.modified().len(), 1);
assert_eq!(
fs::read(d.path().join("Wow.exe")).unwrap(),
b"my patched exe",
"kept"
);
assert!(
s2.requested.lock().unwrap().is_empty(),
"nothing needed downloading"
);
let quiet = sync(d.path(), &m2, &s2, true).unwrap();
assert!(
quiet.items.is_empty() && quiet.kept_files == 1,
"the decision is remembered"
);
let mut v3 = V1.to_vec();
v3[0] = ("Wow.exe", b"exe-3");
let (m3, s3) = (manifest("v3", &v3), Server::new(&v3));
let again = sync(d.path(), &m3, &s3, false).unwrap();
assert_eq!(again.modified().len(), 1, "a newer client asks again");
assert_eq!(fs::read(d.path().join("Wow.exe")).unwrap(), b"exe-3");
let saved = fs::read_dir(d.path().join(".coa-manager/replaced"))
.unwrap()
.next()
.unwrap()
.unwrap()
.path();
assert_eq!(
fs::read(saved.join("Wow.exe")).unwrap(),
b"my patched exe",
"the player's version was moved aside, not lost"
);
}
#[test]
fn renderer_files_configs_and_everything_not_in_the_manifest_survive_an_update_untouched() {
let d = tempfile::tempdir().unwrap();
let v1: Vec<(&str, &[u8])> = vec![
("Wow.exe", b"exe-1"),
("d3d9.dll", b"official d3d9"),
("dxvk.conf", b"official conf"),
("Data/common.MPQ", b"common-1"),
];
sync(d.path(), &manifest("v1", &v1), &Server::new(&v1), false).unwrap();
// the player's own setup: custom renderer + configs, addons, WTF, realmlist, extra archives, backups
let mine: Vec<(&str, &[u8])> = vec![
("d3d9.dll", b"my renderer"),
("dxvk.conf", b"my conf"),
("ModernWoWRenderer.ini", b"cfg"),
("GraphicsEffects.ini.bak", b"bak"),
(
"Data/enUS/realmlist.wtf",
b"set realmlist 127.0.0.1
",
),
("Data/patch-5.MPQ", b"extra archive"),
("Interface/AddOns/ElvUI/ElvUI.toc", b"## Title: Elv"),
("WTF/Account/x/SavedVariables.lua", b"vars"),
("Cache/x.wdb", b"cache"),
];
for (p, b) in &mine {
let path = d.path().join(p);
fs::create_dir_all(path.parent().unwrap()).unwrap();
fs::write(path, b).unwrap();
}
let before: BTreeMap<String, String> = mine
.iter()
.map(|(p, b)| (p.to_string(), fsx::sha256_bytes(b)))
.collect();
let v2: Vec<(&str, &[u8])> = vec![
("Wow.exe", b"exe-2"),
("d3d9.dll", b"official d3d9 v2"),
("dxvk.conf", b"official conf v2"),
("Data/common.MPQ", b"common-2"),
];
let (m2, s2) = (manifest("v2", &v2), Server::new(&v2));
for keep in [false, true] {
sync(d.path(), &m2, &s2, keep).unwrap();
for (p, h) in &before {
assert_eq!(
&fsx::sha256_file(&d.path().join(p)).unwrap(),
h,
"{p} must not change (keep_modified={keep})"
);
}
assert_eq!(fs::read(d.path().join("Wow.exe")).unwrap(), b"exe-2");
assert_eq!(
fs::read(d.path().join("Data/common.MPQ")).unwrap(),
b"common-2"
);
}
assert!(
!d.path().join(".coa-manager/replaced").exists(),
"nothing of the player's was displaced"
);
}
#[test]
fn an_existing_client_without_state_is_compared_by_content() {
let d = tempfile::tempdir().unwrap();
for (p, b) in V1 {
let path = d.path().join(p);
fs::create_dir_all(path.parent().unwrap()).unwrap();
fs::write(path, b).unwrap();
}
fs::write(d.path().join("Data/patch-A.MPQ"), b"patch-a-X").unwrap(); // same size, different content
fs::remove_file(d.path().join("Data/enUS/locale.MPQ")).unwrap();
fs::create_dir_all(d.path().join("WTF")).unwrap();
fs::write(d.path().join("WTF/Config.wtf"), b"mine").unwrap();
let m = manifest("v1", &V1);
let p = plan(d.path(), &m, &State::default(), &Cancel::default(), &|_| {}).unwrap();
let kinds: Vec<_> = p.items.iter().map(|i| (i.path.as_str(), i.kind)).collect();
assert_eq!(
kinds,
[
("Data/patch-A.MPQ", Kind::Modified),
("Data/enUS/locale.MPQ", Kind::Missing)
]
);
assert_eq!(p.up_to_date_files, 2);
assert_eq!(fs::read(d.path().join("WTF/Config.wtf")).unwrap(), b"mine");
}
#[test]
fn cancel_keeps_finished_files_and_the_next_run_only_fetches_the_rest() {
let d = tempfile::tempdir().unwrap();
let m = manifest("v1", &V1);
let mut s = Server::new(&V1);
let cancel = Cancel::default();
s.cancel_after = Some((AtomicUsize::new(3), cancel.clone()));
let state = State::default();
let p = plan(d.path(), &m, &state, &cancel, &|_| {}).unwrap();
let r = apply(
&Apply {
client: d.path(),
manifest: &m,
plan: &p,
keep_modified: false,
transport: &s,
objects_url: "https://x.invalid/o",
cancel: &cancel,
},
&|_| {},
);
assert!(r.is_err());
let st = load_state(d.path()).unwrap();
assert!(
st.version.is_none() && !st.files.is_empty() && st.files.len() < 4,
"unfinished but remembered: {}",
st.files.len()
);
assert!(local(d.path()).managed && local(d.path()).version.is_none());
let s2 = Server::new(&V1);
sync(d.path(), &m, &s2, false).unwrap();
assert_eq!(
s2.requested.lock().unwrap().len(),
4 - st.files.len(),
"only the missing files were requested"
);
assert_eq!(load_state(d.path()).unwrap().version.as_deref(), Some("v1"));
}
#[test]
fn a_wrong_object_never_reaches_the_client_folder() {
let d = tempfile::tempdir().unwrap();
let m = manifest("v1", &V1);
let s = Server::new(&V1);
// the server returns different bytes under the right hash
let sha = fsx::sha256_bytes(b"exe-1");
s.objects.lock().unwrap().insert(sha, b"EVIL!".to_vec());
assert!(sync(d.path(), &m, &s, false).is_err());
assert!(!d.path().join("Wow.exe").exists());
assert!(load_state(d.path()).unwrap().version.is_none());
}
}
-48
View File
@@ -2,7 +2,6 @@
pub mod merge;
pub mod parser;
pub mod portable;
pub mod schema;
use std::collections::{BTreeMap, BTreeSet};
@@ -1034,53 +1033,6 @@ Spellbook.New = 5
assert!(v.drift_keys.is_empty());
}
#[test]
fn skill_controls_persist_and_reject_invalid_gains() {
let (_d, root, meta) = fixture();
let changes = BTreeMap::from([
("SkillChance.Prospecting".into(), json!(true)),
("SkillChance.Milling".into(), json!(true)),
("SkillGain.Crafting".into(), json!(3)),
("SkillGain.Defense".into(), json!(4)),
("SkillGain.Gathering".into(), json!(5)),
]);
let report = save(&root, &meta, Scope::Server, &changes).unwrap();
assert_eq!(report.changed.len(), 5);
assert_eq!(report.restart, Some(Restart::World));
for path in ["Settings/worldserver.conf.template", "Core/configs/worldserver.conf"] {
let conf = load_conf(&root.join(path)).unwrap();
for (key, expected) in [("SkillChance.Prospecting", "1"), ("SkillChance.Milling", "1"), ("SkillGain.Crafting", "3"), ("SkillGain.Defense", "4"), ("SkillGain.Gathering", "5")] {
assert_eq!(conf.get(key), Some(expected));
}
assert_eq!(conf.get("Unknown.Custom"), Some("\"keep me\""));
}
for value in [json!(-1), json!(1.5), json!(451)] {
assert!(save(&root, &meta, Scope::Server, &BTreeMap::from([("SkillGain.Crafting".into(), value)])).is_err());
}
}
#[test]
fn creature_rates_save_independently_in_template_and_active_config() {
let (_d, root, meta) = fixture();
let mut changes = BTreeMap::new();
for (i, group) in ["Normal", "Elite.Elite", "Elite.RARE", "Elite.RAREELITE", "Elite.WORLDBOSS"].iter().enumerate() {
for (j, stat) in ["Damage", "SpellDamage", "HP"].iter().enumerate() {
changes.insert(format!("Rate.Creature.{group}.{stat}"), json!(0.25 + (i * 3 + j) as f64 * 0.25));
}
}
let report = save(&root, &meta, Scope::Server, &changes).unwrap();
assert_eq!(report.changed.len(), 15);
assert_eq!(report.restart, Some(Restart::World));
for path in ["Settings/worldserver.conf.template", "Core/configs/worldserver.conf"] {
let conf = load_conf(&root.join(path)).unwrap();
for (key, value) in &changes {
assert_eq!(conf.get(key).unwrap().parse::<f64>().unwrap(), value.as_f64().unwrap(), "{path}: {key}");
}
assert_eq!(conf.get("Unknown.Custom"), Some("\"keep me\""));
}
assert!(save(&root, &meta, Scope::Server, &changes).unwrap().changed.is_empty());
}
#[test]
fn save_changes_only_that_key_in_template_and_generated_conf() {
let (_d, root, meta) = fixture();
-175
View File
@@ -1,175 +0,0 @@
//! Prepare the core side of the owner's portable-character opt-in.
use std::{fs, path::Path};
use super::{parser::ConfFile, take_snapshot, targets, Scope};
use crate::{fsx, Error, Result};
/// Configuration is changed only while the world is stopped. Disabling admission is
/// handled by the control service and must not disable an active session's core.
pub fn enable(root: &Path) -> Result<()> {
let meta = crate::registry::metadata_dir_for(root)?;
let _lock = crate::update::operation_lock_for(&meta, "configuring portable characters", false)?;
let module = root.join("Core/configs/modules/coa.conf");
let module_source = if module.is_file() {
module.clone()
} else {
root.join("Core/configs/modules/coa.conf.dist")
};
let bytes = fs::read(&module_source).map_err(|_| Error::Invalid(
"Update this server before enabling portable characters; its portable configuration is missing.".into()
))?;
let mut conf = ConfFile::parse_bytes(&bytes)?;
if conf.get("PortableSession.Enable").is_none() {
return Err(Error::Invalid("Update this server before enabling portable characters; its core configuration has no portable session support.".into()));
}
let mut writes = Vec::new();
if conf.get("PortableSession.Enable").map(str::trim) != Some("1")
|| conf.get("PortableImport.JobDir").map(str::trim) != Some("\"PortableImport\"")
|| !module.is_file()
{
conf.set(
"PortableSession.Enable",
"1",
&["Enabled by the realm owner's portable-character opt-in"],
);
conf.set(
"PortableImport.JobDir",
"\"PortableImport\"",
&["Shared working directory for the core and Manager"],
);
writes.push((
module.clone(),
module.is_file().then(|| bytes.clone()),
conf.to_text(),
));
}
for path in targets(root, Scope::Server)?.writes {
let bytes = fs::read(&path)?;
let mut conf = ConfFile::parse_bytes(&bytes)?;
if conf.get("CharacterDatabase.WorkerThreads").map(str::trim) != Some("1") {
conf.set(
"CharacterDatabase.WorkerThreads",
"1",
&["Portable sessions require ordered character database transactions"],
);
writes.push((path, Some(bytes), conf.to_text()));
}
}
if writes.is_empty() {
fs::create_dir_all(root.join("Core/PortableImport"))?;
return Ok(());
}
let observed = crate::process::observe(root, &crate::layout::read_ports(root));
if observed.world.state != crate::process::ServiceState::Stopped
|| observed.world.conflict.is_some()
|| std::net::TcpStream::connect_timeout(
&std::net::SocketAddr::from(([127, 0, 0, 1], crate::layout::read_ports(root).world)),
std::time::Duration::from_millis(100),
)
.is_ok()
|| crate::multiworld::is_running(root)
{
return Err(Error::Invalid("Stop this server, then enable portable characters and save again. The Manager must configure the core before its next start.".into()));
}
let originals = writes
.iter()
.filter_map(|(p, old, _)| old.clone().map(|bytes| (p.clone(), bytes)))
.collect::<Vec<_>>();
take_snapshot(
&meta,
Scope::Server,
"before enabling portable characters",
&originals,
)?;
for (index, (path, _, text)) in writes.iter().enumerate() {
if let Err(error) = fsx::atomic_write(path, text.as_bytes()) {
for (path, old, _) in writes.iter().take(index) {
if let Some(bytes) = old {
let _ = fsx::atomic_write(path, bytes);
} else {
let _ = fs::remove_file(path);
}
}
return Err(error);
}
}
fs::create_dir_all(root.join("Core/PortableImport"))?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use tempfile::tempdir;
#[test]
fn portable_opt_in_updates_the_effective_module_and_survives_launcher_rendering() {
let temp = tempdir().unwrap();
let root = temp.path().join("realm");
fs::create_dir_all(root.join("Core/configs/modules")).unwrap();
fs::create_dir_all(root.join("Settings")).unwrap();
fs::write(
root.join("Settings/repack.json"),
r#"{"worldPort":49143,"authPort":49144,"mysqlPort":49145,"raPort":49146}"#,
)
.unwrap();
fs::write(
root.join("Core/configs/modules/coa.conf"),
"# Owner setting\nCoA.Enable = 1\nPortableSession.Enable = 0\n",
)
.unwrap();
for name in [
"Settings/worldserver.conf.template",
"Core/configs/worldserver.conf",
] {
fs::write(
root.join(name),
"CharacterDatabase.WorkerThreads = 3\nMaxPlayerLevel = 80\n",
)
.unwrap();
}
enable(&root).unwrap();
assert!(root.join("Core/PortableImport").is_dir());
let module = fs::read_to_string(root.join("Core/configs/modules/coa.conf")).unwrap();
assert!(
module.contains("# Owner setting") && module.contains("PortableSession.Enable = 1")
);
for name in [
"Settings/worldserver.conf.template",
"Core/configs/worldserver.conf",
] {
let text = fs::read_to_string(root.join(name)).unwrap();
assert!(
text.contains("CharacterDatabase.WorkerThreads = 1")
&& text.contains("MaxPlayerLevel = 80")
);
}
let snapshots =
super::super::list_snapshots(&crate::registry::metadata_dir_for(&root).unwrap());
assert_eq!(snapshots.len(), 1);
enable(&root).unwrap();
assert_eq!(
super::super::list_snapshots(&crate::registry::metadata_dir_for(&root).unwrap()).len(),
1
);
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
fs::write(
root.join("Settings/repack.json"),
format!(
r#"{{"worldPort":{}}}"#,
listener.local_addr().unwrap().port()
),
)
.unwrap();
let disabled = "PortableSession.Enable = 0\n";
fs::write(root.join("Core/configs/modules/coa.conf"), disabled).unwrap();
assert!(enable(&root)
.unwrap_err()
.to_string()
.contains("Stop this server"));
assert_eq!(
fs::read_to_string(root.join("Core/configs/modules/coa.conf")).unwrap(),
disabled
);
}
}
-646
View File
@@ -63,21 +63,6 @@ impl LocalBackend {
}
}
fn require_portable(&self, local_id: &str) -> Result<()> {
let settings = settings::load(&self.settings_dir)?;
if settings
.realms
.get(local_id)
.is_some_and(|cfg| cfg.allow_portable)
{
Ok(())
} else {
Err(Error::Invalid(
"The realm owner has disabled portable characters.".into(),
))
}
}
fn access(&self, local_id: &str) -> Result<RealmAccess> {
let access =
find_access(&self.descriptors, &(self.installs)(), local_id).ok_or_else(|| {
@@ -122,38 +107,6 @@ impl LocalBackend {
}
impl RealmBackend for LocalBackend {
fn session_message(
&self,
local_id: &str,
character: Uuid,
session: Uuid,
account: u32,
) -> Result<super::service::RemoteSessionState> {
let id = local_id.to_string();
self.portable
.call(move |service| service.remote_session_message(&id, character, session, account))
.map_err(|error| unavailable("portable engine", error))?
.map_err(|error| unavailable("portable session", error))
}
fn session_ack(
&self,
local_id: &str,
character: Uuid,
session: Uuid,
account: u32,
kind: app::SessionMessageKind,
bytes: &[u8],
) -> Result<()> {
let id = local_id.to_string();
let bytes = bytes.to_vec();
self.portable
.call(move |service| {
service.apply_remote_session_ack(&id, character, session, account, kind, &bytes)
})
.map_err(|error| unavailable("portable engine", error))?
.map_err(|error| unavailable("portable session", error))
}
fn info(&self, local_id: &str) -> Result<RealmInfo> {
let cfg = settings::load(&self.settings_dir)?.realms.remove(local_id);
let access = self.access(local_id)?;
@@ -303,7 +256,6 @@ impl RealmBackend for LocalBackend {
}
fn export(&self, local_id: &str, _account_id: u32, guid: u32) -> Result<ClaimExport> {
self.require_portable(local_id)?;
let id = local_id.to_string();
let bundle = self
.portable
@@ -325,7 +277,6 @@ impl RealmBackend for LocalBackend {
character_id: Uuid,
revision: u64,
) -> Result<PreflightVerdict> {
self.require_portable(local_id)?;
let id = local_id.to_string();
let cid = crate::portable::CharacterId::from_uuid(character_id)
.map_err(|e| unavailable("character id", e))?;
@@ -340,7 +291,6 @@ impl RealmBackend for LocalBackend {
local_id: &str,
params: RemoteImportParams,
) -> Result<RemoteImportOutcome> {
self.require_portable(local_id)?;
let id = local_id.to_string();
self.portable
.call(move |s| s.import_remote_character(&id, params))
@@ -348,23 +298,6 @@ impl RealmBackend for LocalBackend {
.map_err(|e| unavailable("import remote", e))
}
fn auth_port(&self, local_id: &str) -> Result<u16> {
let access = self.access(local_id)?;
let root = access
.root
.ok_or_else(|| Error::Invalid("The realm's auth port is unresolved.".into()))?;
let settings: serde_json::Value =
crate::fsx::read_json(&root.join("Settings/repack.json"))?;
match settings.get("authPort") {
None => Ok(coa_control_proto::relay::LOCAL_AUTH_PORT),
Some(value) => value
.as_u64()
.and_then(|port| u16::try_from(port).ok())
.filter(|port| *port != 0)
.ok_or_else(|| Error::Invalid("The realm's auth port is invalid.".into())),
}
}
fn world_port(&self, local_id: &str) -> Result<u16> {
if let Ok(override_port) = std::env::var("COA_OVERRIDE_LOCAL_WORLD_PORT") {
if let Ok(p) = override_port.parse::<u16>() {
@@ -398,566 +331,6 @@ mod tests {
use std::fs;
use tempfile::tempdir;
#[test]
fn portable_access_requires_owner_opt_in_and_revokes_immediately() {
let dir = tempdir().unwrap();
let rt =
PortableRuntime::start(&dir.path().join("portable"), Box::new(Vec::new), None).unwrap();
let backend = LocalBackend::new(Arc::new(rt), dir.path(), dir.path(), Arc::new(Vec::new));
assert!(backend.require_portable("srv-test").is_err());
let mut cfg = settings::RegistrySettings::default();
cfg.realms.insert(
"srv-test".into(),
settings::PublishConfig {
realm_id: None,
enabled: true,
display_name: "Test".into(),
description: String::new(),
language: "en".into(),
region: None,
existing_only: false,
allow_portable: true,
route: None,
},
);
settings::save(dir.path(), &cfg).unwrap();
assert!(backend.require_portable("srv-test").is_ok());
cfg.realms.get_mut("srv-test").unwrap().allow_portable = false;
settings::save(dir.path(), &cfg).unwrap();
assert!(backend
.export("srv-test", 1, 1)
.unwrap_err()
.to_string()
.contains("disabled portable"));
assert!(backend
.check_transfer("srv-test", Uuid::new_v4(), 1)
.unwrap_err()
.to_string()
.contains("disabled portable"));
}
#[test]
#[ignore = "Requires disposable A/B databases, B worldserver configuration and REGISTRY_URL"]
fn live_vps_transfer_uses_real_backend_and_preserves_the_working_copy() {
use crate::control::{
host_link::HostLink,
join::{PlayerControl, RealmTarget},
secrets::MemoryStore,
service::HostService,
store::ControlStore,
transport::coordinator_url,
};
use crate::portable::{
extension::ExtensionRegistry,
realm::{
live_import::{number, realms, reset_b},
live_projection::fixture_character,
profile::probe_capabilities,
},
session::live_session::{spec, Server},
store::Store,
};
use crate::realm_registry::{advert::advertise, client::RegistryClient};
use coa_registry_proto::{
AccountProvisioning, Listing, Population, Rates, RealmId, RegisterRequest,
REGISTRY_PROTOCOL_VERSION,
};
use std::collections::BTreeMap;
use std::sync::Mutex;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
let base = std::env::var("REGISTRY_URL").expect("REGISTRY_URL");
let root = std::path::PathBuf::from(
std::env::var("COA_REAL_CONTROL_ROOT").expect("disposable root"),
);
assert!(root.starts_with("C:/games/source/candidate-evidence-20261021"));
crate::config::portable::enable(&root).expect("owner portable-character opt-in");
let databases = realms().expect("disposable databases");
reset_b(&databases.b);
let server = Server::start(spec().expect("disposable worldserver"));
struct Auth(std::process::Child);
impl Drop for Auth {
fn drop(&mut self) {
let _ = self.0.kill();
let _ = self.0.wait();
}
}
let auth_port = crate::layout::read_ports(&root).auth;
assert_eq!(
auth_port, 57637,
"Only the disposable auth port may be used"
);
assert!(std::net::TcpStream::connect(("127.0.0.1", auth_port)).is_err());
let mut command = std::process::Command::new(root.join("Core/authserver.exe"));
command
.arg("-c")
.arg(root.join("Core/configs/authserver.conf"))
.current_dir(root.join("Core"))
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null());
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
command.creation_flags(0x0800_0000);
}
let mut auth = Auth(command.spawn().unwrap());
let end = Instant::now() + Duration::from_secs(30);
while std::net::TcpStream::connect(("127.0.0.1", auth_port)).is_err() {
assert!(
auth.0.try_wait().unwrap().is_none(),
"Disposable authserver exited"
);
assert!(Instant::now() < end, "Disposable authserver did not listen");
std::thread::sleep(Duration::from_millis(100));
}
let mut ra = crate::ra::Ra::connect_to(
server.spec.ra_port,
&server.spec.user,
&server.spec.password,
)
.unwrap();
let caps = probe_capabilities(
&databases.b,
Some(&root.join("Data")),
Some(&mut ra),
&ExtensionRegistry::new(),
)
.unwrap();
let advertised = advertise(&caps).unwrap();
let realm = RealmId::new();
let mut seed = [0u8; 32];
seed[..16].copy_from_slice(Uuid::new_v4().as_bytes());
seed[16..].copy_from_slice(Uuid::new_v4().as_bytes());
let key = ed25519_dalek::SigningKey::from_bytes(&seed);
let clock = || {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs() as i64
};
let registry = RegistryClient::new(&base).unwrap();
let listing = Listing {
display_name: "Real portable candidate gate".into(),
description: "Disposable database and real worldserver test".into(),
language: "en".into(),
region: None,
rates: Rates::default(),
modules: vec![],
account_provisioning: AccountProvisioning {
automatic: true,
existing_only: false,
},
manager_version: crate::MANAGER_VERSION.into(),
};
registry
.register(
&key,
&RegisterRequest {
protocol_version: REGISTRY_PROTOCOL_VERSION,
realm_id: realm,
public_key: coa_registry_proto::sign::encode_public_key(&key.verifying_key()),
listing_hash: listing.hash(),
listing,
capabilities_hash: advertised.advert_hash(),
capabilities: advertised,
population: Population {
players: 0,
bots: 0,
capacity: None,
},
},
clock(),
)
.unwrap();
// Always unpublish this isolated identity, including after a failed assertion.
struct Lease(RegistryClient, RealmId, ed25519_dalek::SigningKey);
impl Drop for Lease {
fn drop(&mut self) {
let ts = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs() as i64;
let _ = self.0.unpublish(&self.2, &self.1, ts);
}
}
let _lease = Lease(registry, realm, key.clone());
let temporary = tempdir().unwrap();
let settings_dir = temporary.path().join("registry");
let local_id = "srv-live-candidate";
let mut cfg = settings::RegistrySettings::default();
cfg.realms.insert(
local_id.into(),
settings::PublishConfig {
realm_id: Some(realm),
enabled: true,
display_name: "Candidate".into(),
description: String::new(),
language: "en".into(),
region: None,
existing_only: false,
allow_portable: true,
route: None,
},
);
settings::save(&settings_dir, &cfg).unwrap();
let installed = root.clone();
let runtime = Arc::new(
PortableRuntime::start(
&temporary.path().join("portable"),
Box::new(move || vec![("live-candidate".into(), installed.clone())]),
None,
)
.unwrap(),
);
let installed = root.clone();
let backend = LocalBackend::new(
runtime.clone(),
&settings_dir,
temporary.path().join("descriptors"),
Arc::new(move || vec![("live-candidate".into(), installed.clone())]),
);
assert_eq!(
backend.info(local_id).unwrap().ruleset,
crate::portable::Ruleset::Coa
);
let service = Arc::new(HostService::new(
local_id,
realm,
Arc::new(Mutex::new(ControlStore::open_in_memory().unwrap())),
Arc::new(backend),
));
let relay = crate::control::relay_link::RelayLink::start_with_local_ports(
coordinator_url(&base, "/relay/v1/host").unwrap(),
realm,
key.clone(),
auth_port,
Some(57638),
);
service.set_relay(relay.clone());
let mut link = HostLink::start(
coordinator_url(&base, "/coord/v1/host").unwrap(),
realm,
key.clone(),
service,
Arc::new(clock),
);
let deadline = Instant::now() + Duration::from_secs(20);
while !link.status().connected && Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(100));
}
assert!(link.status().connected, "{:?}", link.status());
let player_secrets = Arc::new(MemoryStore::default());
let player = Arc::new(
PlayerControl::open(&temporary.path().join("player"), player_secrets.clone()).unwrap(),
);
let target = RealmTarget {
realm_id: realm,
key: key.verifying_key(),
coordinator: coordinator_url(&base, "/coord/v1/player").unwrap(),
};
let mut channel = player.connect(&target).unwrap();
let account = player
.ensure_account(&mut channel, &realm, Some("REALPORTABLEGATE"))
.unwrap();
let until = Instant::now() + Duration::from_secs(20);
while !relay.status().connected && Instant::now() < until {
std::thread::sleep(Duration::from_millis(100));
}
assert!(relay.status().connected, "{:?}", relay.status());
let allocation = player.allocate_relay(&mut channel).unwrap();
use std::io::{Read, Write};
let mut auth_client =
std::net::TcpStream::connect((allocation.relay_host.as_str(), allocation.auth_port))
.unwrap();
auth_client
.set_read_timeout(Some(Duration::from_secs(10)))
.unwrap();
let username = account.username.to_ascii_uppercase();
let mut challenge = vec![0, 0];
challenge.extend_from_slice(&((30 + username.len()) as u16).to_le_bytes());
challenge.extend_from_slice(b"WoW\0");
challenge.extend_from_slice(&[3, 3, 5]);
challenge.extend_from_slice(&12340u16.to_le_bytes());
challenge.extend_from_slice(b"68x\0niW\0SUne");
challenge.extend_from_slice(&0u32.to_le_bytes());
challenge.extend_from_slice(&[127, 0, 0, 1]);
challenge.push(username.len() as u8);
challenge.extend_from_slice(username.as_bytes());
auth_client.write_all(&challenge).unwrap();
let mut response = [0u8; 35];
auth_client.read_exact(&mut response).unwrap();
assert_eq!(
&response[..3],
&[0, 0, 0],
"Real authserver must accept the relay challenge"
);
assert!(response[3..].iter().any(|byte| *byte != 0));
drop(auth_client);
let mut world_client =
std::net::TcpStream::connect((allocation.relay_host.as_str(), allocation.world_port))
.unwrap();
world_client
.set_read_timeout(Some(Duration::from_secs(10)))
.unwrap();
let mut response = [0u8; 44];
world_client.read_exact(&mut response).unwrap();
assert_eq!(
&response[2..4],
&[0xec, 0x01],
"Real worldserver authentication challenge must pass through relay"
);
drop(world_client);
let mut owner = Store::open_in_memory().unwrap();
let profile = owner.default_profile().unwrap();
let character = fixture_character(&databases, &mut owner, profile);
let mut model = owner.load_current(character).unwrap();
model.progression.level = 50;
model.progression.xp = 0;
let hidden_items = model.items.len();
let owner_path = temporary.path().join("player-portable");
let owner_runtime =
Arc::new(PortableRuntime::start(&owner_path, Box::new(Vec::new), None).unwrap());
owner_runtime
.call(move |service| {
let profile = service.owner_profile();
service
.owner_mut()
.host_install_copy(profile, &model, 1, "test-owner")
.unwrap();
})
.unwrap();
let public_realm = realm.to_string();
let (bundle, session, revision) = owner_runtime
.call(move |service| {
service.prepare_remote_transfer(&character.to_string(), &public_realm)
})
.unwrap()
.unwrap();
let transferred = player
.transfer_owned_character(
&mut channel,
session,
character.as_uuid(),
"coa",
revision,
&bundle.payload,
bundle.content_hash,
BTreeMap::new(),
)
.unwrap();
assert_eq!(transferred.session_id, session);
assert!(transferred.local_guid > 0);
assert_eq!(
number(
&databases.b,
&format!(
"SELECT level FROM acore_characters.characters WHERE guid = {}",
transferred.local_guid
)
),
50
);
let retry = player
.transfer_owned_character(
&mut channel,
session,
character.as_uuid(),
"coa",
revision,
&bundle.payload,
bundle.content_hash,
BTreeMap::new(),
)
.unwrap();
assert_eq!(
(retry.local_guid, retry.session_id),
(transferred.local_guid, transferred.session_id)
);
let pending = player.pending_remote_sessions().unwrap().pop().unwrap();
let mut console = server.ra();
console
.run(&format!("botcmd spawnbot {}", transferred.local_guid))
.unwrap();
let deadline = Instant::now() + Duration::from_secs(90);
let sid = crate::portable::SessionId::from_uuid(session).unwrap();
let mut playing = false;
while Instant::now() < deadline {
player
.sync_remote_session(&pending, &owner_runtime)
.unwrap();
let opened = owner_runtime
.call(move |service| {
service
.owner()
.owner_session_info(sid)
.unwrap()
.is_some_and(|row| row.0 == "open")
})
.unwrap();
if opened
&& crate::portable::session::live_session::online(
&databases.b,
transferred.local_guid,
)
&& console
.run(&format!("portable status {}", transferred.local_guid))
.unwrap_or_default()
.contains("gated 0")
{
playing = true;
break;
}
std::thread::sleep(Duration::from_millis(500));
}
assert!(
playing,
"The actual player never received the Owner's durable baseline acknowledgement"
);
let name =
crate::portable::session::live_session::name_of(&databases.b, transferred.local_guid);
console.run(&format!("character level {name} 51")).unwrap();
// Reopen both Player databases before receiving progress. Recovery uses the pinned realm key and durable session.
owner_runtime.shutdown();
drop(owner_runtime);
drop(player);
let owner_runtime =
Arc::new(PortableRuntime::start(&owner_path, Box::new(Vec::new), None).unwrap());
let player = Arc::new(
PlayerControl::open(&temporary.path().join("player"), player_secrets).unwrap(),
);
let pending = player.pending_remote_sessions().unwrap().pop().unwrap();
let deadline = Instant::now() + Duration::from_secs(90);
let mut saved = false;
while Instant::now() < deadline {
player
.sync_remote_session(&pending, &owner_runtime)
.unwrap();
saved = owner_runtime
.call(move |service| {
service
.owner()
.load_current(character)
.unwrap()
.progression
.level
== 51
})
.unwrap();
if saved {
break;
}
std::thread::sleep(Duration::from_millis(500));
}
assert!(saved, "Real in-game progress was not saved through the public coordinator after Manager restart");
assert!(crate::portable::session::live_session::online(
&databases.b,
transferred.local_guid
));
console
.run(&format!("botcmd despawn {}", transferred.local_guid))
.unwrap();
let deadline = Instant::now() + Duration::from_secs(90);
let mut completed = false;
while Instant::now() < deadline {
if player
.sync_remote_session(&pending, &owner_runtime)
.unwrap()
{
completed = true;
break;
}
std::thread::sleep(Duration::from_millis(500));
}
assert!(
completed,
"The final progress acknowledgement never completed"
);
let next = player.pending_remote_sessions().unwrap().pop().unwrap();
assert_ne!(
next.session_id, session,
"The next login must remain monitored"
);
assert!(owner_runtime
.call(move |service| service.remote_session_idle(next.session_id))
.unwrap()
.unwrap());
// A second login without pressing Play is still supervised and saved.
PlayerControl::start_remote_session_sync(&player, &owner_runtime);
console
.run(&format!("botcmd spawnbot {}", transferred.local_guid))
.unwrap();
let deadline = Instant::now() + Duration::from_secs(90);
let next_sid = crate::portable::SessionId::from_uuid(next.session_id).unwrap();
let mut opened = false;
while Instant::now() < deadline {
opened = owner_runtime
.call(move |service| {
service
.owner()
.owner_session_info(next_sid)
.unwrap()
.is_some_and(|row| row.0 == "open")
})
.unwrap();
if opened {
break;
}
std::thread::sleep(Duration::from_millis(500));
}
assert!(
opened
&& crate::portable::session::live_session::online(
&databases.b,
transferred.local_guid
)
);
console.run(&format!("character level {name} 52")).unwrap();
console
.run(&format!("botcmd despawn {}", transferred.local_guid))
.unwrap();
let deadline = Instant::now() + Duration::from_secs(90);
let mut completed = false;
while Instant::now() < deadline {
if player
.pending_remote_sessions()
.unwrap()
.iter()
.all(|pending| pending.session_id != next.session_id)
{
completed = true;
break;
}
std::thread::sleep(Duration::from_millis(500));
}
assert!(
completed,
"The second login's final checkpoint was not acknowledged"
);
player
.leave_idle_remote_session(character.as_uuid(), &owner_runtime)
.unwrap();
assert!(player.pending_remote_sessions().unwrap().is_empty());
owner_runtime
.call(move |service| {
assert!(service.remote_session_closed(session).unwrap());
let current = service.owner().load_current(character).unwrap();
assert_eq!(current.progression.level, 52);
assert!(
current.items.len() >= hidden_items,
"Hidden equipment was lost"
);
})
.unwrap();
owner_runtime.shutdown();
channel.close();
link.stop();
relay.stop();
runtime.shutdown();
drop(server);
}
#[test]
fn unreadable_or_unknown_realm_fails_closed_in_info() {
let dir = tempdir().unwrap();
@@ -1010,25 +383,6 @@ mod tests {
Arc::new(move || vec![("test1".to_string(), root_clone.clone())]),
);
assert_eq!(backend.auth_port("srv-test1:coa").unwrap(), 3724);
fs::write(
root.join("Settings/repack.json"),
r#"{"worldPort":8085,"authPort":57324}"#,
)
.unwrap();
assert_eq!(backend.auth_port("srv-test1:coa").unwrap(), 57324);
assert_eq!(backend.auth_port("srv-test1:wildcard").unwrap(), 57324);
fs::write(
root.join("Settings/repack.json"),
r#"{"worldPort":8085,"authPort":0}"#,
)
.unwrap();
assert!(backend.auth_port("srv-test1:coa").is_err());
fs::write(
root.join("Settings/repack.json"),
r#"{"worldPort":8085,"authPort":57324}"#,
)
.unwrap();
assert_eq!(backend.world_port("srv-test1:coa").unwrap(), 8085);
assert_eq!(backend.world_port("srv-test1:wildcard").unwrap(), 8086);
+1 -15
View File
@@ -303,21 +303,7 @@ fn attempt_route_discovery(
let local_auth = std::env::var("COA_OVERRIDE_LOCAL_AUTH_PORT")
.ok()
.and_then(|p| p.parse().ok())
.map(Ok)
.unwrap_or_else(|| service.local_auth_port());
let local_auth = match local_auth {
Ok(port) => port,
Err(error) => {
set_status(
status,
RouteStatus::RelayOnly {
reason: format!("Cannot resolve local auth port: {error}"),
},
);
service.set_direct_route(None);
return;
}
};
.unwrap_or(coa_control_proto::relay::LOCAL_AUTH_PORT);
let local_world = match std::env::var("COA_OVERRIDE_LOCAL_WORLD_PORT")
.ok()
.and_then(|p| p.parse().ok())
+1 -1
View File
@@ -159,7 +159,7 @@ fn session(
) -> Result<(), LinkError> {
let mut ws = transport::connect(url, POLL)?;
let nonce = match transport::next_frame(&mut ws, Duration::from_secs(15))? {
Frame::Challenge { protocol, nonce } if protocol == coord::COORDINATOR_PROTOCOL_VERSION => nonce,
Frame::Challenge { nonce, .. } => nonce,
_ => return Err(LinkError::Protocol("a challenge was expected".into())),
};
transport::send_text(
+6 -12
View File
@@ -24,7 +24,6 @@ pub struct HostControlRealm {
pub local_id: String,
pub realm_id: String,
pub link: LinkStatus,
pub relay: Option<crate::control::relay_link::RelayStatus>,
}
pub struct HostControl {
@@ -36,7 +35,6 @@ pub struct HostControl {
struct Running {
realm_id: RealmId,
url: String,
ports: Option<(u16, u16)>,
link: HostLink,
#[allow(dead_code)]
relay_link: Option<Arc<crate::control::relay_link::RelayLink>>,
@@ -85,7 +83,7 @@ impl HostControl {
running.retain(|id, r| {
wanted
.get(id)
.is_some_and(|(realm, url, _, _)| *realm == r.realm_id && *url == r.url && backend.auth_port(id).ok().zip(backend.world_port(id).ok()) == r.ports)
.is_some_and(|(realm, url, _, _)| *realm == r.realm_id && *url == r.url)
});
for (local_id, (realm_id, url, base, key)) in wanted {
if running.contains_key(&local_id) {
@@ -97,17 +95,15 @@ impl HostControl {
store.clone(),
backend.clone(),
));
let ports = service.local_auth_port().ok().zip(service.local_world_port().ok());
let relay_link = match ports {
Some((auth_port, world_port)) => {
let relay_link = match service.local_world_port() {
Ok(world_port) => {
crate::control::transport::relay_url(&base, "/relay/v1/host").map(
|r_url| {
let rl =
crate::control::relay_link::RelayLink::start_with_local_ports(
crate::control::relay_link::RelayLink::start_with_ports(
r_url,
realm_id,
key.clone(),
auth_port,
Some(world_port),
);
service.set_relay(rl.clone());
@@ -115,8 +111,8 @@ impl HostControl {
},
)
}
None => {
tracing::warn!(%local_id, "relay is waiting for valid local auth and world ports");
Err(e) => {
eprintln!("Relay link unavailable for {local_id}: cannot resolve world port: {e}");
None
}
};
@@ -132,7 +128,6 @@ impl HostControl {
Running {
realm_id,
url,
ports,
link,
relay_link,
direct_route,
@@ -149,7 +144,6 @@ impl HostControl {
local_id: id.clone(),
realm_id: r.realm_id.to_string(),
link: r.link.status(),
relay: r.relay_link.as_ref().map(|relay| relay.status()),
},
)
})
+11 -40
View File
@@ -20,8 +20,6 @@ use super::store::{AccountKind, ControlStore};
use super::transport::{self, LinkError};
use crate::{Error, Result};
mod portable_sync;
/// Where and as whom to reach a realm.
#[derive(Clone, Debug)]
pub struct RealmTarget {
@@ -414,11 +412,9 @@ impl PlayerControl {
}
/// Transfer a portable character to a remote realm over the verified control channel (Phase 12.1).
fn transfer_with_id(
pub fn transfer_character(
&self,
ch: &mut PlayerChannel,
transfer_id: Uuid,
owned_session: bool,
character_id: Uuid,
ruleset: &str,
canonical_revision: u64,
@@ -426,27 +422,16 @@ impl PlayerControl {
content_hash: [u8; 32],
collections: BTreeMap<String, Vec<u32>>,
) -> R<RemoteTransferOutcome> {
let transfer_id = Uuid::now_v7();
let content_hash_str = hex::encode(content_hash);
let offer = if owned_session {
Request::OwnedTransferOffer {
transfer_id,
character_id,
ruleset: ruleset.to_string(),
canonical_revision,
content_hash: content_hash_str.clone(),
total_size: payload.len(),
collections,
}
} else {
Request::TransferOffer {
transfer_id,
character_id,
ruleset: ruleset.to_string(),
canonical_revision,
content_hash: content_hash_str.clone(),
total_size: payload.len(),
collections,
}
let offer = Request::TransferOffer {
transfer_id,
character_id,
ruleset: ruleset.to_string(),
canonical_revision,
content_hash: content_hash_str.clone(),
total_size: payload.len(),
collections,
};
let r = ch.request(&offer)?;
let mut offset = match r {
@@ -471,21 +456,7 @@ impl PlayerControl {
notes,
});
}
Response::Error { code, message } => {
if owned_session
&& matches!(
code,
AppError::Incompatible
| AppError::NotYours
| AppError::AlreadyClaimed
| AppError::Invalid
)
{
self.store()?
.player_remote_session_remove(character_id, transfer_id)?;
}
return Err(ControlFail::App { code, message });
}
Response::Error { code, message } => return Err(ControlFail::App { code, message }),
_ => {
return Err(ControlFail::Link(LinkError::Protocol(
"unexpected response to transfer offer".into(),
@@ -1,290 +0,0 @@
use super::*;
use crate::control::store::PlayerRemoteSession;
use crate::portable::service::PortableRuntime;
use base64::engine::general_purpose::STANDARD as B64;
use sha2::{Digest, Sha256};
fn protocol_error(message: &str) -> ControlFail {
ControlFail::Link(LinkError::Protocol(message.into()))
}
impl PlayerControl {
/// Compatibility helper for transport tests. Interactive play uses the Owner's durable session id.
pub fn transfer_character(
&self,
channel: &mut PlayerChannel,
character: Uuid,
ruleset: &str,
revision: u64,
payload: &[u8],
hash: [u8; 32],
collections: BTreeMap<String, Vec<u32>>,
) -> R<RemoteTransferOutcome> {
self.transfer_with_id(
channel,
Uuid::now_v7(),
false,
character,
ruleset,
revision,
payload,
hash,
collections,
)
}
pub fn transfer_owned_character(
&self,
channel: &mut PlayerChannel,
session: Uuid,
character: Uuid,
ruleset: &str,
revision: u64,
payload: &[u8],
hash: [u8; 32],
collections: BTreeMap<String, Vec<u32>>,
) -> R<RemoteTransferOutcome> {
self.store()?
.player_remote_session_set(&PlayerRemoteSession {
character_id: character,
realm_id: channel.realm_id.to_string(),
session_id: session,
public_key: coord::encode_public_key(&channel.realm_key),
coordinator: channel.coordinator.clone(),
})?;
let result = self.transfer_with_id(
channel,
session,
true,
character,
ruleset,
revision,
payload,
hash,
collections,
);
if let Ok(outcome) = &result {
if outcome.session_id != session {
return Err(protocol_error(
"The Host returned another portable session.",
));
}
}
result
}
pub fn pending_remote_sessions(&self) -> R<Vec<PlayerRemoteSession>> {
Ok(self.store()?.player_remote_sessions()?)
}
/// An idle, already-saved realm may be left; an uncertain or open session must finish first.
pub fn leave_idle_remote_session(&self, character: Uuid, runtime: &PortableRuntime) -> R<()> {
for pending in self
.pending_remote_sessions()?
.into_iter()
.filter(|pending| pending.character_id == character)
{
let sid = pending.session_id;
let idle = runtime
.call(move |service| service.remote_session_idle(sid))
.map_err(|error| ControlFail::Local(error.to_string()))?
.map_err(|error| ControlFail::Local(error.message))?;
if !idle {
return Err(ControlFail::Local("Progress from the previous realm is still being saved. Keep both Managers running until it finishes.".into()));
}
self.store()?.player_remote_session_remove(character, sid)?;
}
Ok(())
}
/// Persist the Owner's acknowledgement before acknowledging it to the Host. A lost reply is retried without making another revision.
pub fn sync_remote_session(
&self,
pending: &PlayerRemoteSession,
runtime: &PortableRuntime,
) -> R<bool> {
let mut channel = self.remote_session_channel(pending)?;
self.sync_remote_session_on_channel(pending, runtime, &mut channel)
}
fn remote_session_channel(&self, pending: &PlayerRemoteSession) -> R<PlayerChannel> {
let realm = RealmId::parse(&pending.realm_id)
.map_err(|error| ControlFail::Local(error.to_string()))?;
let key = coord::decode_public_key(&pending.public_key)
.map_err(|error| protocol_error(&error.to_string()))?;
let target = RealmTarget {
realm_id: realm,
key,
coordinator: pending.coordinator.clone(),
};
self.connect(&target)
}
fn sync_remote_session_on_channel(
&self,
pending: &PlayerRemoteSession,
runtime: &PortableRuntime,
channel: &mut PlayerChannel,
) -> R<bool> {
let character_id = pending.character_id;
let session_id = pending.session_id;
for _ in 0..16 {
let (kind, total_size, content_hash) = match channel.request(&Request::SessionPoll {
character_id,
session_id,
})? {
Response::SessionIdle { closed } => {
if closed {
let locally_closed = runtime
.call(move |service| service.remote_session_closed(session_id))
.map_err(|error| ControlFail::Local(error.to_string()))?
.map_err(|error| ControlFail::Local(error.message))?;
if !locally_closed {
return Err(protocol_error(
"The Host closed a session before the Owner saved it.",
));
}
let realm = pending.realm_id.clone();
let next = runtime
.call(move |service| service.next_remote_session(character_id, &realm))
.map_err(|error| ControlFail::Local(error.to_string()))?
.map_err(|error| ControlFail::Local(error.message))?;
if let Some(next) = next {
self.store()?.player_remote_session_advance(
character_id,
session_id,
next,
)?;
} else {
self.store()?
.player_remote_session_remove(character_id, session_id)?;
}
return Ok(true);
}
return Ok(false);
}
Response::SessionPending {
kind,
total_size,
content_hash,
} if total_size > 0
&& total_size <= app::MAX_SESSION_BYTES
&& content_hash.len() == 64 =>
{
(kind, total_size, content_hash)
}
Response::Error { code, message } => {
return Err(ControlFail::App { code, message })
}
_ => return Err(protocol_error("Invalid portable session metadata.")),
};
let mut bytes = Vec::with_capacity(total_size);
while bytes.len() < total_size {
match channel.request(&Request::SessionRead {
character_id,
session_id,
message_hash: content_hash.clone(),
offset: bytes.len(),
})? {
Response::SessionData { offset, data } if offset == bytes.len() => {
let chunk = B64
.decode(data)
.map_err(|_| protocol_error("Invalid portable session chunk."))?;
if chunk.is_empty() || chunk.len() > total_size - bytes.len() {
return Err(protocol_error("Invalid portable session chunk bounds."));
}
bytes.extend_from_slice(&chunk);
}
Response::Error { code, message } => {
return Err(ControlFail::App { code, message })
}
_ => return Err(protocol_error("Invalid portable session chunk offset.")),
}
}
if hex::encode(Sha256::digest(&bytes)) != content_hash {
return Err(protocol_error("The portable session message hash changed."));
}
let remote_realm = pending.realm_id.clone();
let ack = runtime
.call(move |service| {
service.apply_remote_session_message(
character_id,
session_id,
&remote_realm,
kind,
&bytes,
)
})
.map_err(|error| ControlFail::Local(error.to_string()))?
.map_err(|error| ControlFail::Local(error.message))?;
let mut offset = 0;
while offset < ack.len() {
let end = ack.len().min(offset + 24 * 1024);
match channel.request(&Request::SessionAck {
character_id,
session_id,
message_hash: content_hash.clone(),
offset,
total_size: ack.len(),
data: B64.encode(&ack[offset..end]),
})? {
Response::SessionAcked {
received_size,
complete,
} if received_size > offset
&& received_size <= ack.len()
&& (!complete || received_size == ack.len()) =>
{
offset = received_size
}
Response::Error { code, message } => {
return Err(ControlFail::App { code, message })
}
_ => return Err(protocol_error("Invalid portable acknowledgement offset.")),
}
}
}
Ok(false)
}
/// Independent of the visible page and the game process. Durable sessions resume after a Manager restart.
pub fn start_remote_session_sync(player: &Arc<Self>, runtime: &Arc<PortableRuntime>) {
let player = Arc::downgrade(player);
let runtime = Arc::downgrade(runtime);
let _ = std::thread::Builder::new().name("portable-remote-sync".into()).spawn(move || {
let mut errors = std::collections::HashMap::<Uuid, String>::new();
let mut channels = std::collections::HashMap::<String, PlayerChannel>::new();
loop {
{
let (Some(player), Some(runtime)) = (player.upgrade(), runtime.upgrade()) else { return };
if let Ok(sessions) = player.pending_remote_sessions() {
let wanted: std::collections::HashSet<_> = sessions.iter().map(|session| format!("{}|{}|{}", session.realm_id, session.public_key, session.coordinator)).collect();
channels.retain(|key, _| wanted.contains(key));
for session in sessions {
let key = format!("{}|{}|{}", session.realm_id, session.public_key, session.coordinator);
let result = (|| {
if !channels.contains_key(&key) {
if channels.len() >= 8 { channels.clear(); }
channels.insert(key.clone(), player.remote_session_channel(&session)?);
}
player.sync_remote_session_on_channel(&session, &runtime, channels.get_mut(&key).expect("inserted"))
})();
match result {
Ok(_) => { errors.remove(&session.character_id); },
Err(error) => {
channels.remove(&key);
let message = error.to_string();
if errors.get(&session.character_id) != Some(&message) {
tracing::warn!(character = %session.character_id, error = %message, "remote portable progress is pending; retrying");
errors.insert(session.character_id, message);
}
}
}
}
}
}
std::thread::sleep(std::time::Duration::from_secs(2));
}
});
}
}
+2 -16
View File
@@ -13,9 +13,6 @@ use super::identity::PlayerIdentity;
use super::transport::{self, LinkError, Ws};
pub struct PlayerChannel {
pub(crate) realm_id: RealmId,
pub(crate) realm_key: VerifyingKey,
pub(crate) coordinator: String,
ws: Ws,
channel: Channel,
conn: u32,
@@ -38,11 +35,7 @@ impl PlayerChannel {
Duration::from_millis(500),
)?;
let nonce = match transport::next_frame(&mut ws, STEP)? {
Frame::Challenge { protocol, nonce }
if protocol == coord::COORDINATOR_PROTOCOL_VERSION =>
{
nonce
}
Frame::Challenge { nonce, .. } => nonce,
_ => return Err(LinkError::Protocol("a challenge was expected".into())),
};
transport::send_text(
@@ -74,14 +67,7 @@ impl PlayerChannel {
{
transport::send_binary(&mut ws, f)?;
}
Ok(PlayerChannel {
ws,
channel,
conn,
realm_id: *realm,
realm_key: *realm_key,
coordinator: coordinator.into(),
})
Ok(PlayerChannel { ws, channel, conn })
}
pub fn connection(&self) -> u32 {
+9 -179
View File
@@ -1,6 +1,6 @@
//! Outbound Host <-> Game Relay tunnel link (Phase 13).
//! Maintains outbound connectivity from Host Manager to the Game Relay,
//! opening local TCP connections only to the installed realm's configured loopback Auth and World ports.
//! opening local TCP connections strictly to 127.0.0.1:3724 (Auth) and 127.0.0.1:8085 (World).
use std::collections::HashMap;
use std::io::{Read, Write};
@@ -79,22 +79,6 @@ impl RelayLink {
realm_id: RealmId,
key: SigningKey,
local_world_port: Option<u16>,
) -> Arc<Self> {
Self::start_with_local_ports(
url,
realm_id,
key,
RelayTarget::Auth.local_port(),
local_world_port,
)
}
pub fn start_with_local_ports(
url: String,
realm_id: RealmId,
key: SigningKey,
local_auth_port: u16,
local_world_port: Option<u16>,
) -> Arc<Self> {
let stop = Arc::new(AtomicBool::new(false));
let status = Arc::new(Mutex::new(RelayStatus::default()));
@@ -104,18 +88,7 @@ impl RelayLink {
let st = status.clone();
let join = std::thread::Builder::new()
.name("control-relay-host".into())
.spawn(move || {
run(
&url,
realm_id,
&key,
alloc_rx,
&s,
&st,
local_auth_port,
local_world_port,
)
})
.spawn(move || run(&url, realm_id, &key, alloc_rx, &s, &st, local_world_port))
.ok();
Arc::new(RelayLink {
@@ -163,25 +136,12 @@ fn run(
)>,
stop: &AtomicBool,
status: &Mutex<RelayStatus>,
local_auth_port: u16,
local_world_port: Option<u16>,
) {
let mut failures = 0u32;
while !stop.load(Ordering::SeqCst) {
let began = Instant::now();
let result = session(
url,
realm,
key,
&alloc_rx,
stop,
status,
local_auth_port,
local_world_port,
);
if let Err(error) = &result {
tracing::warn!(%realm, %error, "game relay connection lost; retrying");
}
let result = session(url, realm, key, &alloc_rx, stop, status, local_world_port);
set_status(status, |s| {
s.connected = false;
s.active_streams = 0;
@@ -213,15 +173,6 @@ fn run(
struct StreamWorker {
tx: Sender<TunnelMsg>,
reset_on_drop: bool,
}
impl Drop for StreamWorker {
fn drop(&mut self) {
if self.reset_on_drop {
let _ = self.tx.send(TunnelMsg::Reset { stream_id: 0 });
}
}
}
fn session(
@@ -235,7 +186,6 @@ fn session(
)>,
stop: &AtomicBool,
status: &Mutex<RelayStatus>,
local_auth_port: u16,
local_world_port: Option<u16>,
) -> Result<(), LinkError> {
let mut ws = transport::connect(url, POLL)?;
@@ -304,7 +254,6 @@ fn session(
let (ws_out_tx, ws_out_rx) = channel::<TunnelMsg>();
let mut last_ping = Instant::now();
let mut last_pong = Instant::now();
while !stop.load(Ordering::SeqCst) {
// Drain pending allocation requests
@@ -325,14 +274,10 @@ fn session(
}
// Keepalive
if last_pong.elapsed() > Duration::from_secs(90) {
return Err(LinkError::Timeout);
}
if last_ping.elapsed() > Duration::from_secs(30) {
ws.send(Message::Text(
let _ = ws.send(Message::Text(
serde_json::to_string(&TunnelMsg::Ping).unwrap().into(),
))
.map_err(|error| LinkError::Io(error.to_string()))?;
));
last_ping = Instant::now();
}
@@ -373,7 +318,7 @@ fn session(
} => {
// Strictly predefined local targets: Auth (3724) or World (8085 or bound realm world port)
let local_port = match target {
RelayTarget::Auth => local_auth_port,
RelayTarget::Auth => target.local_port(),
RelayTarget::World => match local_world_port {
Some(p) => p,
None => {
@@ -393,13 +338,7 @@ fn session(
// Spawn worker for this stream
spawn_local_tcp_bridge(stream_id, tcp, stream_rx, ws_tx);
streams.insert(
stream_id,
StreamWorker {
tx: stream_tx,
reset_on_drop: true,
},
);
streams.insert(stream_id, StreamWorker { tx: stream_tx });
// Reply ConnectOk
let ok_msg = TunnelMsg::ConnectOk { stream_id };
@@ -425,8 +364,7 @@ fn session(
}
}
TunnelMsg::Close { stream_id } => {
if let Some(mut w) = streams.remove(&stream_id) {
w.reset_on_drop = false;
if let Some(w) = streams.remove(&stream_id) {
let _ = w.tx.send(TunnelMsg::Close { stream_id });
}
set_status(status, |s| s.active_streams = streams.len());
@@ -437,9 +375,7 @@ fn session(
}
set_status(status, |s| s.active_streams = streams.len());
}
TunnelMsg::Pong => {
last_pong = Instant::now();
}
TunnelMsg::Pong => {}
_ => {}
}
}
@@ -521,109 +457,3 @@ fn spawn_local_tcp_bridge(
})
.ok();
}
#[cfg(test)]
mod tests {
use super::*;
use std::net::TcpListener;
use std::sync::atomic::AtomicUsize;
#[test]
fn relay_reconnects_after_a_dropped_link_and_clears_its_error() {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
let accepted = Arc::new(AtomicUsize::new(0));
let seen = accepted.clone();
let worker = std::thread::spawn(move || {
for turn in 0..2 {
let (tcp, _) = listener.accept().unwrap();
tcp.set_read_timeout(Some(Duration::from_secs(15))).unwrap();
let mut ws = tungstenite::accept(tcp).unwrap();
ws.send(Message::Text(
serde_json::to_string(&RelayChallenge {
nonce: "relay-reconnect-test".into(),
})
.unwrap()
.into(),
))
.unwrap();
let _: HostHello =
serde_json::from_str(ws.read().unwrap().to_text().unwrap()).unwrap();
ws.send(Message::Text(
serde_json::to_string(&RelayWelcome {
ok: true,
message: String::new(),
})
.unwrap()
.into(),
))
.unwrap();
seen.fetch_add(1, Ordering::SeqCst);
if turn == 0 {
continue;
}
while let Ok(message) = ws.read() {
let Ok(text) = message.to_text() else {
continue;
};
if let Ok(TunnelMsg::Allocate { request_id, .. }) = serde_json::from_str(text) {
ws.send(Message::Text(
serde_json::to_string(&TunnelMsg::AllocateOk {
request_id,
token: "test-only".into(),
relay_host: "127.0.0.1".into(),
auth_port: 41001,
world_port: 41002,
expires_at: i64::MAX,
})
.unwrap()
.into(),
))
.unwrap();
break;
}
}
}
});
let link = RelayLink::start_with_local_ports(
format!("ws://{addr}"),
RealmId::new(),
SigningKey::from_bytes(&[43; 32]),
57324,
Some(58085),
);
let until = Instant::now() + Duration::from_secs(20);
while accepted.load(Ordering::SeqCst) < 2 || !link.status().connected {
assert!(Instant::now() < until, "{:?}", link.status());
std::thread::sleep(Duration::from_millis(50));
}
assert!(link.status().last_error.is_none());
let allocation = link.allocate(&Uuid::now_v7(), None).unwrap();
assert_eq!(
(allocation.auth_port, allocation.world_port),
(41001, 41002)
);
link.stop();
worker.join().unwrap();
}
#[test]
fn dropping_a_tunnel_closes_its_local_tcp_stream() {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let tcp = TcpStream::connect(listener.local_addr().unwrap()).unwrap();
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,
});
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:?}"),
}
}
}
+26 -214
View File
@@ -20,20 +20,6 @@ use uuid::Uuid;
use super::store::{AccountKind, ClaimState, ControlStore, HostTransfer, TransferState};
use crate::{Error, Result};
mod portable_sync;
#[derive(Clone, Debug)]
pub struct RemoteSessionMessage {
pub kind: app::SessionMessageKind,
pub bytes: Vec<u8>,
}
#[derive(Clone, Debug)]
pub struct RemoteSessionState {
pub message: Option<RemoteSessionMessage>,
pub closed: bool,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RealmInfo {
/// Create accounts for joining players (the default). When false the realm only links accounts that exist.
@@ -78,7 +64,6 @@ pub struct ClaimExport {
#[derive(Clone, Debug)]
pub struct RemoteImportParams {
pub session_id: Uuid,
pub character_id: Uuid,
pub revision: u64,
pub payload: Vec<u8>,
@@ -104,30 +89,6 @@ pub enum PreflightVerdict {
/// The realm itself: its login database, its console and the portable engine.
pub trait RealmBackend: Send + Sync {
fn session_message(
&self,
_local_id: &str,
_character: Uuid,
_session: Uuid,
_account: u32,
) -> Result<RemoteSessionState> {
Err(Error::Invalid(
"Portable session synchronization is unavailable.".into(),
))
}
fn session_ack(
&self,
_local_id: &str,
_character: Uuid,
_session: Uuid,
_account: u32,
_kind: app::SessionMessageKind,
_bytes: &[u8],
) -> Result<()> {
Err(Error::Invalid(
"Portable session synchronization is unavailable.".into(),
))
}
fn info(&self, local_id: &str) -> Result<RealmInfo>;
fn account_by_name(&self, local_id: &str, username: &str) -> Result<Option<AccountRow>>;
fn account_by_id(&self, local_id: &str, id: u32) -> Result<Option<AccountRow>>;
@@ -160,9 +121,6 @@ pub trait RealmBackend: Send + Sync {
params: RemoteImportParams,
) -> Result<RemoteImportOutcome>;
/// Local world port for this realm. Must fail closed if the realm port cannot be resolved.
fn auth_port(&self, _local_id: &str) -> Result<u16> {
Ok(coa_control_proto::relay::LOCAL_AUTH_PORT)
}
fn world_port(&self, local_id: &str) -> Result<u16>;
}
@@ -190,7 +148,7 @@ impl Session {
}
const MAX_REQUESTS_PER_SESSION: u32 = 60;
const MAX_TRANSFER_CHUNKS_PER_SESSION: u32 = 2048;
const MAX_TRANSFER_CHUNKS_PER_SESSION: u32 = 128;
const LINK_FAILURES: usize = 5;
const LINK_WINDOW: Duration = Duration::from_secs(600);
@@ -223,8 +181,6 @@ fn err(code: AppError, message: &str) -> Response {
fn unavailable(what: &str, e: &Error) -> Response {
tracing::warn!(error = %e, "{what}");
#[cfg(test)]
eprintln!("{what}: {e}");
err(
AppError::Unavailable,
"The server could not do that right now.",
@@ -266,10 +222,6 @@ impl HostService {
self.realm_id
}
pub fn local_auth_port(&self) -> Result<u16> {
self.backend.auth_port(&self.local_id)
}
pub fn local_world_port(&self) -> Result<u16> {
self.backend.world_port(&self.local_id)
}
@@ -294,12 +246,7 @@ impl HostService {
public_key: &str,
request: Request,
) -> Response {
if matches!(
request,
Request::TransferChunk { .. }
| Request::SessionRead { .. }
| Request::SessionAck { .. }
) {
if matches!(request, Request::TransferChunk { .. }) {
session.transfer_chunks += 1;
if session.transfer_chunks > MAX_TRANSFER_CHUNKS_PER_SESSION {
return err(
@@ -378,26 +325,6 @@ impl HostService {
content_hash,
total_size,
collections,
false,
),
Request::OwnedTransferOffer {
transfer_id,
character_id,
ruleset,
canonical_revision,
content_hash,
total_size,
collections,
} => self.transfer_offer(
player,
transfer_id,
character_id,
ruleset,
canonical_revision,
content_hash,
total_size,
collections,
true,
),
Request::TransferChunk {
transfer_id,
@@ -410,32 +337,6 @@ impl HostService {
transfer_id,
character_id,
} => self.transfer_ack(player, transfer_id, character_id),
Request::SessionPoll {
character_id,
session_id,
} => self.session_poll(player, character_id, session_id),
Request::SessionRead {
character_id,
session_id,
message_hash,
offset,
} => self.session_read(player, character_id, session_id, &message_hash, offset),
Request::SessionAck {
character_id,
session_id,
message_hash,
offset,
total_size,
data,
} => self.session_ack_chunk(
player,
character_id,
session_id,
&message_hash,
offset,
total_size,
&data,
),
Request::AllocateRelay { player_id } => {
self.allocate_relay(session, player, &player_id)
}
@@ -841,7 +742,6 @@ impl HostService {
content_hash: String,
total_size: usize,
collections: BTreeMap<String, Vec<u32>>,
owned_session: bool,
) -> Response {
let Ok(_guard) = self.write.lock() else {
return err(AppError::Unavailable, "Busy.");
@@ -892,41 +792,6 @@ impl HostService {
}
}
// An exact committed retry returns its saved result before transient presence or compatibility checks.
if let Ok(Some(existing)) = self
.store
.lock()
.map_err(|_| Error::Invalid("lock".into()))
.and_then(|s| s.host_transfer_latest(&self.local_id, &character_id))
{
if existing.player_id != *player {
return err(
AppError::NotYours,
"This character's transfer belongs to another player.",
);
}
if existing.state != TransferState::Receiving
&& (!owned_session || existing.transfer_id == transfer_id)
&& existing.player_id == *player
&& existing.ruleset == ruleset
&& existing.total_size == total_size
&& existing.collections == collections
&& existing.revision == canonical_revision
&& existing.content_hash == content_hash
{
if let (Some(guid), Some(sid)) = (existing.local_guid, existing.session_id) {
return Response::TransferCommitted {
transfer_id,
character_id,
local_guid: guid,
session_id: sid,
projected_level: existing.projected_level,
notes: existing.notes,
};
}
}
}
// 2. Active session conflict: if account is online with active characters
match self.backend.presence(&self.local_id, m.account_id) {
Ok(p) if p.account_online && p.online_characters > 0 => {
@@ -954,6 +819,30 @@ impl HostService {
_ => {}
}
// 4. Idempotency / already committed check
if let Ok(Some(existing)) = self
.store
.lock()
.map_err(|_| Error::Invalid("lock".into()))
.and_then(|s| s.host_transfer_latest(&self.local_id, &character_id))
{
if existing.state != TransferState::Receiving
&& existing.revision == canonical_revision
&& existing.content_hash == content_hash
{
if let (Some(guid), Some(sid)) = (existing.local_guid, existing.session_id) {
return Response::TransferCommitted {
transfer_id,
character_id,
local_guid: guid,
session_id: sid,
projected_level: existing.projected_level,
notes: existing.notes,
};
}
}
}
// 5. Resume check for this specific transfer_id
if let Ok(Some(cur)) = self
.store
@@ -1210,7 +1099,6 @@ impl HostService {
};
let params = RemoteImportParams {
session_id: t.transfer_id,
character_id: t.character_id,
revision: t.revision,
payload,
@@ -2370,82 +2258,6 @@ mod tests {
);
}
#[test]
fn committed_transfer_retry_survives_presence_and_compatibility_changes() {
let (realm, service, player, account) = claimed_setup();
let character = Uuid::now_v7();
let session_id = Uuid::now_v7();
let (payload, hash) = test_snapshot(character, crate::portable::Ruleset::Coa);
let transfer = HostTransfer {
realm_local_id: service.local_id.clone(),
transfer_id: Uuid::now_v7(),
character_id: character,
ruleset: "coa".into(),
player_id: player,
revision: 7,
content_hash: hash.clone(),
total_size: payload.len(),
received_size: payload.len(),
state: TransferState::Committed,
local_guid: Some(3012),
session_id: Some(session_id),
projected_level: Some(60),
notes: vec![],
collections: BTreeMap::new(),
};
service
.store
.lock()
.unwrap()
.host_transfer_save(&transfer)
.unwrap();
realm.incompatible.lock().unwrap().insert(character);
realm.online.lock().unwrap().insert(
account,
Presence {
account_online: true,
online_characters: 1,
},
);
let offer = || Request::TransferOffer {
transfer_id: Uuid::now_v7(),
character_id: character,
ruleset: "coa".into(),
canonical_revision: 7,
content_hash: hash.clone(),
total_size: payload.len(),
collections: BTreeMap::new(),
};
assert!(
matches!(service.handle(&mut Session::default(), &player, "K", offer()),
Response::TransferCommitted { local_guid: 3012, session_id: returned, .. } if returned == session_id)
);
let mut different = transfer;
different.player_id = Uuid::now_v7();
different.transfer_id = Uuid::now_v7();
different.character_id = Uuid::now_v7();
service
.store
.lock()
.unwrap()
.host_transfer_save(&different)
.unwrap();
let foreign_offer = Request::TransferOffer {
transfer_id: Uuid::now_v7(),
character_id: different.character_id,
ruleset: "coa".into(),
canonical_revision: 7,
content_hash: hash.clone(),
total_size: payload.len(),
collections: BTreeMap::new(),
};
assert!(matches!(
service.handle(&mut Session::default(), &player, "K", foreign_offer),
Response::Error { .. }
));
assert!(realm.imported.lock().unwrap().is_empty());
}
#[test]
fn wrong_player_identity_cannot_overwrite_another_players_realm_copy() {
let (_realm, s, p, _acc) = claimed_setup();
@@ -1,209 +0,0 @@
//! Authenticated, bounded transport for the existing Owner/Host session messages.
use super::*;
use base64::{engine::general_purpose::STANDARD as B64, Engine};
use sha2::{Digest, Sha256};
use std::io::Write;
fn digest(bytes: &[u8]) -> String {
hex::encode(Sha256::digest(bytes))
}
impl HostService {
fn session_account(&self, player: &Uuid, character: Uuid) -> Option<u32> {
let mapping = self.mapping(player)?;
let transfer = self
.store
.lock()
.ok()?
.host_transfer_latest(&self.local_id, &character)
.ok()??;
(transfer.player_id == *player && transfer.state != TransferState::Receiving)
.then_some(mapping.account_id)
}
pub(super) fn session_poll(&self, player: &Uuid, character: Uuid, session: Uuid) -> Response {
let Some(account) = self.session_account(player, character) else {
return err(
AppError::NotYours,
"This portable session does not belong to this player.",
);
};
match self
.backend
.session_message(&self.local_id, character, session, account)
{
Ok(RemoteSessionState {
message: Some(message),
..
}) => Response::SessionPending {
kind: message.kind,
total_size: message.bytes.len(),
content_hash: digest(&message.bytes),
},
Ok(state) => Response::SessionIdle {
closed: state.closed,
},
Err(error) => unavailable("reading portable session", &error),
}
}
pub(super) fn session_read(
&self,
player: &Uuid,
character: Uuid,
session: Uuid,
expected: &str,
offset: usize,
) -> Response {
let Some(account) = self.session_account(player, character) else {
return err(
AppError::NotYours,
"This portable session does not belong to this player.",
);
};
let message =
match self
.backend
.session_message(&self.local_id, character, session, account)
{
Ok(state) => match state.message {
Some(message) => message,
None => {
return err(
AppError::Conflict,
"The portable session message changed; retry.",
)
}
},
Err(error) => return unavailable("reading portable session", &error),
};
if digest(&message.bytes) != expected || offset > message.bytes.len() {
return err(
AppError::Conflict,
"The portable session message changed; retry.",
);
}
let end = message.bytes.len().min(offset.saturating_add(24 * 1024));
Response::SessionData {
offset,
data: B64.encode(&message.bytes[offset..end]),
}
}
pub(super) fn session_ack_chunk(
&self,
player: &Uuid,
character: Uuid,
session: Uuid,
expected: &str,
offset: usize,
total_size: usize,
data: &str,
) -> Response {
let Ok(_guard) = self.write.lock() else {
return err(AppError::Unavailable, "Busy.");
};
let Some(account) = self.session_account(player, character) else {
return err(
AppError::NotYours,
"This portable session does not belong to this player.",
);
};
if expected.len() != 64
|| !expected.bytes().all(|b| b.is_ascii_hexdigit())
|| total_size == 0
|| total_size > app::MAX_SESSION_BYTES
|| offset > total_size
|| data.len() > 48 * 1024
{
return err(AppError::Invalid, "Invalid acknowledgement bounds.");
}
let bytes = match B64.decode(data) {
Ok(bytes) if bytes.len() <= total_size - offset => bytes,
_ => return err(AppError::Invalid, "Invalid acknowledgement chunk."),
};
let directory = std::env::temp_dir()
.join("coa-session-acks")
.join(digest(self.local_id.as_bytes()));
if let Err(error) = std::fs::create_dir_all(&directory) {
return unavailable("preparing session acknowledgement", &Error::from(error));
}
let path = directory.join(format!("{character}-{session}.part"));
let state = match self
.backend
.session_message(&self.local_id, character, session, account)
{
Ok(state) => state,
Err(error) => return unavailable("reading portable session", &error),
};
let Some(message) = state.message else {
let _ = std::fs::remove_file(&path);
return Response::SessionAcked {
received_size: total_size,
complete: true,
};
};
if digest(&message.bytes) != expected {
return err(
AppError::Conflict,
"The portable session message changed; retry.",
);
}
// Bind one partial file to the precise message and acknowledgement length.
let mut header = expected.as_bytes().to_vec();
header.extend_from_slice(&(total_size as u64).to_le_bytes());
let write = (|| -> Result<usize> {
if offset == 0 {
let mut file = std::fs::File::create(&path)?;
file.write_all(&header)?;
}
let current = std::fs::read(&path)?;
if !current.starts_with(&header) {
return Err(Error::Invalid(
"The acknowledgement changed; restart it.".into(),
));
}
let received = current.len() - header.len();
if received != offset {
return Ok(received);
}
let mut file = std::fs::OpenOptions::new().append(true).open(&path)?;
file.write_all(&bytes)?;
file.sync_all()?;
Ok(received + bytes.len())
})();
let received = match write {
Ok(received) => received,
Err(error) => return unavailable("saving portable acknowledgement", &error),
};
if received != total_size {
return Response::SessionAcked {
received_size: received,
complete: false,
};
}
let complete = match std::fs::read(&path) {
Ok(bytes) => bytes,
Err(error) => {
return unavailable("reading portable acknowledgement", &Error::from(error))
}
};
match self.backend.session_ack(
&self.local_id,
character,
session,
account,
message.kind,
&complete[header.len()..],
) {
Ok(()) => {
let _ = std::fs::remove_file(&path);
Response::SessionAcked {
received_size: total_size,
complete: true,
}
}
Err(error) => unavailable("applying portable acknowledgement", &error),
}
}
}
-113
View File
@@ -72,13 +72,6 @@ CREATE TABLE IF NOT EXISTS host_transfer(
updated_at TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS host_transfer_char ON host_transfer(realm_local_id, character_id);
CREATE TABLE IF NOT EXISTS player_remote_session(
character_id TEXT PRIMARY KEY,
realm_id TEXT NOT NULL,
session_id TEXT NOT NULL,
public_key TEXT NOT NULL,
coordinator TEXT NOT NULL
);
";
fn now() -> String {
@@ -184,15 +177,6 @@ pub struct PlayerRealm {
pub kind: AccountKind,
}
#[derive(Clone, Debug)]
pub struct PlayerRemoteSession {
pub character_id: Uuid,
pub realm_id: String,
pub session_id: Uuid,
pub public_key: String,
pub coordinator: String,
}
pub struct ControlStore {
conn: Connection,
}
@@ -202,66 +186,6 @@ fn uuid(s: String) -> Result<Uuid> {
}
impl ControlStore {
pub fn player_remote_sessions(&self) -> Result<Vec<PlayerRemoteSession>> {
let mut statement = self.conn.prepare("SELECT character_id, realm_id, session_id, public_key, coordinator FROM player_remote_session ORDER BY character_id").map_err(db)?;
let rows = statement
.query_map([], |row| {
Ok((
row.get::<_, String>(0)?,
row.get::<_, String>(1)?,
row.get::<_, String>(2)?,
row.get::<_, String>(3)?,
row.get::<_, String>(4)?,
))
})
.map_err(db)?;
rows.map(|row| {
let (character, realm_id, session, public_key, coordinator) = row.map_err(db)?;
Ok(PlayerRemoteSession {
character_id: uuid(character)?,
realm_id,
session_id: uuid(session)?,
public_key,
coordinator,
})
})
.collect()
}
pub fn player_remote_session_set(&self, session: &PlayerRemoteSession) -> Result<()> {
if self.player_remote_sessions()?.iter().any(|existing| {
existing.character_id == session.character_id
&& (existing.session_id != session.session_id
|| existing.realm_id != session.realm_id
|| existing.public_key != session.public_key)
}) {
return Err(Error::Invalid(
"The character's previous remote session must finish saving first.".into(),
));
}
self.conn.execute("INSERT INTO player_remote_session(character_id, realm_id, session_id, public_key, coordinator) VALUES(?1,?2,?3,?4,?5) ON CONFLICT(character_id) DO NOTHING", params![session.character_id.to_string(), session.realm_id, session.session_id.to_string(), session.public_key, session.coordinator]).map_err(db)?;
Ok(())
}
pub fn player_remote_session_advance(
&self,
character: Uuid,
previous: Uuid,
next: Uuid,
) -> Result<()> {
self.conn.execute("UPDATE player_remote_session SET session_id=?3 WHERE character_id=?1 AND session_id=?2", params![character.to_string(), previous.to_string(), next.to_string()]).map_err(db)?;
Ok(())
}
pub fn player_remote_session_remove(&self, character: Uuid, session: Uuid) -> Result<()> {
self.conn
.execute(
"DELETE FROM player_remote_session WHERE character_id=?1 AND session_id=?2",
params![character.to_string(), session.to_string()],
)
.map_err(db)?;
Ok(())
}
pub fn open(dir: &Path) -> Result<Self> {
std::fs::create_dir_all(dir)?;
let conn = Connection::open(dir.join("control.sqlite")).map_err(db)?;
@@ -650,43 +574,6 @@ fn row_transfer(r: &rusqlite::Row<'_>) -> rusqlite::Result<Result<HostTransfer>>
mod tests {
use super::*;
#[test]
fn remote_session_survives_restart_and_cannot_be_replaced() {
let dir = tempfile::tempdir().unwrap();
let row = PlayerRemoteSession {
character_id: Uuid::now_v7(),
realm_id: "realm".into(),
session_id: Uuid::now_v7(),
public_key: "pinned-key".into(),
coordinator: "wss://example.test/coord/v1/player".into(),
};
{
let store = ControlStore::open(dir.path()).unwrap();
store.player_remote_session_set(&row).unwrap();
store.player_remote_session_set(&row).unwrap();
let mut other = row.clone();
other.session_id = Uuid::now_v7();
assert!(store.player_remote_session_set(&other).is_err());
other = row.clone();
other.public_key = "changed-key".into();
assert!(store.player_remote_session_set(&other).is_err());
}
let store = ControlStore::open(dir.path()).unwrap();
let recovered = store.player_remote_sessions().unwrap().pop().unwrap();
assert_eq!(
(recovered.session_id, recovered.public_key),
(row.session_id, row.public_key)
);
store
.player_remote_session_remove(row.character_id, Uuid::now_v7())
.unwrap();
assert_eq!(store.player_remote_sessions().unwrap().len(), 1);
store
.player_remote_session_remove(row.character_id, row.session_id)
.unwrap();
assert!(store.player_remote_sessions().unwrap().is_empty());
}
#[test]
fn a_player_owns_one_account_per_realm_and_an_account_one_player() {
let s = ControlStore::open_in_memory().unwrap();
+30 -125
View File
@@ -14,14 +14,12 @@ use crate::download::Cancel;
use crate::error::{Error, Result};
use crate::fsx;
pub const CLIENT_VERSION: &str = "1.9.2";
pub const CLIENT_VERSION: &str = "1.8.3";
pub const MANIFEST_FILENAME: &str = "custom_races_patch_manifest.txt";
pub const ARCHIVES: &[(&str, &str)] = &[
("CoA-Custom-1.9.2-Client-1.zip", "https://github.com/ilusixn/azerothcore-wotlk-coa/releases/download/coa-custom-1.9.2/CoA-Custom-1.9.2-Client-1.zip"),
("CoA-Custom-1.9.2-Client-2.zip", "https://github.com/ilusixn/azerothcore-wotlk-coa/releases/download/coa-custom-1.9.2/CoA-Custom-1.9.2-Client-2.zip"),
("CoA-Custom-1.9.2-Client-3.zip", "https://github.com/ilusixn/azerothcore-wotlk-coa/releases/download/coa-custom-1.9.2/CoA-Custom-1.9.2-Client-3.zip"),
("CoA-Custom-1.9.2-Client-4.zip", "https://github.com/ilusixn/azerothcore-wotlk-coa/releases/download/coa-custom-1.9.2/CoA-Custom-1.9.2-Client-4.zip"),
("CoA-Custom-1.9.2-Client-5.zip", "https://github.com/ilusixn/azerothcore-wotlk-coa/releases/download/coa-custom-1.9.2/CoA-Custom-1.9.2-Client-5.zip"),
("CoA-Custom-1.8.3-Client-1.zip", "https://github.com/ilusixn/azerothcore-wotlk-coa/releases/download/coa-custom-1.8.3/CoA-Custom-1.8.3-Client-1.zip"),
("CoA-Custom-1.8.3-Client-2.zip", "https://github.com/ilusixn/azerothcore-wotlk-coa/releases/download/coa-custom-1.8.3/CoA-Custom-1.8.3-Client-2.zip"),
("CoA-Custom-1.8.3-Client-3.zip", "https://github.com/ilusixn/azerothcore-wotlk-coa/releases/download/coa-custom-1.8.3/CoA-Custom-1.8.3-Client-3.zip"),
];
pub const RACE_MPQS: &[&str] = &[
@@ -55,15 +53,9 @@ pub const RACE_MPQS: &[&str] = &[
"patch-ZZX.MPQ",
"patch-ZZZC.MPQ",
"patch-ZZZD.MPQ",
"patch-ZZZA.MPQ",
"patch-ZZZE.MPQ",
"patch-ZZZF.MPQ",
"patch-ZZZZ.MPQ",
];
pub const RACE_ADDONS: &[&str] = &[
"CoAQuestSafe/CoAQuestSafe.lua",
"CoAQuestSafe/CoAQuestSafe.toc",
"CoAWC2Cursor/CoAWC2Cursor.lua",
"CoAWC2Cursor/CoAWC2Cursor.toc",
"CoAHideArmor/CoAHideArmor.lua",
@@ -111,13 +103,6 @@ pub fn playerbots_conf_paths(root: &Path) -> Vec<PathBuf> {
/// Checks whether playerbots are configured to allow custom races.
/// Returns true if AiPlayerbot.ExcludedBotRaces exists and does not exclude general custom races.
pub fn is_bot_custom_races_allowed(root: &Path) -> Option<bool> {
if let Ok(bytes) = fs::read(root.join("Core/configs/modules/coa_custom_races.conf")) {
if let Ok(conf) = crate::config::parser::ConfFile::parse_bytes(&bytes) {
if let Some(value) = conf.get("CoACustomRaces.BotsEnable") {
return Some(matches!(value.trim().trim_matches('"'), "1" | "true"));
}
}
}
for path in playerbots_conf_paths(root) {
if let Ok(bytes) = fs::read(&path) {
if let Ok(conf) = crate::config::parser::ConfFile::parse_bytes(&bytes) {
@@ -149,15 +134,6 @@ pub fn sync_bot_races_config(root: &Path, allow_custom_races: bool) -> Result<()
for path in playerbots_conf_paths(root) {
if let Ok(bytes) = fs::read(&path) {
if let Ok(mut conf) = crate::config::parser::ConfFile::parse_bytes(&bytes) {
if let Some(value) = conf.get("AiPlayerbot.ExcludedBotRaces") {
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);
if !owned {
continue;
}
}
conf.set(
"AiPlayerbot.ExcludedBotRaces",
&format!("\"{excluded}\""),
@@ -210,10 +186,6 @@ fn patch_files(client: &Path) -> Result<Vec<PatchFile>> {
include_str!("custom_races_hashes_1_7.json")
} else if manifest.lines().any(|line| line == "# CoA Custom 1.8") {
include_str!("custom_races_hashes_1_8.json")
} else if manifest.lines().any(|line| line == "# CoA Custom 1.8.3") {
include_str!("custom_races_hashes_1_8_3.json")
} else if manifest.lines().any(|line| line == "# CoA Custom 1.9.1") {
include_str!("custom_races_hashes_1_9_1.json")
} else {
include_str!("custom_races_hashes.json")
};
@@ -228,6 +200,11 @@ fn patch_files(client: &Path) -> Result<Vec<PatchFile>> {
}
Some(format!("Data/{name}"))
} else if let Some(name) = line.strip_prefix("ROOT:") {
if name.contains(['/', '\\']) {
return Err(Error::Invalid(
"Invalid custom races patch manifest.".into(),
));
}
Some(name.to_string())
} else {
line.strip_prefix("ADDON:")
@@ -647,37 +624,16 @@ pub fn uninstall_client_patches(client: &Path) -> Result<()> {
tx.finish()
}
fn stage_root_asset(staging: &Path, relative: &str, reader: &mut impl Read) -> Result<String> {
let dest = fsx::safe_join(staging, relative)?;
fs::create_dir_all(
dest.parent()
.ok_or_else(|| Error::Invalid("Invalid client asset path.".into()))?,
)?;
let mut output = File::create(&dest)?;
io::copy(reader, &mut output)?;
let disabled = PathBuf::from(format!("{}.disabled", dest.display()));
if disabled.is_file() {
fs::remove_file(disabled)?;
}
Ok(relative.to_string())
}
fn verify_archive(path: &Path, filename: &str) -> Result<()> {
let expected = match filename {
"CoA-Custom-1.9.2-Client-1.zip" => {
"CoA-Custom-1.8.3-Client-1.zip" => {
"a9dd51ed2d90fb048d549602f40f5429d56e2df0df5606a38781b358fa369568"
}
"CoA-Custom-1.9.2-Client-2.zip" => {
"CoA-Custom-1.8.3-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"
"CoA-Custom-1.8.3-Client-3.zip" => {
"270c7b306624bf9e5c3fe577e3bd058601221df223dd9e449ff7c25de70b9461"
}
_ => return Err(Error::Invalid("Unknown custom races archive.".into())),
};
@@ -911,8 +867,22 @@ pub fn install_client_patches(
let mut out = File::create(&dest)?;
io::copy(&mut zfile, &mut out)?;
installed_roots.push(relative);
} else if let Some(relative) = zname_norm.split("files/client_root/").nth(1) {
installed_roots.push(stage_root_asset(staging.path(), relative, &mut zfile)?);
} else if zname_norm.contains("files/client_root/") {
let base = Path::new(&zname_norm)
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default();
if !base.is_empty() {
let dest = staging.path().join(&base);
let mut out = File::create(&dest)?;
io::copy(&mut zfile, &mut out)?;
let disabled = staging.path().join(format!("{base}.disabled"));
if disabled.is_file() {
fs::remove_file(disabled)?;
}
installed_roots.push(base);
}
}
}
}
@@ -1078,56 +1048,6 @@ mod tests {
fs::remove_dir(link).unwrap();
}
#[test]
fn nested_root_manifest_remains_valid_and_rejects_traversal() {
let temp = tempfile::tempdir().unwrap();
let relative = "Data/Retail/Assets/EquipmentFitting/60-0.bin";
fs::write(
temp.path().join(MANIFEST_FILENAME),
format!("# CoA Custom {CLIENT_VERSION}\nROOT:{relative}\n"),
)
.unwrap();
assert_eq!(patch_files(temp.path()).unwrap()[0].path, relative);
fs::write(temp.path().join(MANIFEST_FILENAME), "ROOT:../outside.bin\n").unwrap();
assert!(patch_files(temp.path()).is_err());
}
#[test]
fn previous_split_release_retains_its_original_hash_inventory() {
let temp = tempfile::tempdir().unwrap();
fs::write(temp.path().join(MANIFEST_FILENAME), "# CoA Custom 1.8.3\n").unwrap();
let old: std::collections::BTreeMap<String, String> =
serde_json::from_str(include_str!("custom_races_hashes_1_8_3.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)));
}
#[test]
fn previous_191_release_keeps_its_hashes_and_does_not_claim_new_addons() {
let temp = tempfile::tempdir().unwrap();
fs::write(temp.path().join(MANIFEST_FILENAME), "# CoA Custom 1.9.1\n").unwrap();
let old: std::collections::BTreeMap<String, String> =
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().any(|file| file.path.contains("CoAQuestSafe")));
}
#[test]
fn root_assets_preserve_nested_paths_and_reject_traversal() {
let temp = tempfile::tempdir().unwrap();
let relative = "Data/Retail/Assets/EquipmentFitting/60-0.bin";
let result = stage_root_asset(temp.path(), relative, &mut &b"fitting"[..]).unwrap();
assert_eq!(result, relative);
assert_eq!(fs::read(temp.path().join(relative)).unwrap(), b"fitting");
assert!(!temp.path().join("60-0.bin").exists());
assert!(stage_root_asset(temp.path(), "../outside.bin", &mut &b"bad"[..]).is_err());
}
#[test]
#[cfg(windows)]
fn shared_addons_junction_supports_install_switch_and_rollback() {
@@ -1637,7 +1557,7 @@ mod tests {
let temp = tempfile::tempdir().unwrap();
let conf = temp.path().join("Core/configs/modules/playerbots.conf");
fs::create_dir_all(conf.parent().unwrap()).unwrap();
fs::write(&conf, "AiPlayerbot.Enabled = 1\n").unwrap();
fs::write(&conf, "AiPlayerbot.ExcludedBotRaces = \"\"\n").unwrap();
sync_bot_races_config(temp.path(), false).unwrap();
assert_eq!(is_bot_custom_races_allowed(temp.path()), Some(false));
let parsed =
@@ -1655,19 +1575,4 @@ mod tests {
);
}
}
#[test]
fn bot_race_sync_preserves_user_and_crashing_exclusions() {
let temp = tempfile::tempdir().unwrap();
let conf = temp.path().join("Core/configs/modules/playerbots.conf");
fs::create_dir_all(conf.parent().unwrap()).unwrap();
for value in ["", "1,82,97", EXCLUDED_BOT_RACES_RECOMMENDED] {
let original = format!("AiPlayerbot.ExcludedBotRaces = \"{value}\"\nAiPlayerbot.CrashingBotRaces = \"72,77,97\"\n");
fs::write(&conf, &original).unwrap();
sync_bot_races_config(temp.path(), true).unwrap();
assert_eq!(fs::read_to_string(&conf).unwrap(), original);
sync_bot_races_config(temp.path(), false).unwrap();
assert_eq!(fs::read_to_string(&conf).unwrap(), original);
}
}
}
+8 -51
View File
@@ -1,20 +1,5 @@
{
"Ascension.exe": "e2c347019d554a59639e5978fd68e50e906973ab313c6573cc56ca82e8e3c547",
"Data/Retail/Assets/EquipmentFitting/1068-1.bin": "332d2c38b037a118f262bbb3096a01ebfb33c5347e96bbfb64157437b300281b",
"Data/Retail/Assets/EquipmentFitting/60-0.bin": "ffbf6efc9ea09b0c442f048c5bc7b4c5975258045cfddedd9a77a93363312b5e",
"Data/Retail/Assets/EquipmentFitting/60-1.bin": "36ceed2a55756f3322e018938809acea5124351161405058ef27d100173778da",
"Data/Retail/Assets/EquipmentFitting/61-0.bin": "3b302a4055d1e795c451b02e38dfe8007527ee1bc5f926ebcd6ef17f433cd232",
"Data/Retail/Assets/EquipmentFitting/61-1.bin": "c42df399ed99be3c7ce1b5fdb95a873711011713a4cd867bc226a14b1ce0e8ca",
"Data/Retail/Assets/EquipmentFitting/65-0.bin": "8ce3f884ae197d14dff0f955c2cf05abb716742c8aff79f7af1cec5cf7225f04",
"Data/Retail/Assets/EquipmentFitting/68-0.bin": "f1d878f0f943cbdb8025af8daac4a38c1d1e159bd961d9d76f225931c11648ac",
"Data/Retail/Assets/EquipmentFitting/68-1.bin": "2ccbae634384200340c0cc3dca36a7a014a8ddad110598e4470ff1b266576465",
"Data/Retail/Assets/EquipmentFitting/73-0.bin": "5530882678f677ad47987ce906e851338a35f7d9737e3f9d829938027b8af67f",
"Data/Retail/Assets/EquipmentFitting/74-0.bin": "53a7be86b3bfdd6995406c706df3ca091484206d8141cebb39113c714500384a",
"Data/Retail/Assets/EquipmentFitting/74-1.bin": "e688c55a355231978d42480a003c26d379460f5931c2469c119ecb073ea153e1",
"Data/Retail/Assets/EquipmentFitting/75-0.bin": "289abc71c6df0e031a64d62a40e658eaefd37e45373a062ca52f08fbe803500c",
"Data/Retail/Assets/EquipmentFitting/76-0.bin": "63a493e70b91f59ff49f1942d959df986062bd267fe2ba589f344963df771021",
"Data/Retail/Assets/EquipmentFitting/77-0.bin": "b1366ce0dc4f31cb8c8c9705be2da565df4b905224af04b6b88f8c8e9c87e3c9",
"Data/Retail/Assets/EquipmentFitting/78-0.bin": "7b0031fb12ab19020005bdccacca2dd3991349c36949a58b035992585b4134db",
"Data/patch-T.MPQ": "fe597138ab7f56881b5f4f27d6dc9d81bb278b483ca0d91b7207ffd4a5ae7bfd",
"Data/patch-ZE1.MPQ": "69d79dbbea54ec0312c37770debc79c7bc9ce2e21eedef99c03cd8d911955283",
"Data/patch-ZE2.MPQ": "1a41cae77ad730e9cf69e8d63fd12ae3a579418bb550d351fff469573a97ac3c",
@@ -37,48 +22,28 @@
"Data/patch-ZZE.MPQ": "4b1e289e12c82644cb78f50170e6b5fd53918eb2de834f9e0cebddd81873a8bb",
"Data/patch-ZZR.MPQ": "5a7575e592dc0c8a6913e0d946bbe06fa0ca2e4d817ef1f8548d3d13142bcbd3",
"Data/patch-ZZS.MPQ": "533fd69d5784d83e872a5a28d27301dc9ab5d0cb925f8b2116926854e4a0a5b8",
"Data/patch-ZZT.MPQ": "e60dab63fe5650fdf5f0846ea6d4136219293bcfdad46d9b796697faeff9ab4c",
"Data/patch-ZZU.MPQ": "0311de8f034eae7dec1bd2c92b1fe6c741cbaf53da62c7609cd12b6c37908e47",
"Data/patch-ZZV.MPQ": "3b04008905e7185d165827d68f7ca228dda8272816364f7d71874ecc83b64f0e",
"Data/patch-ZZW.MPQ": "3bbbc72901fd2d662113036485c380701e693f5a39ba9479af306bf2fa2030bd",
"Data/patch-ZZT.MPQ": "aef3bbe4951333d62fb55224484724fbaa9c35773a19944ffb9935e250cfb59c",
"Data/patch-ZZU.MPQ": "8ee1839415b56d46c6eff7eb4dfbaf6fbafc4c6b29b39380d69f4d827d02a99e",
"Data/patch-ZZV.MPQ": "8d5e61d37008abf70478e5d5f46ec7afb0490b9a643323bd75a1c70cadd63290",
"Data/patch-ZZW.MPQ": "3689c485f8ee8fccaa6dbae1d073bc9231229f9a040f79a272d80a87486d0c33",
"Data/patch-ZZX.MPQ": "4c12608089cfe356f7c8882d66db90239ed3ec8ddd980d91d7a3a488680f3c88",
"Data/patch-ZZZ.MPQ": "566aaadf501af42e29a828b1bc2edbd36d436288fb309fe423bd74b9619bf593",
"Data/patch-ZZZA.MPQ": "57ccbdc0a66000767554ffd194088df6d602ddd8341a141bca8201e7d5435889",
"Data/patch-ZZZC.MPQ": "691a53f6325c2615a64ced0802f18bc4d96e99c62aaa606fc930f9406ee74cdf",
"Data/patch-ZZZD.MPQ": "ca893cf8129f6fd442a63f0697a8ddea88546e3ce71bde713be2cc832b892bc9",
"Data/patch-ZZZE.MPQ": "2e245ee0fe3b913087eed399062fda5843d98b04afac38024f7c64ac3bf43e18",
"Data/patch-ZZZF.MPQ": "40eac695cfcafb598b8376f3b9a61ecc037e4d445b87279cfe387a91edad32c3",
"Data/patch-ZZZZ.MPQ": "860c990db3b4185fdc36e1a001d3ca3507a68253a4506793a115f86eb0892a15",
"Data/patch-ZZZD.MPQ": "e4ce9d8b363eb609d0d6d92627eb53454fa2e03e4dbc1795b3573a22b7d009c8",
"EsteriaAppearance.bin": "90d9cfaeaf6de10f014f1d1610ea10453ec9b240255759aea99513cac488a3ec",
"EsteriaAppearance.dll": "88e268d3be9eca3b0644f543d823f4bdcc04a9700a6e8ed73fd2a1260ad191af",
"EsteriaAppearance.dll": "196a82f24dd287653e2b2fc4d12bfc796f8ee3f6687ca8308905a5ab528a51a9",
"EsteriaAppearanceGeometry.bin": "19de5b4b4f79778ea5316659efc2f66c6edb6b5149c46efa47c46bfa4ec6904c",
"EsteriaAppearanceMaterials.bin": "f72f027f54a55c05aa0f76b457b97b484fe0e1aedc0e068cc0e0ca53e1878cba",
"EsteriaBanshee.bin": "d3fe66caa6a0ecba96bddb07ac1cbdb915694e87fc1608da0fdabecdf9ffea4d",
"EsteriaBansheeTextures.bin": "837774377ca055e6a5c79c1a4cfd8151e7c1f7ce2c16990b00fd445281137433",
"EsteriaCentaur.bin": "d63f0b7d21cee67d234d134e832fe6d55c398f2b63f9f6c191dcfa9671637185",
"EsteriaCentaurTextures.bin": "837774377ca055e6a5c79c1a4cfd8151e7c1f7ce2c16990b00fd445281137433",
"EsteriaCosmeticWings.bin": "57352c28459d073a29b3014d33b70f3b3756afa37fa9583ef6b30d503422ac3f",
"EsteriaDrakonid.bin": "95440ee9c065ef20bb7fed6158d20623d68745291cedc2726fc746ff54601f95",
"EsteriaDrakonidCoverage.bin": "9cdc227f08329e1245d2b864a996e7a772c96ecdbe5d81925f4d60cdbe4fa11e",
"EsteriaDrakonidTextures.bin": "1ba9133a75dad291d98a068b2dcde01f31a897a1764cd7f3e2c316c288a8f605",
"EsteriaEarthen.bin": "8a0db93ba2d5c756b44ed84f2f7bc7c15eef13be6a7d87baf1383c6c0c624e02",
"EsteriaEthereal.bin": "ada3b7588511a847dd5154d91e3041e9f7f193998b06bfede5e0afc32570b48c",
"EsteriaEtherealTextures.bin": "837774377ca055e6a5c79c1a4cfd8151e7c1f7ce2c16990b00fd445281137433",
"EsteriaFaceless.bin": "1c5a1d7a6b1db6984a8e41bc4804e9f7c50d65dcdbb8c0a9d1a9e8af8c91bd8f",
"EsteriaFacelessTextures.bin": "837774377ca055e6a5c79c1a4cfd8151e7c1f7ce2c16990b00fd445281137433",
"EsteriaGnoll.bin": "cfacc8e681bb8e54a4f01ee9c12a91bf0bd23a23527bb548d4dc21ec1b33eea2",
"EsteriaGnollTextures.bin": "1ba9133a75dad291d98a068b2dcde01f31a897a1764cd7f3e2c316c288a8f605",
"EsteriaHaranir.bin": "59f31d00e372fd2646e1cf0d9d3d5d671b31edd60ff7b862f8d1ce7e53ba1f2f",
"EsteriaHaranirTextures.bin": "99948ca570be2d376f0c67e3b8088739b6fa9f9d2c73985e19f68df77689a229",
"EsteriaHighmountain.bin": "e83349252ad2687ac23fcfc5623db7401cf32e5faf47a5a7be20c2f94b014938",
"EsteriaHozen.bin": "739bc3775388976f5c09bcbf3a98b62d804dff78d545e25a41d07dd99b5fddc5",
"EsteriaHozenTextures.bin": "837774377ca055e6a5c79c1a4cfd8151e7c1f7ce2c16990b00fd445281137433",
"EsteriaKvItems.bin": "fc5f9d86114234b38dbb0e14a6a5ec16249eaa92a73411a7fc371a950549dcce",
"EsteriaKvSkins.bin": "60b2b899f5f83137368514928f92f3b04c0fae058f534c487ddbe913ee4bec18",
"EsteriaKyrian.bin": "9329147f08805ff4003f9e062fea7c6ea8fdd8c4d6a40de63a6d228ebe1b7c9a",
"EsteriaKyrianTextures.bin": "837774377ca055e6a5c79c1a4cfd8151e7c1f7ce2c16990b00fd445281137433",
"EsteriaMantid.bin": "71536dee6c2abd0b0e13f33bc73cad7e6fb1b0fc1f6912a95c55d57bc7ee1787",
"EsteriaMantidTextures.bin": "837774377ca055e6a5c79c1a4cfd8151e7c1f7ce2c16990b00fd445281137433",
"EsteriaNaga.bin": "e87547cff5d09500c294f8b06935d134cdd0bbb962e294a72de09404505bd8b3",
"EsteriaNagaTextures.bin": "57ec560f99c1d48ac1e8f6a797c156513b99e7d349e3071afe405f812d159ae3",
"EsteriaSaberon.bin": "7735c9325c807c5125760d87f323d6b7d4162fb542c1d8b5f435ea2d6b9a4daa",
@@ -86,26 +51,18 @@
"EsteriaSaberonTextures.bin": "1ba9133a75dad291d98a068b2dcde01f31a897a1764cd7f3e2c316c288a8f605",
"EsteriaSethrak.bin": "bd14857a8c11fdf8027128763293701586b2102f9a6539d33a727014789fd606",
"EsteriaSethrakTextures.bin": "d2b2cf58087a391f00198008fe871edd400ddf28d54a3a05674df74c5198528a",
"EsteriaSlime.bin": "491e942ceb6abda83c0249afebae7c9c43af3897b35e45fa33d6f9177ecbc177",
"EsteriaSlimeTextures.bin": "837774377ca055e6a5c79c1a4cfd8151e7c1f7ce2c16990b00fd445281137433",
"EsteriaTarasek.bin": "f718444d5ec36f7aff018883486ae1981151fe6e01f5b7781d68d74e9fadfa47",
"EsteriaTarasekTextures.bin": "1ba9133a75dad291d98a068b2dcde01f31a897a1764cd7f3e2c316c288a8f605",
"EsteriaThinHuman.bin": "bc12e5ca2c087ca0a8642ff6cd8e78fe2e1f85928518b12c19b4245a8320585d",
"EsteriaThinHumanTextures.bin": "27488a7494fa9733b53118d1d0f4acef50a9e19004f81f9c8a614b10f4c3fd5e",
"EsteriaThinHuman.bin": "75794d192ea0c228b3da7bf7d0bdff1119f79d3f9bfef6650cd5e1a2b5d106eb",
"EsteriaThinHumanTextures.bin": "02aeb4c05893d06125b8b58fdb7c2a56fe3d66a7d094706a44b43cb503d1731e",
"EsteriaTuskarr.bin": "ecbe7ef490ba67eca029a57639192db61238522618491549766fe38529914387",
"EsteriaTuskarrTextures.bin": "e2116c2c83adea079126fd5da765d20da24f044d4f161c4124e4368cb3d6bc71",
"EsteriaVenthyr.bin": "5bcf7804363e59b3c922830d06de17bbd348b9967307f39b7d72bc09f58814eb",
"EsteriaVenthyrTextures.bin": "837774377ca055e6a5c79c1a4cfd8151e7c1f7ce2c16990b00fd445281137433",
"EsteriaVorkai.bin": "d6d2088c7e867b5db437e9afc2d323c22d830c6f84a3598415eedcaa27e2461f",
"EsteriaVorkaiTextures.bin": "837774377ca055e6a5c79c1a4cfd8151e7c1f7ce2c16990b00fd445281137433",
"EsteriaVrykul.bin": "39e2b7b4c67997dbbd34bae840bd606a59290f7f2fc82565a0ba00090335415c",
"EsteriaVrykulTextures.bin": "46098750a0e235724c6e9cc8d9d4e26550aa47bef95fd5f0f82efe5e945bf296",
"EsteriaVulpera.bin": "c5434993b9af4a17d881965e4735cd2ac379e39c7142aac9844adff9528562d4",
"EsteriaVulperaTextures.bin": "1ab844e74684aced2b069f1b91cd563aade45e05bd5e23f866a6c0c301cb098e",
"Interface/AddOns/CoAHideArmor/CoAHideArmor.lua": "8c1c7403524fc9bd56c0809b4101b141da700ba163701209bf1420f2ef106aa7",
"Interface/AddOns/CoAHideArmor/CoAHideArmor.toc": "123580d92fd5ceee258e96296f42c359b7e83cdff151af49c50c6c4e2059677c",
"Interface/AddOns/CoAQuestSafe/CoAQuestSafe.lua": "062de55c91228971553f482fd2c8753f4752993b4e8e49d4ded04fa18b98bde7",
"Interface/AddOns/CoAQuestSafe/CoAQuestSafe.toc": "890bb9d1087e236f4823603f5df3ab0e316dbb65c28feebbda08fb0ab53a408f",
"Interface/AddOns/CoAWC2Cursor/CoAWC2Cursor.lua": "1cf9537ff5f10b77250fea4407aea1008da690afe102ed6ed2dac21f79638cfa",
"Interface/AddOns/CoAWC2Cursor/CoAWC2Cursor.toc": "48ce695dce712b3643ebe13a77e318d623c964acc69479b8fc8cc675099801bf",
"Interface/AddOns/CoA_TalentReset/CoA_TalentReset.lua": "827d756d5948ef918fafaf8b869290b3a1faa4e4cc21b19b512a00d4509f3d41",
@@ -1,73 +0,0 @@
{
"Ascension.exe": "e2c347019d554a59639e5978fd68e50e906973ab313c6573cc56ca82e8e3c547",
"Data/patch-T.MPQ": "fe597138ab7f56881b5f4f27d6dc9d81bb278b483ca0d91b7207ffd4a5ae7bfd",
"Data/patch-ZE1.MPQ": "69d79dbbea54ec0312c37770debc79c7bc9ce2e21eedef99c03cd8d911955283",
"Data/patch-ZE2.MPQ": "1a41cae77ad730e9cf69e8d63fd12ae3a579418bb550d351fff469573a97ac3c",
"Data/patch-ZE3.MPQ": "b587202c21b6f580682b601b7c2e905fbfa766276e74733db55c1bddbffb7f87",
"Data/patch-ZE5.MPQ": "476b5a1fcf69f64fdb281e3b445362b936d016066ccd12f897acfcf200d6c0cf",
"Data/patch-ZE6.MPQ": "762592c9ed950b4a7b6c7d85d45050b30fa3f35d53e348ee1e1516fdbb7e5484",
"Data/patch-ZE7.MPQ": "de54b0189d242763d2872223419a259b6b8a4b380c24b50a2ef9c6fa44466248",
"Data/patch-ZE8.MPQ": "1bc5691fb84a84f3e7a0a70baaa9192a97b4ec5906ee37c85838ffe08adef934",
"Data/patch-ZE9.MPQ": "d49c94463e9548e76378ce2c0454d8f204f0745c8c0de32b6dce7f0b0fd67c4a",
"Data/patch-ZEA.MPQ": "78fd10ec5262ae2417eba9700d2172553bbc1e5cfb0b597aada8f1753ca46d9d",
"Data/patch-ZES.MPQ": "a2d9348f917f745c7aa25b2eed96efa312f7b2d2f62cb86a4f2eaabc2dfa895f",
"Data/patch-ZG.MPQ": "48979e1fda775f8deb47bffa48e0a468595d4c71286fee518f51dc5801c5ca39",
"Data/patch-ZH.MPQ": "5e1d2fe287053abba703d7af381e10096c6525ba477ffed3971c2fc4f93e919c",
"Data/patch-ZHA.MPQ": "0fc6ebeafe1d14192dc64bafc90bde3c49230df1297f98bf65900a3bcf953617",
"Data/patch-ZHM.MPQ": "317d3ae00f0bd674b358af07544976acb7804aa6d8b19d1788ad96030e8c9bf0",
"Data/patch-ZJ.MPQ": "f821e99add86ef68d108c5ec466328c97677d3ed52f7944e200f3fe38c13b4de",
"Data/patch-ZK.MPQ": "444d0ecb72c1e990509d53e3cfa5b7634c816733533e8a97e5d7f5653ee32cce",
"Data/patch-ZM.MPQ": "424ab1978986e854551633983a94bd15beba6328aabea8c02f98eaa32f6f0b61",
"Data/patch-ZVU.MPQ": "c679b85a2e97344395756b54d2cf6abefe4e80e74944cb55b6e573ad17b7d020",
"Data/patch-ZZE.MPQ": "4b1e289e12c82644cb78f50170e6b5fd53918eb2de834f9e0cebddd81873a8bb",
"Data/patch-ZZR.MPQ": "5a7575e592dc0c8a6913e0d946bbe06fa0ca2e4d817ef1f8548d3d13142bcbd3",
"Data/patch-ZZS.MPQ": "533fd69d5784d83e872a5a28d27301dc9ab5d0cb925f8b2116926854e4a0a5b8",
"Data/patch-ZZT.MPQ": "aef3bbe4951333d62fb55224484724fbaa9c35773a19944ffb9935e250cfb59c",
"Data/patch-ZZU.MPQ": "8ee1839415b56d46c6eff7eb4dfbaf6fbafc4c6b29b39380d69f4d827d02a99e",
"Data/patch-ZZV.MPQ": "8d5e61d37008abf70478e5d5f46ec7afb0490b9a643323bd75a1c70cadd63290",
"Data/patch-ZZW.MPQ": "3689c485f8ee8fccaa6dbae1d073bc9231229f9a040f79a272d80a87486d0c33",
"Data/patch-ZZX.MPQ": "4c12608089cfe356f7c8882d66db90239ed3ec8ddd980d91d7a3a488680f3c88",
"Data/patch-ZZZ.MPQ": "566aaadf501af42e29a828b1bc2edbd36d436288fb309fe423bd74b9619bf593",
"Data/patch-ZZZC.MPQ": "691a53f6325c2615a64ced0802f18bc4d96e99c62aaa606fc930f9406ee74cdf",
"Data/patch-ZZZD.MPQ": "e4ce9d8b363eb609d0d6d92627eb53454fa2e03e4dbc1795b3573a22b7d009c8",
"EsteriaAppearance.bin": "90d9cfaeaf6de10f014f1d1610ea10453ec9b240255759aea99513cac488a3ec",
"EsteriaAppearance.dll": "196a82f24dd287653e2b2fc4d12bfc796f8ee3f6687ca8308905a5ab528a51a9",
"EsteriaAppearanceGeometry.bin": "19de5b4b4f79778ea5316659efc2f66c6edb6b5149c46efa47c46bfa4ec6904c",
"EsteriaAppearanceMaterials.bin": "f72f027f54a55c05aa0f76b457b97b484fe0e1aedc0e068cc0e0ca53e1878cba",
"EsteriaCosmeticWings.bin": "57352c28459d073a29b3014d33b70f3b3756afa37fa9583ef6b30d503422ac3f",
"EsteriaDrakonid.bin": "95440ee9c065ef20bb7fed6158d20623d68745291cedc2726fc746ff54601f95",
"EsteriaDrakonidCoverage.bin": "9cdc227f08329e1245d2b864a996e7a772c96ecdbe5d81925f4d60cdbe4fa11e",
"EsteriaDrakonidTextures.bin": "1ba9133a75dad291d98a068b2dcde01f31a897a1764cd7f3e2c316c288a8f605",
"EsteriaEarthen.bin": "8a0db93ba2d5c756b44ed84f2f7bc7c15eef13be6a7d87baf1383c6c0c624e02",
"EsteriaGnoll.bin": "cfacc8e681bb8e54a4f01ee9c12a91bf0bd23a23527bb548d4dc21ec1b33eea2",
"EsteriaGnollTextures.bin": "1ba9133a75dad291d98a068b2dcde01f31a897a1764cd7f3e2c316c288a8f605",
"EsteriaHaranir.bin": "59f31d00e372fd2646e1cf0d9d3d5d671b31edd60ff7b862f8d1ce7e53ba1f2f",
"EsteriaHaranirTextures.bin": "99948ca570be2d376f0c67e3b8088739b6fa9f9d2c73985e19f68df77689a229",
"EsteriaHighmountain.bin": "e83349252ad2687ac23fcfc5623db7401cf32e5faf47a5a7be20c2f94b014938",
"EsteriaNaga.bin": "e87547cff5d09500c294f8b06935d134cdd0bbb962e294a72de09404505bd8b3",
"EsteriaNagaTextures.bin": "57ec560f99c1d48ac1e8f6a797c156513b99e7d349e3071afe405f812d159ae3",
"EsteriaSaberon.bin": "7735c9325c807c5125760d87f323d6b7d4162fb542c1d8b5f435ea2d6b9a4daa",
"EsteriaSaberonCoverage.bin": "9cdc227f08329e1245d2b864a996e7a772c96ecdbe5d81925f4d60cdbe4fa11e",
"EsteriaSaberonTextures.bin": "1ba9133a75dad291d98a068b2dcde01f31a897a1764cd7f3e2c316c288a8f605",
"EsteriaSethrak.bin": "bd14857a8c11fdf8027128763293701586b2102f9a6539d33a727014789fd606",
"EsteriaSethrakTextures.bin": "d2b2cf58087a391f00198008fe871edd400ddf28d54a3a05674df74c5198528a",
"EsteriaTarasek.bin": "f718444d5ec36f7aff018883486ae1981151fe6e01f5b7781d68d74e9fadfa47",
"EsteriaTarasekTextures.bin": "1ba9133a75dad291d98a068b2dcde01f31a897a1764cd7f3e2c316c288a8f605",
"EsteriaThinHuman.bin": "75794d192ea0c228b3da7bf7d0bdff1119f79d3f9bfef6650cd5e1a2b5d106eb",
"EsteriaThinHumanTextures.bin": "02aeb4c05893d06125b8b58fdb7c2a56fe3d66a7d094706a44b43cb503d1731e",
"EsteriaTuskarr.bin": "ecbe7ef490ba67eca029a57639192db61238522618491549766fe38529914387",
"EsteriaTuskarrTextures.bin": "e2116c2c83adea079126fd5da765d20da24f044d4f161c4124e4368cb3d6bc71",
"EsteriaVrykul.bin": "39e2b7b4c67997dbbd34bae840bd606a59290f7f2fc82565a0ba00090335415c",
"EsteriaVrykulTextures.bin": "46098750a0e235724c6e9cc8d9d4e26550aa47bef95fd5f0f82efe5e945bf296",
"EsteriaVulpera.bin": "c5434993b9af4a17d881965e4735cd2ac379e39c7142aac9844adff9528562d4",
"EsteriaVulperaTextures.bin": "1ab844e74684aced2b069f1b91cd563aade45e05bd5e23f866a6c0c301cb098e",
"Interface/AddOns/CoAHideArmor/CoAHideArmor.lua": "8c1c7403524fc9bd56c0809b4101b141da700ba163701209bf1420f2ef106aa7",
"Interface/AddOns/CoAHideArmor/CoAHideArmor.toc": "123580d92fd5ceee258e96296f42c359b7e83cdff151af49c50c6c4e2059677c",
"Interface/AddOns/CoAWC2Cursor/CoAWC2Cursor.lua": "1cf9537ff5f10b77250fea4407aea1008da690afe102ed6ed2dac21f79638cfa",
"Interface/AddOns/CoAWC2Cursor/CoAWC2Cursor.toc": "48ce695dce712b3643ebe13a77e318d623c964acc69479b8fc8cc675099801bf",
"Interface/AddOns/CoA_TalentReset/CoA_TalentReset.lua": "827d756d5948ef918fafaf8b869290b3a1faa4e4cc21b19b512a00d4509f3d41",
"Interface/AddOns/CoA_TalentReset/CoA_TalentReset.toc": "16298c04af68e68d6445e7a11f42aee525dd4145f85d2771ff434fb7c6e95a85",
"dinput8.dll": "f8de78606c241fb3911dce22faf68f5b9f9885b142b183c1e2c09ddc8f7e380c",
"wc2_human.cur": "f609736e29596bb386ef1597b157d211e01a86d32c2a929e256c581c37d71791",
"wc2_orc.cur": "baa512c9b9045762ba35b6e0d35b8f79c54b7649f35cc9c0e0cc8c168a1e5a97"
}
@@ -1,114 +0,0 @@
{
"Ascension.exe": "e2c347019d554a59639e5978fd68e50e906973ab313c6573cc56ca82e8e3c547",
"Data/Retail/Assets/EquipmentFitting/1068-1.bin": "332d2c38b037a118f262bbb3096a01ebfb33c5347e96bbfb64157437b300281b",
"Data/Retail/Assets/EquipmentFitting/60-0.bin": "ffbf6efc9ea09b0c442f048c5bc7b4c5975258045cfddedd9a77a93363312b5e",
"Data/Retail/Assets/EquipmentFitting/60-1.bin": "36ceed2a55756f3322e018938809acea5124351161405058ef27d100173778da",
"Data/Retail/Assets/EquipmentFitting/61-0.bin": "3b302a4055d1e795c451b02e38dfe8007527ee1bc5f926ebcd6ef17f433cd232",
"Data/Retail/Assets/EquipmentFitting/61-1.bin": "c42df399ed99be3c7ce1b5fdb95a873711011713a4cd867bc226a14b1ce0e8ca",
"Data/Retail/Assets/EquipmentFitting/65-0.bin": "8ce3f884ae197d14dff0f955c2cf05abb716742c8aff79f7af1cec5cf7225f04",
"Data/Retail/Assets/EquipmentFitting/68-0.bin": "f1d878f0f943cbdb8025af8daac4a38c1d1e159bd961d9d76f225931c11648ac",
"Data/Retail/Assets/EquipmentFitting/68-1.bin": "2ccbae634384200340c0cc3dca36a7a014a8ddad110598e4470ff1b266576465",
"Data/Retail/Assets/EquipmentFitting/73-0.bin": "5530882678f677ad47987ce906e851338a35f7d9737e3f9d829938027b8af67f",
"Data/Retail/Assets/EquipmentFitting/74-0.bin": "53a7be86b3bfdd6995406c706df3ca091484206d8141cebb39113c714500384a",
"Data/Retail/Assets/EquipmentFitting/74-1.bin": "e688c55a355231978d42480a003c26d379460f5931c2469c119ecb073ea153e1",
"Data/Retail/Assets/EquipmentFitting/75-0.bin": "289abc71c6df0e031a64d62a40e658eaefd37e45373a062ca52f08fbe803500c",
"Data/Retail/Assets/EquipmentFitting/76-0.bin": "63a493e70b91f59ff49f1942d959df986062bd267fe2ba589f344963df771021",
"Data/Retail/Assets/EquipmentFitting/77-0.bin": "b1366ce0dc4f31cb8c8c9705be2da565df4b905224af04b6b88f8c8e9c87e3c9",
"Data/Retail/Assets/EquipmentFitting/78-0.bin": "7b0031fb12ab19020005bdccacca2dd3991349c36949a58b035992585b4134db",
"Data/patch-T.MPQ": "fe597138ab7f56881b5f4f27d6dc9d81bb278b483ca0d91b7207ffd4a5ae7bfd",
"Data/patch-ZE1.MPQ": "69d79dbbea54ec0312c37770debc79c7bc9ce2e21eedef99c03cd8d911955283",
"Data/patch-ZE2.MPQ": "1a41cae77ad730e9cf69e8d63fd12ae3a579418bb550d351fff469573a97ac3c",
"Data/patch-ZE3.MPQ": "b587202c21b6f580682b601b7c2e905fbfa766276e74733db55c1bddbffb7f87",
"Data/patch-ZE5.MPQ": "476b5a1fcf69f64fdb281e3b445362b936d016066ccd12f897acfcf200d6c0cf",
"Data/patch-ZE6.MPQ": "762592c9ed950b4a7b6c7d85d45050b30fa3f35d53e348ee1e1516fdbb7e5484",
"Data/patch-ZE7.MPQ": "de54b0189d242763d2872223419a259b6b8a4b380c24b50a2ef9c6fa44466248",
"Data/patch-ZE8.MPQ": "1bc5691fb84a84f3e7a0a70baaa9192a97b4ec5906ee37c85838ffe08adef934",
"Data/patch-ZE9.MPQ": "d49c94463e9548e76378ce2c0454d8f204f0745c8c0de32b6dce7f0b0fd67c4a",
"Data/patch-ZEA.MPQ": "78fd10ec5262ae2417eba9700d2172553bbc1e5cfb0b597aada8f1753ca46d9d",
"Data/patch-ZES.MPQ": "a2d9348f917f745c7aa25b2eed96efa312f7b2d2f62cb86a4f2eaabc2dfa895f",
"Data/patch-ZG.MPQ": "48979e1fda775f8deb47bffa48e0a468595d4c71286fee518f51dc5801c5ca39",
"Data/patch-ZH.MPQ": "5e1d2fe287053abba703d7af381e10096c6525ba477ffed3971c2fc4f93e919c",
"Data/patch-ZHA.MPQ": "0fc6ebeafe1d14192dc64bafc90bde3c49230df1297f98bf65900a3bcf953617",
"Data/patch-ZHM.MPQ": "317d3ae00f0bd674b358af07544976acb7804aa6d8b19d1788ad96030e8c9bf0",
"Data/patch-ZJ.MPQ": "f821e99add86ef68d108c5ec466328c97677d3ed52f7944e200f3fe38c13b4de",
"Data/patch-ZK.MPQ": "444d0ecb72c1e990509d53e3cfa5b7634c816733533e8a97e5d7f5653ee32cce",
"Data/patch-ZM.MPQ": "424ab1978986e854551633983a94bd15beba6328aabea8c02f98eaa32f6f0b61",
"Data/patch-ZVU.MPQ": "c679b85a2e97344395756b54d2cf6abefe4e80e74944cb55b6e573ad17b7d020",
"Data/patch-ZZE.MPQ": "4b1e289e12c82644cb78f50170e6b5fd53918eb2de834f9e0cebddd81873a8bb",
"Data/patch-ZZR.MPQ": "5a7575e592dc0c8a6913e0d946bbe06fa0ca2e4d817ef1f8548d3d13142bcbd3",
"Data/patch-ZZS.MPQ": "533fd69d5784d83e872a5a28d27301dc9ab5d0cb925f8b2116926854e4a0a5b8",
"Data/patch-ZZT.MPQ": "e60dab63fe5650fdf5f0846ea6d4136219293bcfdad46d9b796697faeff9ab4c",
"Data/patch-ZZU.MPQ": "0311de8f034eae7dec1bd2c92b1fe6c741cbaf53da62c7609cd12b6c37908e47",
"Data/patch-ZZV.MPQ": "3b04008905e7185d165827d68f7ca228dda8272816364f7d71874ecc83b64f0e",
"Data/patch-ZZW.MPQ": "3bbbc72901fd2d662113036485c380701e693f5a39ba9479af306bf2fa2030bd",
"Data/patch-ZZX.MPQ": "4c12608089cfe356f7c8882d66db90239ed3ec8ddd980d91d7a3a488680f3c88",
"Data/patch-ZZZ.MPQ": "566aaadf501af42e29a828b1bc2edbd36d436288fb309fe423bd74b9619bf593",
"Data/patch-ZZZA.MPQ": "57ccbdc0a66000767554ffd194088df6d602ddd8341a141bca8201e7d5435889",
"Data/patch-ZZZC.MPQ": "691a53f6325c2615a64ced0802f18bc4d96e99c62aaa606fc930f9406ee74cdf",
"Data/patch-ZZZD.MPQ": "ca893cf8129f6fd442a63f0697a8ddea88546e3ce71bde713be2cc832b892bc9",
"Data/patch-ZZZE.MPQ": "2e245ee0fe3b913087eed399062fda5843d98b04afac38024f7c64ac3bf43e18",
"Data/patch-ZZZF.MPQ": "0e0dd0b46e5308756af779803259e2ba6c99920a01b62a01505b268c20a15bbe",
"Data/patch-ZZZZ.MPQ": "ae27e2f203755c8a74f21cabf8d3ebafd076b53452b1eb9d894fa1ce9837d0ea",
"EsteriaAppearance.bin": "90d9cfaeaf6de10f014f1d1610ea10453ec9b240255759aea99513cac488a3ec",
"EsteriaAppearance.dll": "88e268d3be9eca3b0644f543d823f4bdcc04a9700a6e8ed73fd2a1260ad191af",
"EsteriaAppearanceGeometry.bin": "19de5b4b4f79778ea5316659efc2f66c6edb6b5149c46efa47c46bfa4ec6904c",
"EsteriaAppearanceMaterials.bin": "f72f027f54a55c05aa0f76b457b97b484fe0e1aedc0e068cc0e0ca53e1878cba",
"EsteriaBanshee.bin": "d3fe66caa6a0ecba96bddb07ac1cbdb915694e87fc1608da0fdabecdf9ffea4d",
"EsteriaBansheeTextures.bin": "837774377ca055e6a5c79c1a4cfd8151e7c1f7ce2c16990b00fd445281137433",
"EsteriaCentaur.bin": "d63f0b7d21cee67d234d134e832fe6d55c398f2b63f9f6c191dcfa9671637185",
"EsteriaCentaurTextures.bin": "837774377ca055e6a5c79c1a4cfd8151e7c1f7ce2c16990b00fd445281137433",
"EsteriaCosmeticWings.bin": "57352c28459d073a29b3014d33b70f3b3756afa37fa9583ef6b30d503422ac3f",
"EsteriaDrakonid.bin": "95440ee9c065ef20bb7fed6158d20623d68745291cedc2726fc746ff54601f95",
"EsteriaDrakonidCoverage.bin": "9cdc227f08329e1245d2b864a996e7a772c96ecdbe5d81925f4d60cdbe4fa11e",
"EsteriaDrakonidTextures.bin": "1ba9133a75dad291d98a068b2dcde01f31a897a1764cd7f3e2c316c288a8f605",
"EsteriaEarthen.bin": "8a0db93ba2d5c756b44ed84f2f7bc7c15eef13be6a7d87baf1383c6c0c624e02",
"EsteriaEthereal.bin": "ada3b7588511a847dd5154d91e3041e9f7f193998b06bfede5e0afc32570b48c",
"EsteriaEtherealTextures.bin": "837774377ca055e6a5c79c1a4cfd8151e7c1f7ce2c16990b00fd445281137433",
"EsteriaFaceless.bin": "1c5a1d7a6b1db6984a8e41bc4804e9f7c50d65dcdbb8c0a9d1a9e8af8c91bd8f",
"EsteriaFacelessTextures.bin": "837774377ca055e6a5c79c1a4cfd8151e7c1f7ce2c16990b00fd445281137433",
"EsteriaGnoll.bin": "cfacc8e681bb8e54a4f01ee9c12a91bf0bd23a23527bb548d4dc21ec1b33eea2",
"EsteriaGnollTextures.bin": "1ba9133a75dad291d98a068b2dcde01f31a897a1764cd7f3e2c316c288a8f605",
"EsteriaHaranir.bin": "59f31d00e372fd2646e1cf0d9d3d5d671b31edd60ff7b862f8d1ce7e53ba1f2f",
"EsteriaHaranirTextures.bin": "99948ca570be2d376f0c67e3b8088739b6fa9f9d2c73985e19f68df77689a229",
"EsteriaHighmountain.bin": "e83349252ad2687ac23fcfc5623db7401cf32e5faf47a5a7be20c2f94b014938",
"EsteriaHozen.bin": "739bc3775388976f5c09bcbf3a98b62d804dff78d545e25a41d07dd99b5fddc5",
"EsteriaHozenTextures.bin": "837774377ca055e6a5c79c1a4cfd8151e7c1f7ce2c16990b00fd445281137433",
"EsteriaKvItems.bin": "fc5f9d86114234b38dbb0e14a6a5ec16249eaa92a73411a7fc371a950549dcce",
"EsteriaKvSkins.bin": "60b2b899f5f83137368514928f92f3b04c0fae058f534c487ddbe913ee4bec18",
"EsteriaKyrian.bin": "9329147f08805ff4003f9e062fea7c6ea8fdd8c4d6a40de63a6d228ebe1b7c9a",
"EsteriaKyrianTextures.bin": "837774377ca055e6a5c79c1a4cfd8151e7c1f7ce2c16990b00fd445281137433",
"EsteriaMantid.bin": "71536dee6c2abd0b0e13f33bc73cad7e6fb1b0fc1f6912a95c55d57bc7ee1787",
"EsteriaMantidTextures.bin": "837774377ca055e6a5c79c1a4cfd8151e7c1f7ce2c16990b00fd445281137433",
"EsteriaNaga.bin": "e87547cff5d09500c294f8b06935d134cdd0bbb962e294a72de09404505bd8b3",
"EsteriaNagaTextures.bin": "57ec560f99c1d48ac1e8f6a797c156513b99e7d349e3071afe405f812d159ae3",
"EsteriaSaberon.bin": "7735c9325c807c5125760d87f323d6b7d4162fb542c1d8b5f435ea2d6b9a4daa",
"EsteriaSaberonCoverage.bin": "9cdc227f08329e1245d2b864a996e7a772c96ecdbe5d81925f4d60cdbe4fa11e",
"EsteriaSaberonTextures.bin": "1ba9133a75dad291d98a068b2dcde01f31a897a1764cd7f3e2c316c288a8f605",
"EsteriaSethrak.bin": "bd14857a8c11fdf8027128763293701586b2102f9a6539d33a727014789fd606",
"EsteriaSethrakTextures.bin": "d2b2cf58087a391f00198008fe871edd400ddf28d54a3a05674df74c5198528a",
"EsteriaSlime.bin": "491e942ceb6abda83c0249afebae7c9c43af3897b35e45fa33d6f9177ecbc177",
"EsteriaSlimeTextures.bin": "837774377ca055e6a5c79c1a4cfd8151e7c1f7ce2c16990b00fd445281137433",
"EsteriaTarasek.bin": "f718444d5ec36f7aff018883486ae1981151fe6e01f5b7781d68d74e9fadfa47",
"EsteriaTarasekTextures.bin": "1ba9133a75dad291d98a068b2dcde01f31a897a1764cd7f3e2c316c288a8f605",
"EsteriaThinHuman.bin": "bc12e5ca2c087ca0a8642ff6cd8e78fe2e1f85928518b12c19b4245a8320585d",
"EsteriaThinHumanTextures.bin": "27488a7494fa9733b53118d1d0f4acef50a9e19004f81f9c8a614b10f4c3fd5e",
"EsteriaTuskarr.bin": "ecbe7ef490ba67eca029a57639192db61238522618491549766fe38529914387",
"EsteriaTuskarrTextures.bin": "e2116c2c83adea079126fd5da765d20da24f044d4f161c4124e4368cb3d6bc71",
"EsteriaVenthyr.bin": "5bcf7804363e59b3c922830d06de17bbd348b9967307f39b7d72bc09f58814eb",
"EsteriaVenthyrTextures.bin": "837774377ca055e6a5c79c1a4cfd8151e7c1f7ce2c16990b00fd445281137433",
"EsteriaVorkai.bin": "d6d2088c7e867b5db437e9afc2d323c22d830c6f84a3598415eedcaa27e2461f",
"EsteriaVorkaiTextures.bin": "837774377ca055e6a5c79c1a4cfd8151e7c1f7ce2c16990b00fd445281137433",
"EsteriaVrykul.bin": "39e2b7b4c67997dbbd34bae840bd606a59290f7f2fc82565a0ba00090335415c",
"EsteriaVrykulTextures.bin": "46098750a0e235724c6e9cc8d9d4e26550aa47bef95fd5f0f82efe5e945bf296",
"EsteriaVulpera.bin": "c5434993b9af4a17d881965e4735cd2ac379e39c7142aac9844adff9528562d4",
"EsteriaVulperaTextures.bin": "1ab844e74684aced2b069f1b91cd563aade45e05bd5e23f866a6c0c301cb098e",
"Interface/AddOns/CoAHideArmor/CoAHideArmor.lua": "8c1c7403524fc9bd56c0809b4101b141da700ba163701209bf1420f2ef106aa7",
"Interface/AddOns/CoAHideArmor/CoAHideArmor.toc": "123580d92fd5ceee258e96296f42c359b7e83cdff151af49c50c6c4e2059677c",
"Interface/AddOns/CoAWC2Cursor/CoAWC2Cursor.lua": "1cf9537ff5f10b77250fea4407aea1008da690afe102ed6ed2dac21f79638cfa",
"Interface/AddOns/CoAWC2Cursor/CoAWC2Cursor.toc": "48ce695dce712b3643ebe13a77e318d623c964acc69479b8fc8cc675099801bf",
"Interface/AddOns/CoA_TalentReset/CoA_TalentReset.lua": "827d756d5948ef918fafaf8b869290b3a1faa4e4cc21b19b512a00d4509f3d41",
"Interface/AddOns/CoA_TalentReset/CoA_TalentReset.toc": "16298c04af68e68d6445e7a11f42aee525dd4145f85d2771ff434fb7c6e95a85",
"dinput8.dll": "f8de78606c241fb3911dce22faf68f5b9f9885b142b183c1e2c09ddc8f7e380c",
"wc2_human.cur": "f609736e29596bb386ef1597b157d211e01a86d32c2a929e256c581c37d71791",
"wc2_orc.cur": "baa512c9b9045762ba35b6e0d35b8f79c54b7649f35cc9c0e0cc8c168a1e5a97"
}
+2 -153
View File
@@ -5,10 +5,9 @@
use std::fmt;
use std::fs::File;
use std::io::{BufReader, BufWriter, Read, Seek, SeekFrom, Write};
use std::io::{BufReader, BufWriter, Read, Write};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::time::{Duration, Instant};
use serde::Deserialize;
@@ -49,7 +48,6 @@ pub struct Db {
realm: crate::realms::Mode,
/// Name of the database container of a Docker installation; the client tools then run inside it.
container: Option<String>,
read_deadline: Option<Instant>,
}
#[derive(Deserialize)]
@@ -69,42 +67,6 @@ fn no_window(cmd: &mut Command) {
let _ = cmd;
}
fn bounded_client_output(command: &mut Command, input: &[u8], deadline: Instant) -> Result<std::process::Output> {
let timeout = || Error::Invalid("The database inspection timed out. The Manager stopped its client process; the database server was not stopped. Retry the operation or export diagnostics if this continues.".into());
if Instant::now() >= deadline {
return Err(timeout());
}
let mut stdin = tempfile::tempfile()?;
stdin.write_all(input)?;
stdin.seek(SeekFrom::Start(0))?;
let mut stdout = tempfile::tempfile()?;
let mut stderr = tempfile::tempfile()?;
command.stdin(stdin).stdout(stdout.try_clone()?).stderr(stderr.try_clone()?);
let mut child = command.spawn()?;
let status = loop {
match child.try_wait() {
Ok(Some(status)) => break status,
Ok(None) if Instant::now() < deadline => std::thread::sleep(Duration::from_millis(25)),
result => {
child.kill().map_err(|error| Error::Invalid(format!(
"The database inspection timed out, but its client could not be stopped: {error}"
)))?;
let _ = child.wait();
return match result {
Err(error) => Err(error.into()),
_ => Err(timeout()),
};
}
}
};
stdout.seek(SeekFrom::Start(0))?;
stderr.seek(SeekFrom::Start(0))?;
let mut output = std::process::Output { status, stdout: Vec::new(), stderr: Vec::new() };
stdout.read_to_end(&mut output.stdout)?;
stderr.read_to_end(&mut output.stderr)?;
Ok(output)
}
/// Schema names of the three game databases.
pub const SCHEMAS: [(&str, &str); 3] = [
("characters", "acore_characters"),
@@ -173,7 +135,6 @@ impl Db {
password: Secret(password),
realm: crate::realms::state(root)?.active,
container: None,
read_deadline: None,
})
}
@@ -194,7 +155,6 @@ impl Db {
password: Secret(password),
realm: crate::realms::state(root)?.active,
container: Some(container),
read_deadline: None,
})
}
@@ -214,7 +174,6 @@ impl Db {
password: Secret(password.to_string()),
realm,
container: None,
read_deadline: None,
}
}
@@ -333,13 +292,7 @@ impl Db {
pub fn ping(&self) -> bool {
let mut c = self.command("mysqladmin.exe");
c.arg("ping").arg("--connect-timeout=3");
bounded_client_output(&mut c, b"", Instant::now() + Duration::from_secs(5))
.map(|o| o.status.success()).unwrap_or(false)
}
pub(crate) fn with_read_deadline(mut self, deadline: Instant) -> Self {
self.read_deadline = Some(deadline);
self
c.output().map(|o| o.status.success()).unwrap_or(false)
}
/// Run SQL text (statement(s) supplied on stdin) and return the raw output.
@@ -350,13 +303,6 @@ impl Db {
"--default-character-set=utf8mb4",
"--max-allowed-packet=128M",
]);
if let Some(deadline) = self.read_deadline {
let out = bounded_client_output(&mut c, route_sql(sql, self.realm).as_bytes(), deadline)?;
if !out.status.success() {
return Err(self.fail(&out.stderr));
}
return Ok(String::from_utf8_lossy(&out.stdout).trim().to_string());
}
c.stdin(Stdio::piped());
let mut child = c.spawn()?;
child
@@ -658,103 +604,6 @@ mod realm_tests {
#[cfg(test)]
mod tests {
fn client_fixture(mode: &str) -> std::process::Command {
let mut command = std::process::Command::new(std::env::current_exe().unwrap());
command.args(["--exact", "db::tests::bounded_client_fixture", "--nocapture"])
.env("COA_DATABASE_CLIENT_TEST", mode);
super::no_window(&mut command);
command
}
#[test]
fn bounded_client_fixture() {
match std::env::var("COA_DATABASE_CLIENT_TEST").as_deref() {
Ok("hang") => std::thread::sleep(std::time::Duration::from_secs(60)),
Ok("output") => {
use std::io::{Read, Write};
let mut input = Vec::new();
std::io::stdin().read_to_end(&mut input).unwrap();
std::io::stdout().write_all(&input).unwrap();
std::io::stderr().write_all(&vec![b'e'; 256 * 1024]).unwrap();
}
Ok("fail") => std::process::exit(17),
_ => (),
}
}
#[test]
fn bounded_client_captures_large_output_without_pipe_deadlock() {
let data = vec![b'x'; 256 * 1024];
let out = super::bounded_client_output(&mut client_fixture("output"), &data,
std::time::Instant::now() + std::time::Duration::from_secs(10)).unwrap();
assert!(out.status.success());
assert!(out.stdout.windows(data.len()).any(|part| part == data));
assert_eq!(out.stderr, vec![b'e'; 256 * 1024]);
let out = super::bounded_client_output(&mut client_fixture("fail"), b"",
std::time::Instant::now() + std::time::Duration::from_secs(10)).unwrap();
assert_eq!(out.status.code(), Some(17));
}
#[test]
fn bounded_client_timeout_releases_the_update_operation_lock() {
let folder = tempfile::tempdir().unwrap();
let start = std::time::Instant::now();
let result = (|| {
let _lock = crate::update::operation_lock_for(folder.path(), "checking updates", false)?;
super::bounded_client_output(&mut client_fixture("hang"), b"",
start + std::time::Duration::from_millis(250))
})();
assert!(result.unwrap_err().to_string().contains("inspection timed out"));
assert!(start.elapsed() < std::time::Duration::from_secs(5));
crate::update::operation_lock(folder.path()).unwrap();
}
#[cfg(windows)]
#[test]
#[ignore = "requires COA_MYSQL_TEST_BIN; starts a disposable MySQL server"]
fn real_mysql_inspection_timeout_preserves_server_and_releases_lock() {
use std::os::windows::process::CommandExt;
struct Server(std::process::Child);
impl Drop for Server {
fn drop(&mut self) {
let _ = self.0.kill();
let _ = self.0.wait();
}
}
let bin = std::path::PathBuf::from(std::env::var("COA_MYSQL_TEST_BIN").unwrap());
let folder = tempfile::tempdir().unwrap();
let data = folder.path().join("data");
let initialized = std::process::Command::new(bin.join("mysqld.exe"))
.args(["--no-defaults", "--initialize-insecure"])
.arg(format!("--datadir={}", data.display()))
.creation_flags(0x0800_0000).output().unwrap();
assert!(initialized.status.success(), "{}", String::from_utf8_lossy(&initialized.stderr));
let socket = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let port = socket.local_addr().unwrap().port();
drop(socket);
let mut server = Server(std::process::Command::new(bin.join("mysqld.exe"))
.args(["--no-defaults", "--bind-address=127.0.0.1", "--mysqlx=0", "--skip-log-bin"])
.arg(format!("--datadir={}", data.display())).arg(format!("--port={port}"))
.arg(format!("--log-error={}", folder.path().join("mysql.log").display()))
.stdout(std::process::Stdio::null()).stderr(std::process::Stdio::null())
.creation_flags(0x0800_0000).spawn().unwrap());
let db = super::Db::with_tools(bin, port, "root", "", crate::realms::Mode::Coa);
let ready = std::time::Instant::now() + std::time::Duration::from_secs(30);
while !db.ping() {
assert!(std::time::Instant::now() < ready);
std::thread::sleep(std::time::Duration::from_millis(100));
}
let result = (|| {
let _lock = crate::update::operation_lock_for(folder.path(), "checking updates", false)?;
db.clone().with_read_deadline(std::time::Instant::now() + std::time::Duration::from_millis(500))
.query("SELECT SLEEP(60);")
})();
assert!(result.unwrap_err().to_string().contains("inspection timed out"));
assert!(server.0.try_wait().unwrap().is_none());
assert_eq!(db.query("SELECT 42;").unwrap(), "42");
crate::update::operation_lock(folder.path()).unwrap();
}
#[test]
fn reborn_sql_routes_only_database_identifiers() {
use crate::realms::Mode;
+6 -65
View File
@@ -163,52 +163,10 @@ pub fn set_open(root: &Path, meta: &Path, open: bool) -> Result<bool> {
/// Make the realm list advertise `host` to remote clients (the launcher resets it to 127.0.0.1 at every start, so this
/// runs after each start).
fn realm_address_sql(
host: &str,
local: Option<(std::net::Ipv4Addr, std::net::Ipv4Addr)>,
where_realms: &str,
) -> Result<String> {
pub fn apply_realm_address(root: &Path, host: &str) -> Result<()> {
if !host_ok(host) {
return Err(Error::Invalid("That address is not valid.".into()));
}
let local = local
.map(|(address, mask)| format!(",localAddress='{address}',localSubnetMask='{mask}'"))
.unwrap_or_default();
Ok(format!(
"UPDATE acore_auth.realmlist SET address='{host}'{local} WHERE {where_realms};"
))
}
pub fn apply_realm_address(root: &Path, settings: &Settings) -> Result<()> {
let host = settings.host.as_deref().unwrap_or("127.0.0.1");
let local = match settings.mode {
Mode::Direct | Mode::Lan => {
let address = if settings.mode == Mode::Lan {
host.to_owned()
} else {
crate::net::resolve_lan_host(
settings.lan_address_override.as_deref(),
crate::net::lan_ip(),
)?
};
let address = crate::net::validate_lan_address(&address)?;
let mask = if_addrs::get_if_addrs()?
.into_iter()
.find_map(|interface| match interface.addr {
if_addrs::IfAddr::V4(v4) if v4.ip == address => Some(v4.netmask),
_ => None,
})
.ok_or_else(|| {
Error::Invalid("The selected local network address is not connected.".into())
})?;
Some((address, mask))
}
Mode::Local => Some((
std::net::Ipv4Addr::LOCALHOST,
std::net::Ipv4Addr::new(255, 0, 0, 0),
)),
Mode::Private => None,
};
let db = Db::from_repack(root, Account::Admin)?;
let state = crate::realms::state(root)?;
let mut ids = vec![state.active];
@@ -220,7 +178,9 @@ pub fn apply_realm_address(root: &Path, settings: &Settings) -> Result<()> {
.collect::<Vec<_>>()
.join(",")
);
db.query(&realm_address_sql(host, local, &where_realms)?)?;
db.query(&format!(
"UPDATE acore_auth.realmlist SET address='{host}' WHERE {where_realms};"
))?;
Ok(())
}
@@ -238,9 +198,9 @@ pub fn ensure_bind(root: &Path, meta: &Path) -> Result<bool> {
/// After every server start: put the chosen address back into the realm list (the launcher resets it to 127.0.0.1).
pub fn reapply(root: &Path, meta: &Path) -> Result<()> {
let s = load(meta);
match (s.mode, &s.host) {
match (s.mode, s.host) {
(Mode::Local, _) | (_, None) => Ok(()),
(_, Some(_)) => apply_realm_address(root, &s),
(_, Some(host)) => apply_realm_address(root, &host),
}
}
@@ -434,25 +394,6 @@ CoA.AllowRemoteClients = 0
);
}
#[test]
fn realm_addresses_restore_lan_without_replacing_public_host() {
let sql = realm_address_sql(
"203.0.113.9",
Some((
"192.168.50.7".parse().unwrap(),
"255.255.254.0".parse().unwrap(),
)),
"id IN (1,2)",
)
.unwrap();
assert_eq!(sql, "UPDATE acore_auth.realmlist SET address='203.0.113.9',localAddress='192.168.50.7',localSubnetMask='255.255.254.0' WHERE id IN (1,2);");
assert_eq!(
realm_address_sql("100.64.1.2", None, "id=1").unwrap(),
"UPDATE acore_auth.realmlist SET address='100.64.1.2' WHERE id=1;"
);
assert!(realm_address_sql("bad'host", None, "id=1").is_err());
}
#[test]
fn old_settings_load_without_migrating_effective_host_to_override() {
let s: Settings = serde_json::from_str(r#"{"mode":"lan","host":"192.168.1.50"}"#).unwrap();
+3 -3
View File
@@ -9,12 +9,11 @@
pub mod accounts;
pub mod allsettings;
pub mod analyzer;
pub mod backup;
pub mod channels;
pub mod character_start_check;
pub mod cleanbase;
pub mod client;
pub mod clientdl;
pub mod companions;
pub mod config;
pub mod console;
@@ -45,11 +44,12 @@ pub mod net;
pub mod package;
pub mod pkgsource;
pub mod platform;
pub mod plugins;
pub mod population;
pub mod portable;
pub mod process;
pub mod provenance;
pub mod ra;
pub mod race_availability;
pub mod realm_registry;
pub mod realmlist;
pub mod realms;
+27 -80
View File
@@ -173,6 +173,7 @@ fn installed_module_commits(root: &Path) -> BTreeMap<String, String> {
fn list_in(cat: &[Entry], root: &Path) -> Vec<ModuleView> {
let installed_commits = installed_module_commits(root);
let plugin_reg = crate::plugins::load_registry(root).ok();
let wildcard = crate::realms::state(root)
.map(|s| s.active != crate::realms::Mode::Coa)
.unwrap_or(true);
@@ -182,13 +183,16 @@ fn list_in(cat: &[Entry], root: &Path) -> Vec<ModuleView> {
let name = conf_name(root, &e);
let conf = dir(root).join(&name);
let dist = dir(root).join(format!("{name}.dist"));
let installed = conf.is_file() || dist.is_file();
let plugin_entry = plugin_reg.as_ref().and_then(|r| r.plugins.get(&e.id));
let installed = conf.is_file() || dist.is_file() || plugin_entry.is_some();
let has_settings = installed
&& settings_in(cat, root, &e.id)
.map(|settings| settings.iter().any(|s| s.key != e.enable_key))
.unwrap_or(false);
// the active file decides; without one the documented default is what the server will use
let enabled = if matches!(e.id.as_str(), "companions" | "playerbots") {
// the active file or plugin registry decides
let enabled = if let Some(p) = plugin_entry {
p.enabled
} else if matches!(e.id.as_str(), "companions" | "playerbots") {
bot_enabled(root, &e).unwrap_or(true)
} else {
!e.switchable
@@ -198,7 +202,9 @@ fn list_in(cat: &[Entry], root: &Path) -> Vec<ModuleView> {
.unwrap_or(e.default_on)
};
let blocked = wildcard && matches!(e.id.as_str(), "companions" | "playerbots");
let version = if e.id == "playerbots" {
let version = if let Some(p) = plugin_entry {
Some(p.version.clone())
} else if e.id == "playerbots" {
crate::squid::release(root).map(|release| {
[
release.tag,
@@ -296,7 +302,10 @@ 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 is_dynamic_plugin = crate::plugins::load_registry(root)
.map(|r| r.plugins.contains_key(id))
.unwrap_or(false);
let _lock = if is_dynamic_plugin || matches!(id, "companions" | "playerbots") {
require_bot_server_stopped(root)?;
fs::create_dir_all(root.join(".state"))?;
let lock = fs::OpenOptions::new()
@@ -408,6 +417,17 @@ fn set_enabled_in(cat: &[Entry], root: &Path, meta: &Path, id: &str, on: bool) -
&["Changed by CoA Server Manager"],
);
fsx::atomic_write(&conf, file.to_text().as_bytes())?;
// If registered as a dynamic plugin, synchronize plugins.lock and plugin state
if let Ok(reg) = crate::plugins::load_registry(root) {
if reg.plugins.contains_key(id) {
let _ = crate::plugins::set_enabled(root, id, on);
}
}
if id == "playerbots" && on {
let _ = crate::plugins::record_squid_migrations_applied(root);
}
tracing::info!(module = id, on, "module switched");
Ok(())
}
@@ -516,20 +536,6 @@ fn save_settings_in(
let mut changed = Vec::new();
for (key, value) in changes {
let value = value.trim();
if id == "custom-races" && key == crate::race_availability::KEY {
require_bot_server_stopped(root)?;
let catalog = crate::race_availability::status(root)?;
if !catalog.server_config_supported {
return Err(Error::Invalid("Update the server before configuring individual race restrictions.".into()));
}
crate::race_availability::parse_disabled(value, &catalog.races)?;
}
if id == "custom-races" && key == crate::race_availability::CATALOG_KEY {
let hash = value.trim_matches('"');
if !hash.is_empty() && (hash.len() != 64 || !hash.bytes().all(|byte| byte.is_ascii_hexdigit())) {
return Err(Error::Invalid("Invalid race catalog fingerprint.".into()));
}
}
if let Some(field) = fields.get(key) {
crate::squid::validate(field, value)?;
}
@@ -538,18 +544,6 @@ fn save_settings_in(
"Use the module switch to turn this module on or off.".into(),
));
}
if id == "time-is-time" {
let valid = match key.as_str() {
"TimeIsTime.Announce" => matches!(value, "0" | "1"),
"TimeIsTime.SpeedRate" => value.parse::<f32>().is_ok_and(|v| v.is_finite() && (0.0..=60.0).contains(&v)),
"TimeIsTime.TimeStart" => value.parse::<i32>().is_ok_and(|v| v >= 0),
"TimeIsTime.HourOffset" => value.parse::<f32>().is_ok_and(|v| v.is_finite() && (-24.0..=24.0).contains(&v)),
_ => true,
};
if !valid {
return Err(Error::Invalid(format!("Invalid value for {key}.")));
}
}
if id == "content-scaling" && key == "CoAContentScaling.Difficulty.DamageMultiplier" {
let multiplier = value.parse::<f32>().map_err(|_| {
Error::Invalid("Enemy damage must be a number from 0.25 to 2.0.".into())
@@ -646,53 +640,6 @@ fn save_settings_in(
mod tests {
use super::*;
#[test]
fn time_is_time_card_settings_and_backups_match_the_module() {
let temp = tempfile::tempdir().unwrap();
let root = temp.path().join("server");
let meta = temp.path().join("metadata");
fs::create_dir_all(dir(&root)).unwrap();
fs::create_dir_all(&meta).unwrap();
let cat = catalog();
assert!(!list_in(&cat, &root).iter().find(|m| m.id == "time-is-time").unwrap().installed);
let defaults = "# Keep module documentation\n[worldserver]\nTimeIsTime.Enable = 1\nTimeIsTime.Announce = 1\nTimeIsTime.SpeedRate = 1.0\nTimeIsTime.TimeStart = 0\nTimeIsTime.HourOffset = 0.0\n";
let dist = dir(&root).join("mod-time_is_time.conf.dist");
let active = dir(&root).join("mod-time_is_time.conf");
fs::write(&dist, defaults).unwrap();
let view = list_in(&cat, &root).into_iter().find(|m| m.id == "time-is-time").unwrap();
assert!(view.installed && view.enabled && view.switchable && view.has_settings);
for locale in ["en", "ru", "de", "fr", "es", "zh"] {
assert!(!view.description[locale].is_empty());
}
assert_eq!(settings_in(&cat, &root, "time-is-time").unwrap().len(), 5);
let changes = BTreeMap::from([
("TimeIsTime.SpeedRate".into(), "7.5".into()),
("TimeIsTime.TimeStart".into(), "1213963200".into()),
("TimeIsTime.HourOffset".into(), "5.5".into()),
("TimeIsTime.Announce".into(), "0".into()),
]);
assert_eq!(save_settings_in(&cat, &root, &meta, "time-is-time", &changes).unwrap().len(), 4);
let saved = fs::read(&active).unwrap();
assert!(String::from_utf8_lossy(&saved).contains("# Keep module documentation"));
assert_eq!(fs::read_to_string(&dist).unwrap(), defaults);
assert!(save_settings_in(&cat, &root, &meta, "time-is-time", &changes).unwrap().is_empty());
for (key, value) in [
("TimeIsTime.Enable", "0"), ("TimeIsTime.SpeedRate", "NaN"),
("TimeIsTime.SpeedRate", "-1"), ("TimeIsTime.SpeedRate", "61"),
("TimeIsTime.HourOffset", "inf"), ("TimeIsTime.HourOffset", "25"),
("TimeIsTime.TimeStart", "-1"), ("TimeIsTime.TimeStart", "2147483648"),
("TimeIsTime.TimeStart", "1.5"), ("TimeIsTime.Announce", "2"),
] {
assert!(save_settings_in(&cat, &root, &meta, "time-is-time", &BTreeMap::from([(key.into(), value.into())])).is_err(), "{key}={value}");
assert_eq!(fs::read(&active).unwrap(), saved);
}
set_enabled_in(&cat, &root, &meta, "time-is-time", false).unwrap();
assert_eq!(read(&active).unwrap().get("TimeIsTime.Enable"), Some("0"));
set_enabled_in(&cat, &root, &meta, "time-is-time", true).unwrap();
assert_eq!(read(&active).unwrap().get("TimeIsTime.SpeedRate"), Some("7.5"));
assert!(meta.join("backups").exists());
}
fn test_catalog() -> Vec<Entry> {
let one = |id: &str, name: &str, conf: &str, key: &str| Entry {
id: id.into(),
@@ -884,8 +831,8 @@ mod tests {
// it may be empty (modules are added to it one by one); whatever is in it must be complete
for e in &c {
assert!(
["en", "ru", "de", "fr", "es"].iter().all(|locale| e.description.get(*locale).is_some_and(|text| !text.is_empty())),
"{} has the existing catalog languages (additional translations are allowed)",
e.description.contains_key("en") && e.description.len() == 5,
"{} has all five descriptions",
e.id
);
assert!(
+1 -37
View File
@@ -82,21 +82,6 @@ pub fn tree_running(main: &Path, tree: Tree) -> bool {
.any(|n| process::read_state_record(&second, n).is_some_and(|p| process::is_alive(&p)))
}
/// The folder whose world server runs `mode`: the main folder, or the folder of the extra world that runs that realm.
/// Its settings hold the console port that belongs to that world.
pub fn world_root(main: &Path, mode: Mode) -> PathBuf {
let Ok(s) = realms::state(main) else {
return main.to_path_buf();
};
if mode == s.active {
return main.to_path_buf();
}
Tree::ALL
.into_iter()
.find(|t| t.enabled(&s) && t.mode(s.active) == mode)
.map_or_else(|| main.to_path_buf(), |t| tree_root(main, t))
}
/// Any of the extra worlds is running or still stopping.
pub fn is_running(main: &Path) -> bool {
Tree::ALL.into_iter().any(|t| tree_running(main, t))
@@ -275,6 +260,7 @@ fn prepare(main: &Path, tree: Tree) -> Result<PathBuf> {
)?;
}
}
let _ = crate::plugins::prepare_multiworld(main, &second);
let files: BTreeMap<String, Vec<u8>> =
fsx::read_json(&main.join(format!("Settings/realm-profiles/{}.json", mode.name())))?;
// A previous secondary run may have used the other realm's module files.
@@ -461,28 +447,6 @@ mod tests {
assert!(!Tree::Second.enabled(&s) && Tree::Reborn.enabled(&s));
}
#[test]
fn a_realm_is_reached_through_the_folder_of_its_own_world() {
let t = tempfile::tempdir().unwrap();
let main = t.path();
fsx::atomic_write(
&main.join("Settings/realm-profile.json"),
br#"{"active":"coa","wildcard_created":true,"reborn_created":true,"simultaneous":true,"with_reborn":true}"#,
)
.unwrap();
assert_eq!(world_root(main, Mode::Coa), main);
assert_eq!(world_root(main, Mode::Wildcard), main.join(".realms/secondary"));
assert_eq!(world_root(main, Mode::Reborn), main.join(".realms/reborn"));
// A realm that is not switched on has no world of its own: the main folder answers.
fsx::atomic_write(
&main.join("Settings/realm-profile.json"),
br#"{"active":"coa","wildcard_created":true,"reborn_created":true,"with_reborn":true}"#,
)
.unwrap();
assert_eq!(world_root(main, Mode::Wildcard), main);
assert_eq!(world_root(main, Mode::Reborn), main.join(".realms/reborn"));
}
#[test]
fn reborn_starts_together_with_conquest_of_azeroth_only() {
let t = tempfile::tempdir().unwrap();
-83
View File
@@ -1004,89 +1004,6 @@ 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();
File diff suppressed because it is too large. Load diff
@@ -20,4 +20,29 @@ FROM collection;
DROP TABLE collection;
ALTER TABLE collection_new RENAME TO collection;
CREATE INDEX IF NOT EXISTS character_profile_ruleset ON character(profile_id, ruleset);
-- 2. Upgrade character table to allow 'reborn' in CHECK (ruleset IN ('coa', 'wildcard', 'reborn'))
-- Foreign keys are off during migration runner, but legacy child tables remain valid because primary keys are untouched.
CREATE TABLE character_new (
character_id TEXT PRIMARY KEY,
profile_id TEXT NOT NULL REFERENCES profile(profile_id),
ruleset TEXT NOT NULL CHECK (ruleset IN ('coa', 'wildcard', 'reborn')),
name TEXT NOT NULL,
race TEXT NOT NULL,
class TEXT NOT NULL,
gender INTEGER NOT NULL,
level INTEGER NOT NULL,
revision INTEGER NOT NULL CHECK (revision >= 1),
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
archived INTEGER NOT NULL DEFAULT 0 CHECK (archived IN (0, 1))
) STRICT;
INSERT INTO character_new (character_id, profile_id, ruleset, name, race, class, gender, level, revision, created_at, updated_at, archived)
SELECT character_id, profile_id, ruleset, name, race, class, gender, level, revision, created_at, updated_at, archived
FROM character;
DROP TABLE character;
ALTER TABLE character_new RENAME TO character;
CREATE INDEX character_profile ON character(profile_id);
CREATE INDEX character_profile_ruleset ON character(profile_id, ruleset);
@@ -1,26 +0,0 @@
-- 2. Upgrade character table to allow 'reborn' in CHECK (ruleset IN ('coa', 'wildcard', 'reborn'))
-- Foreign keys are off during migration runner, but legacy child tables remain valid because primary keys are untouched.
CREATE TABLE character_new (
character_id TEXT PRIMARY KEY,
profile_id TEXT NOT NULL REFERENCES profile(profile_id),
ruleset TEXT NOT NULL CHECK (ruleset IN ('coa', 'wildcard', 'reborn')),
name TEXT NOT NULL,
race TEXT NOT NULL,
class TEXT NOT NULL,
gender INTEGER NOT NULL,
level INTEGER NOT NULL,
revision INTEGER NOT NULL CHECK (revision >= 1),
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
archived INTEGER NOT NULL DEFAULT 0 CHECK (archived IN (0, 1))
) STRICT;
INSERT INTO character_new (character_id, profile_id, ruleset, name, race, class, gender, level, revision, created_at, updated_at, archived)
SELECT character_id, profile_id, ruleset, name, race, class, gender, level, revision, created_at, updated_at, archived
FROM character;
DROP TABLE character;
ALTER TABLE character_new RENAME TO character;
CREATE INDEX character_profile ON character(profile_id);
CREATE INDEX character_profile_ruleset ON character(profile_id, ruleset);
@@ -248,15 +248,9 @@ impl RealmAccess {
}
}
/// The folder of the world server this realm runs in: an extra world next to the main one has its own console port.
fn world_folder(&self, root: &Path) -> PathBuf {
self.mode
.map_or_else(|| root.to_path_buf(), |m| crate::multiworld::world_root(root, m))
}
pub fn ra(&self) -> Result<Ra> {
match &self.source {
Source::Install { root } => Ra::connect(&self.world_folder(root)),
Source::Install { root } => Ra::connect(root),
Source::Descriptor(d) => Ra::connect_to(d.ra_port, &d.ra_user, d.ra_password.expose()),
}
}
@@ -267,7 +261,7 @@ impl RealmAccess {
pub fn ports(&self) -> (Option<u16>, u16) {
match &self.source {
Source::Install { root } => (None, read_ports(&self.world_folder(root)).ra),
Source::Install { root } => (None, read_ports(root).ra),
Source::Descriptor(d) => (Some(d.db_port), d.ra_port),
}
}
+10 -52
View File
@@ -31,8 +31,6 @@ use serde::{Deserialize, Serialize};
use crate::db::Db;
use crate::ra::Ra;
mod remote_sync;
use super::super::capabilities::RealmCapabilities;
use super::super::compat::{self, CompatibilityReport, Inputs, Operation, Outcome, Topic};
use super::super::error::PortableError;
@@ -731,12 +729,6 @@ impl PortableService {
updated_at: at,
});
}
let remote_active = self
.owner
.owner_active_remote(c.character_id)
.ok()
.flatten()
.is_some();
let active = copies
.iter()
.find(|x| {
@@ -749,9 +741,9 @@ impl PortableService {
)
})
.cloned();
let status = remote_active
.then_some(PlayStatus::Syncing)
.or_else(|| active.as_ref().map(|a| a.status))
let status = active
.as_ref()
.map(|a| a.status)
.or_else(|| {
copies
.iter()
@@ -1326,11 +1318,6 @@ impl PortableService {
if events.is_ok() {
delivery = (|| {
for m in host.outbox()? {
if self.owner.owner_session_realm(m.session_id)?.as_deref()
!= Some(access.id.as_str())
{
continue; // The remote Owner must acknowledge its own baseline and checkpoints.
}
let mut owner = OwnerService::new(&mut self.owner);
let ack: OwnerAck = if m.started {
owner.handle_started(&m.bytes)?
@@ -1344,25 +1331,6 @@ impl PortableService {
}
}
for m in host.collection_outbox()? {
let local_owner =
host.store()
.host_live_sessions(&access.id)?
.iter()
.any(|session| {
session.local_guid.is_some_and(|guid| {
realm::collections::account_of(&db, guid).ok().flatten()
== Some(m.account)
}) && self
.owner
.owner_session_realm(session.session_id)
.ok()
.flatten()
.as_deref()
== Some(access.id.as_str())
});
if !local_owner {
continue;
}
let ack = OwnerService::new(&mut self.owner).handle_collection(&m.bytes)?;
host.receive_collection_ack(&mut bridge, m.account, &ack)?;
}
@@ -1681,28 +1649,12 @@ impl PortableService {
let ops = [Operation::OnlineImport, Operation::RuntimeSession];
let report = self.report(&model, &caps, &opts, &ops, true);
if verdict_of(report.verdict()) == Verdict::Incompatible {
#[cfg(test)]
eprintln!("Remote import compatibility: {report:?}");
return Err(fail(
"incompatible",
"Character is incompatible with this realm; nothing was changed.",
));
}
let existing_mapping = self
.host
.server_mappings(cid)?
.into_iter()
.find(|m| m.server_id == realm_id);
// A live realm must never arm stale data as a new canonical revision.
if existing_mapping
.as_ref()
.is_some_and(|mapping| mapping.last_revision != params.revision)
{
return Err(fail("update_required", "The realm's existing copy needs an offline refresh by its owner before this revision can be played. Your canonical character is unchanged."));
}
// Install or advance copy in host store
self.host
.host_install_copy(self.host_profile, &model, params.revision, "remote")?;
@@ -1725,7 +1677,13 @@ impl PortableService {
}
}
let session_id = SessionId::from_uuid(params.session_id)?;
let existing_mapping = self
.host
.server_mappings(cid)?
.into_iter()
.find(|m| m.server_id == realm_id);
let session_id = SessionId::new();
let envelope = super::super::session::protocol::Envelope::from_encoded(
&super::super::snapshot::encode(&model)?,
);
@@ -1,345 +0,0 @@
use super::*;
use crate::control::service::{RemoteSessionMessage, RemoteSessionState};
use crate::portable::session::protocol::{
self, CollectionAck, CollectionObserved, OwnerAck, PortableCheckpoint, PortableSessionStarted,
};
use coa_control_proto::app::SessionMessageKind;
pub fn owner_realm(realm: &str) -> String {
format!("remote-{realm}")
}
impl PortableService {
/// Open the Owner's durable session before its snapshot leaves this computer.
pub fn prepare_remote_transfer(
&mut self,
character: &str,
realm: &str,
) -> Res<(ClaimBundle, uuid::Uuid, u64)> {
let cid = self.cid(character)?;
let offer = OwnerService::new(&mut self.owner).offer(cid, &owner_realm(realm))?;
let bundle = self.export_for_remote_transfer(character)?;
self.publish();
Ok((bundle, offer.session_id.as_uuid(), offer.canonical_revision))
}
pub fn remote_session_closed(&self, session: uuid::Uuid) -> Res<bool> {
let sid = SessionId::from_uuid(session)?;
Ok(self
.owner
.owner_session_info(sid)?
.is_some_and(|row| row.0 == "closed"))
}
pub fn remote_session_idle(&self, session: uuid::Uuid) -> Res<bool> {
let sid = SessionId::from_uuid(session)?;
Ok(self
.owner
.owner_session_info(sid)?
.is_some_and(|row| row.0 == "offered" || row.0 == "superseded"))
}
pub fn next_remote_session(
&self,
character: uuid::Uuid,
realm: &str,
) -> Res<Option<uuid::Uuid>> {
Ok(self
.owner
.owner_next_session(CharacterId::from_uuid(character)?, &owner_realm(realm))?
.map(|sid| sid.as_uuid()))
}
/// The channel authenticates the public realm. Its private local id is never an Owner-side namespace.
pub fn apply_remote_session_message(
&mut self,
character: uuid::Uuid,
session: uuid::Uuid,
realm: &str,
kind: SessionMessageKind,
bytes: &[u8],
) -> Res<Vec<u8>> {
let cid = CharacterId::from_uuid(character)?;
let sid = SessionId::from_uuid(session)?;
let scope = owner_realm(realm);
if self.owner.owner_session_realm(sid)?.as_deref() != Some(scope.as_str()) {
return Err(fail(
"not_yours",
"This remote session was not opened by this Manager.",
));
}
let ruleset = self.owner.character(cid)?.ruleset;
let answer = match kind {
SessionMessageKind::Started => {
let mut message: PortableSessionStarted = protocol::from_json(bytes)?;
if message.character_id != cid
|| message.session_id != sid
|| message.ruleset != ruleset
{
return Err(fail(
"not_yours",
"The baseline belongs to another character or session.",
));
}
message.server_id = scope;
let ack = self.owner.owner_session_started(&message)?;
protocol::to_json(&ack)?
}
SessionMessageKind::Checkpoint => {
let mut message: PortableCheckpoint = protocol::from_json(bytes)?;
if message.character_id != cid
|| message.session_id != sid
|| message.ruleset != ruleset
{
return Err(fail(
"not_yours",
"The checkpoint belongs to another character or session.",
));
}
message.server_id = scope;
let ack = self.owner.owner_checkpoint(&message)?;
protocol::to_json(&ack)?
}
SessionMessageKind::Collection => {
let mut message: CollectionObserved = protocol::collection_from_json(bytes)?;
if message.ruleset != ruleset {
return Err(fail(
"incompatible",
"The collection belongs to another ruleset.",
));
}
message.server_id = scope;
let ack = OwnerService::new(&mut self.owner)
.handle_collection(&protocol::collection_to_json(&message)?)?;
protocol::collection_to_json(&ack)?
}
};
self.publish();
Ok(answer)
}
fn checked_remote_session(
&self,
realm: &str,
character: uuid::Uuid,
session: uuid::Uuid,
account: u32,
) -> Res<(RealmAccess, crate::portable::store::HostSession)> {
let access = self.access(realm)?;
let cid = CharacterId::from_uuid(character)?;
let sid = SessionId::from_uuid(session)?;
let row = self
.host
.host_session(sid)?
.ok_or_else(|| fail("not_yours", "Unknown portable session."))?;
if row.character_id != cid || row.server_id != realm {
return Err(fail(
"not_yours",
"The portable session belongs to another realm or character.",
));
}
let guid = row
.local_guid
.ok_or_else(|| fail("not_yours", "The portable session has no realm character."))?;
if realm::collections::account_of(&access.db()?, guid)? != Some(account) {
return Err(fail(
"not_yours",
"The portable session belongs to another account.",
));
}
Ok((access, row))
}
pub fn remote_session_message(
&mut self,
realm: &str,
character: uuid::Uuid,
session: uuid::Uuid,
account: u32,
) -> Res<RemoteSessionState> {
let (_, row) = self.checked_remote_session(realm, character, session, account)?;
let host = HostService::new(&mut self.host, realm, self.host_config.clone());
let collection = host
.collection_outbox()?
.into_iter()
.find(|message| message.account == account);
let message = if let Some(message) = collection {
Some(RemoteSessionMessage {
kind: SessionMessageKind::Collection,
bytes: message.bytes,
})
} else {
host.outbox()?
.into_iter()
.find(|message| message.session_id == row.session_id)
.map(|message| RemoteSessionMessage {
kind: if message.started {
SessionMessageKind::Started
} else {
SessionMessageKind::Checkpoint
},
bytes: message.bytes,
})
};
Ok(RemoteSessionState {
message,
closed: row.state == crate::portable::store::HostState::Closed,
})
}
pub fn apply_remote_session_ack(
&mut self,
realm: &str,
character: uuid::Uuid,
session: uuid::Uuid,
account: u32,
kind: SessionMessageKind,
bytes: &[u8],
) -> Res<()> {
let (access, row) = self.checked_remote_session(realm, character, session, account)?;
let db = access.db()?;
let knowledge = RealmKnowledge::from_data_dir(&access.data_dir)
.ok()
.map(Arc::new);
let mut bridge = LiveBridge::new(
&db,
access
.ra()
.map_err(|error| fail("realm_offline", error.to_string()))?,
)
.with_knowledge(knowledge);
let mut host = HostService::new(&mut self.host, realm, self.host_config.clone());
match kind {
SessionMessageKind::Collection => {
let ack: CollectionAck = protocol::collection_from_json(bytes)?;
host.receive_collection_ack(&mut bridge, account, &ack)?;
}
_ => {
let ack: OwnerAck = protocol::from_json(bytes)?;
if ack.session_id != row.session_id {
return Err(fail(
"not_yours",
"The acknowledgement belongs to another session.",
));
}
host.receive_ack(&mut bridge, &ack)?;
}
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::portable::{
fixtures::geared_level_eighty,
session::protocol::{AckOutcome, PortableCheckpoint, PortableSessionStarted},
};
#[test]
fn remote_progress_is_scoped_durable_and_idempotent() {
let dir = tempfile::tempdir().unwrap();
let mut service = PortableService::open(dir.path(), vec![]).unwrap();
let model = geared_level_eighty();
let cid = model.character_id;
service
.owner
.host_install_copy(service.owner_profile, &model, 7, "fixture")
.unwrap();
let (_, sid, revision) = service
.prepare_remote_transfer(&cid.to_string(), "public-realm")
.unwrap();
assert_eq!(revision, 7);
let session = SessionId::from_uuid(sid).unwrap();
let started =
PortableSessionStarted::new(session, cid, "private-host-id", revision, 1, &model, None)
.unwrap();
let bytes = protocol::to_json(&started).unwrap();
assert!(service
.apply_remote_session_message(
cid.as_uuid(),
sid,
"other-realm",
SessionMessageKind::Started,
&bytes
)
.is_err());
assert!(service
.apply_remote_session_message(
uuid::Uuid::now_v7(),
sid,
"public-realm",
SessionMessageKind::Started,
&bytes
)
.is_err());
let ack: OwnerAck = protocol::from_json(
&service
.apply_remote_session_message(
cid.as_uuid(),
sid,
"public-realm",
SessionMessageKind::Started,
&bytes,
)
.unwrap(),
)
.unwrap();
assert_eq!(ack.outcome, AckOutcome::Applied);
assert_eq!(service.state().characters[0].status, PlayStatus::Syncing);
assert!(service
.prepare_remote_transfer(&cid.to_string(), "other-realm")
.is_err());
drop(service);
let mut service = PortableService::open(dir.path(), vec![]).unwrap();
let mut changed = model.clone();
changed.progression.money += 123;
let checkpoint = PortableCheckpoint::new(
session,
cid,
"private-host-id",
revision,
1,
true,
&changed,
None,
)
.unwrap();
let bytes = protocol::to_json(&checkpoint).unwrap();
let first: OwnerAck = protocol::from_json(
&service
.apply_remote_session_message(
cid.as_uuid(),
sid,
"public-realm",
SessionMessageKind::Checkpoint,
&bytes,
)
.unwrap(),
)
.unwrap();
assert_eq!(first.outcome, AckOutcome::Applied);
let again: OwnerAck = protocol::from_json(
&service
.apply_remote_session_message(
cid.as_uuid(),
sid,
"public-realm",
SessionMessageKind::Checkpoint,
&bytes,
)
.unwrap(),
)
.unwrap();
assert_eq!(again.outcome, AckOutcome::Duplicate);
assert_eq!(first.canonical_revision, again.canonical_revision);
assert!(service.remote_session_closed(sid).unwrap());
drop(service);
let service = PortableService::open(dir.path(), vec![]).unwrap();
assert_eq!(
service.owner.load_current(cid).unwrap().progression.money,
changed.progression.money
);
}
}
+1 -2
View File
@@ -28,7 +28,6 @@ const MIGRATIONS: &[&str] = &[
include_str!("migrations/007_capabilities.sql"),
include_str!("migrations/008_projection.sql"),
include_str!("migrations/009_multiruleset.sql"),
include_str!("migrations/010_reborn_character_ruleset.sql"),
];
pub const DEFAULT_HISTORY_KEEP: u32 = 20;
@@ -177,7 +176,7 @@ impl Store {
fn init(conn: Connection) -> Result<Store> {
conn.busy_timeout(std::time::Duration::from_secs(5))?;
let _ = conn.pragma_update(None, "journal_mode", "WAL");
conn.pragma_update(None, "synchronous", "FULL")?;
let _ = conn.pragma_update(None, "synchronous", "NORMAL");
let mut store = Store { conn };
store.migrate()?;
store.conn.pragma_update(None, "foreign_keys", true)?;
@@ -181,10 +181,6 @@ impl Store {
check_server_id(server_id)?;
let tx = self.write_tx()?;
let record = read_character(&tx, id)?;
let busy: bool = tx.query_row("SELECT EXISTS(SELECT 1 FROM owner_session WHERE character_id = ?1 AND server_id != ?2 AND state = 'open')", params![id.to_string(), server_id], |row| row.get(0))?;
if busy {
return Err(PortableError::SessionOpen);
}
let live: Option<String> = tx
.query_row("SELECT session_id FROM owner_session WHERE character_id = ?1 AND server_id = ?2 AND state IN ('offered', 'open')", params![id.to_string(), server_id], |r| r.get(0))
.optional()?;
@@ -198,8 +194,6 @@ impl Store {
}
tx.execute("UPDATE owner_session SET state = 'superseded', updated_at = ?2 WHERE session_id = ?1", params![live, now()])?;
}
// Only the selected realm may start the next session. Other idle offers must not come alive later.
tx.execute("UPDATE owner_session SET state='superseded', updated_at=?3 WHERE character_id=?1 AND server_id!=?2 AND state='offered'", params![id.to_string(), server_id, now()])?;
let offer = open_offer(&tx, id, server_id)?;
tx.commit()?;
Ok(offer)
@@ -527,21 +521,4 @@ impl Store {
Ok(read_owner_row(&self.conn, session)?
.map(|r| (r.state, r.last_sequence, r.head_revision)))
}
pub fn owner_next_session(
&self,
character: CharacterId,
realm: &str,
) -> Result<Option<SessionId>> {
let sid: Option<String> = self.conn.query_row("SELECT session_id FROM owner_session WHERE character_id=?1 AND server_id=?2 AND state IN ('offered','open') ORDER BY updated_at DESC LIMIT 1", params![character.to_string(), realm], |row| row.get(0)).optional()?;
sid.map(|sid| sid.parse()).transpose()
}
pub fn owner_active_remote(&self, character: CharacterId) -> Result<Option<(String, String)>> {
self.conn.query_row("SELECT server_id, state FROM owner_session WHERE character_id=?1 AND server_id LIKE 'remote-%' AND state='open' ORDER BY updated_at DESC LIMIT 1", [character.to_string()], |row| Ok((row.get(0)?, row.get(1)?))).optional().map_err(Into::into)
}
pub fn owner_session_realm(&self, session: SessionId) -> Result<Option<String>> {
Ok(read_owner_row(&self.conn, session)?.map(|row| row.server_id))
}
}
+1 -120
View File
@@ -7,112 +7,6 @@ fn fresh() -> (Store, ProfileId) {
(store, profile)
}
#[test]
fn schema_nine_upgrade_preserves_characters_and_isolates_collections() {
let dir = tempfile::tempdir().unwrap();
let conn = Connection::open(Store::path_of(dir.path())).unwrap();
for sql in &MIGRATIONS[..8] {
conn.execute_batch(sql).unwrap();
}
conn.pragma_update(None, "application_id", APPLICATION_ID)
.unwrap();
conn.pragma_update(None, "user_version", 8).unwrap();
let mut old = Store { conn };
let profile = old.default_profile().unwrap();
let id = created(&mut old, profile);
old.bind_server(id, "realm-a", 42, 1, MappingState::Synced)
.unwrap();
let before = old.load_current(id).unwrap();
let set = IdSet::from_ids([10, 20]).unwrap();
let kind = "coa:wardrobe";
old.conn
.execute(
"INSERT INTO collection VALUES (?1, ?2, 7, ?3, ?4, 2, 'before', ?5)",
params![
profile.to_string(),
kind,
set.hash(kind).as_slice(),
PORTABLE_COLLECTION_FORMAT_VERSION,
set.encode()
],
)
.unwrap();
drop(old);
let mut store = Store::open(dir.path()).unwrap();
assert_eq!(store.schema_version().unwrap(), 10);
assert_eq!(store.load_current(id).unwrap(), before);
assert_eq!(store.server_mappings(id).unwrap()[0].local_guid, 42);
assert_eq!(
store
.collection(profile, Ruleset::Coa, kind)
.unwrap()
.unwrap()
.1,
set
);
assert_eq!(
store
.collection_info(profile, Ruleset::Coa, kind)
.unwrap()
.unwrap()
.revision,
7
);
// An experimental Manager may already have populated another partition.
store.conn.execute(
"INSERT INTO collection SELECT profile_id, 'reborn', kind, collection_revision, collection_hash, format_version, item_count, updated_at, payload FROM collection WHERE ruleset = 'coa'",
[],
).unwrap();
store
.merge_collection(profile, Ruleset::Coa, kind, &IdSet::from_ids([30]).unwrap())
.unwrap();
assert_eq!(
store
.collection(profile, Ruleset::Coa, kind)
.unwrap()
.unwrap()
.1,
IdSet::from_ids([10, 20, 30]).unwrap()
);
let foreign: (i64, Vec<u8>) = store
.conn
.query_row(
"SELECT collection_revision, payload FROM collection WHERE ruleset = 'reborn'",
[],
|r| Ok((r.get(0)?, r.get(1)?)),
)
.unwrap();
assert_eq!(foreign, (7, set.encode()));
drop(store);
assert_eq!(
Store::open(dir.path()).unwrap().load_current(id).unwrap(),
before
);
}
#[test]
#[ignore = "Requires a disposable SQLite backup in COA_PORTABLE_SCHEMA9_FIXTURE"]
fn schema_nine_existing_store_and_runtime_smoke() {
let root = std::path::PathBuf::from(
std::env::var_os("COA_PORTABLE_SCHEMA9_FIXTURE").expect("fixture path"),
);
for role in ["owner", "host"] {
let store = Store::open(&root.join(role)).unwrap();
assert_eq!(store.schema_version().unwrap(), 10);
let records = store.list_characters_all().unwrap();
assert!(!records.is_empty());
for record in records {
store.load_current(record.character_id).unwrap();
store.list_revisions(record.character_id).unwrap();
}
}
let runtime =
crate::portable::service::PortableRuntime::start(&root, Box::new(Vec::new), None).unwrap();
runtime.call(|_| ()).unwrap();
runtime.shutdown();
}
fn created(store: &mut Store, profile: ProfileId) -> CharacterId {
store
.create_character(profile, fixtures::geared_level_eighty(), "realm-a")
@@ -2161,7 +2055,7 @@ fn released_v0_7_x_database_upgrades_transactionally_through_migration_009_and_a
// Upgrade through Store::open_file (applies migration 009)
let store = Store::open_file(&file).unwrap();
assert_eq!(store.schema_version().unwrap(), 10);
assert_eq!(store.schema_version().unwrap(), 9);
// Verify all original rows and fields survived byte-for-byte and constraint-wise
let coa_rec = store.character(char_coa).unwrap();
@@ -2589,16 +2483,3 @@ fn reborn_store_corruption_fails_closed() {
"Loading reborn summary with Wildcard snapshot must fail closed"
);
}
#[test]
fn canonical_file_retains_full_sync_after_initialization_and_reopen() {
let dir = tempfile::tempdir().unwrap();
for _ in 0..2 {
let store = Store::open(dir.path()).unwrap();
let sync: i64 = store
.conn
.pragma_query_value(None, "synchronous", |row| row.get(0))
.unwrap();
assert_eq!(sync, 2);
}
}
+292
View File
@@ -0,0 +1,292 @@
use std::collections::BTreeMap;
use std::fs;
use std::path::Path;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use crate::error::{Error, Result};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PeExportEntry {
pub ordinal: u32,
pub rva: String,
pub decorated_name: String,
pub demangled_signature: Option<String>,
pub is_forwarder: bool,
pub forwarder_target: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ArtifactProvenanceRecord {
pub file_path: String,
pub file_size: u64,
pub file_sha256: String,
pub machine_architecture: String,
pub is_dll: bool,
pub total_export_count: usize,
pub total_name_count: usize,
pub embedded_abi_fingerprint: Option<String>,
pub sdk_manifest_fingerprint: Option<String>,
pub sdk_manifest_match: bool,
pub category_a_signatures: Vec<String>,
pub category_a_count: usize,
pub compiler_environment: BTreeMap<String, String>,
pub provenance_status: String, // "PROVENANCE_VERIFIED" or "CONFLICT_DETECTED"
pub notes: Vec<String>,
}
/// Helper function to translate RVA to file offset given PE section headers
fn rva_to_offset(rva: u32, sections: &[(u32, u32, u32, u32)]) -> Option<usize> {
for &(sec_va, sec_vsize, sec_raw_ptr, sec_raw_size) in sections {
let size = sec_vsize.max(sec_raw_size);
if rva >= sec_va && rva < sec_va + size {
return Some((sec_raw_ptr + (rva - sec_va)) as usize);
}
}
None
}
/// Parse PE headers and extract all exported symbols and metadata directly from binary bytes
pub fn parse_pe_exports(bytes: &[u8]) -> Result<(String, bool, Vec<PeExportEntry>, Option<String>)> {
if bytes.len() < 64 {
return Err(Error::Invalid("File too small to be a PE image".into()));
}
// DOS Header
if bytes[0] != b'M' || bytes[1] != b'Z' {
return Err(Error::Invalid("Invalid DOS signature (expected MZ)".into()));
}
let e_lfanew = u32::from_le_bytes(bytes[0x3C..0x40].try_into().unwrap()) as usize;
if e_lfanew + 24 > bytes.len() {
return Err(Error::Invalid("Truncated NT header offset".into()));
}
// PE Signature
if &bytes[e_lfanew..e_lfanew + 4] != b"PE\0\0" {
return Err(Error::Invalid("Invalid PE signature".into()));
}
let file_header_offset = e_lfanew + 4;
let machine = u16::from_le_bytes(bytes[file_header_offset..file_header_offset + 2].try_into().unwrap());
let num_sections = u16::from_le_bytes(bytes[file_header_offset + 2..file_header_offset + 4].try_into().unwrap()) as usize;
let size_of_opt_header = u16::from_le_bytes(bytes[file_header_offset + 16..file_header_offset + 18].try_into().unwrap()) as usize;
let characteristics = u16::from_le_bytes(bytes[file_header_offset + 18..file_header_offset + 20].try_into().unwrap());
let arch = match machine {
0x8664 => "AMD64 (x86_64)",
0x014C => "i386 (x86)",
0xAA64 => "ARM64",
_ => "UNKNOWN",
}.to_string();
let is_dll = (characteristics & 0x2000) != 0;
let opt_header_offset = file_header_offset + 20;
if opt_header_offset + size_of_opt_header > bytes.len() {
return Err(Error::Invalid("Truncated Optional Header".into()));
}
let magic = u16::from_le_bytes(bytes[opt_header_offset..opt_header_offset + 2].try_into().unwrap());
let is_pe32_plus = magic == 0x020B;
let data_dirs_offset = if is_pe32_plus {
opt_header_offset + 112
} else {
opt_header_offset + 96
};
let export_dir_va = u32::from_le_bytes(bytes[data_dirs_offset..data_dirs_offset + 4].try_into().unwrap());
let export_dir_size = u32::from_le_bytes(bytes[data_dirs_offset + 4..data_dirs_offset + 8].try_into().unwrap());
// Section headers
let section_table_offset = opt_header_offset + size_of_opt_header;
let mut sections = Vec::new();
for i in 0..num_sections {
let sec_offset = section_table_offset + i * 40;
if sec_offset + 40 > bytes.len() {
break;
}
let sec_vsize = u32::from_le_bytes(bytes[sec_offset + 8..sec_offset + 12].try_into().unwrap());
let sec_va = u32::from_le_bytes(bytes[sec_offset + 12..sec_offset + 16].try_into().unwrap());
let sec_raw_size = u32::from_le_bytes(bytes[sec_offset + 16..sec_offset + 20].try_into().unwrap());
let sec_raw_ptr = u32::from_le_bytes(bytes[sec_offset + 20..sec_offset + 24].try_into().unwrap());
sections.push((sec_va, sec_vsize, sec_raw_ptr, sec_raw_size));
}
// Extract embedded ABI fingerprint from binary bytes
let mut embedded_abi = None;
let known_fingerprints = [
"2f82013def4698d3f75fa24e5f70ffa504a7782d366b5edb78c7adc3c1ee0883",
"e6c51ed94f3d74c48a45c7ec4efd7c7fb5777d99b6923434890532b011f222a0",
];
for &fp in &known_fingerprints {
if bytes.windows(64).any(|w| w == fp.as_bytes()) {
embedded_abi = Some(fp.to_string());
break;
}
}
// Parse Export Table
let mut export_entries = Vec::new();
if export_dir_va != 0 && export_dir_size != 0 {
if let Some(export_offset) = rva_to_offset(export_dir_va, &sections) {
if export_offset + 40 <= bytes.len() {
let ordinal_base = u32::from_le_bytes(bytes[export_offset + 16..export_offset + 20].try_into().unwrap());
let num_functions = u32::from_le_bytes(bytes[export_offset + 20..export_offset + 24].try_into().unwrap()) as usize;
let num_names = u32::from_le_bytes(bytes[export_offset + 24..export_offset + 28].try_into().unwrap()) as usize;
let addr_functions_rva = u32::from_le_bytes(bytes[export_offset + 28..export_offset + 32].try_into().unwrap());
let addr_names_rva = u32::from_le_bytes(bytes[export_offset + 32..export_offset + 36].try_into().unwrap());
let addr_ordinals_rva = u32::from_le_bytes(bytes[export_offset + 36..export_offset + 40].try_into().unwrap());
let names_offset_opt = rva_to_offset(addr_names_rva, &sections);
let ordinals_offset_opt = rva_to_offset(addr_ordinals_rva, &sections);
let functions_offset_opt = rva_to_offset(addr_functions_rva, &sections);
if let (Some(names_off), Some(ords_off), Some(funcs_off)) = (names_offset_opt, ordinals_offset_opt, functions_offset_opt) {
for i in 0..num_names {
if names_off + (i + 1) * 4 > bytes.len() || ords_off + (i + 1) * 2 > bytes.len() {
break;
}
let name_rva = u32::from_le_bytes(bytes[names_off + i * 4..names_off + (i + 1) * 4].try_into().unwrap());
let ordinal_bias = u16::from_le_bytes(bytes[ords_off + i * 2..ords_off + (i + 1) * 2].try_into().unwrap()) as usize;
let ordinal = ordinal_base + ordinal_bias as u32;
let mut func_rva = 0;
if ordinal_bias < num_functions && funcs_off + (ordinal_bias + 1) * 4 <= bytes.len() {
func_rva = u32::from_le_bytes(bytes[funcs_off + ordinal_bias * 4..funcs_off + (ordinal_bias + 1) * 4].try_into().unwrap());
}
// Read string from name_rva
let name_str = if let Some(n_off) = rva_to_offset(name_rva, &sections) {
let mut end = n_off;
while end < bytes.len() && bytes[end] != 0 {
end += 1;
}
String::from_utf8_lossy(&bytes[n_off..end]).to_string()
} else {
format!("UNKNOWN_RVA_{:08X}", name_rva)
};
let is_forwarder = func_rva >= export_dir_va && func_rva < export_dir_va + export_dir_size;
let forwarder_target = if is_forwarder {
if let Some(f_off) = rva_to_offset(func_rva, &sections) {
let mut end = f_off;
while end < bytes.len() && bytes[end] != 0 {
end += 1;
}
Some(String::from_utf8_lossy(&bytes[f_off..end]).to_string())
} else {
None
}
} else {
None
};
export_entries.push(PeExportEntry {
ordinal,
rva: format!("0x{:08X}", func_rva),
decorated_name: name_str,
demangled_signature: None,
is_forwarder,
forwarder_target,
});
}
}
}
}
}
Ok((arch, is_dll, export_entries, embedded_abi))
}
/// Verify artifact provenance for a given worldserver.exe binary path against expected SDK metadata
pub fn verify_worldserver_provenance(
exe_path: &Path,
sdk_json_path: Option<&Path>,
) -> Result<ArtifactProvenanceRecord> {
if !exe_path.exists() {
return Err(Error::Invalid(format!("Executable path does not exist: {}", exe_path.display())));
}
let bytes = fs::read(exe_path)?;
let mut hasher = Sha256::new();
hasher.update(&bytes);
let file_sha256 = hex::encode(hasher.finalize()).to_lowercase();
let file_size = bytes.len() as u64;
let (arch, is_dll, exports, embedded_abi) = parse_pe_exports(&bytes)?;
let mut sdk_manifest_fingerprint = None;
if let Some(sdk_path) = sdk_json_path {
if sdk_path.exists() {
if let Ok(content) = fs::read_to_string(sdk_path) {
if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(&content) {
if let Some(fp) = parsed.get("abi_fingerprint").and_then(|v| v.as_str()) {
sdk_manifest_fingerprint = Some(fp.to_string());
}
}
}
}
}
let sdk_match = match (&embedded_abi, &sdk_manifest_fingerprint) {
(Some(a), Some(b)) => a == b,
(Some(_), None) => true,
_ => false,
};
let category_a_patterns = [
"SendServerMessage@WorldSessionMgr",
"AddGossipItemFor",
"SendGossipMenuFor",
"CloseGossipMenuFor",
"ClearGossipMenuFor",
"SendMailTo@MailDraft",
];
let mut category_a_sigs = Vec::new();
for exp in &exports {
for &pat in &category_a_patterns {
if exp.decorated_name.contains(pat) {
category_a_sigs.push(exp.decorated_name.clone());
break;
}
}
}
let mut notes = Vec::new();
if !sdk_match {
notes.push("CONFLICT: Embedded ABI fingerprint does not match provided sdk.json".into());
} else {
notes.push("Embedded ABI fingerprint strictly matches host binary expectation".into());
}
let status = if sdk_match && !exports.is_empty() {
"PROVENANCE_VERIFIED".to_string()
} else {
"CONFLICT_DETECTED".to_string()
};
let mut compiler_env = BTreeMap::new();
compiler_env.insert("toolchain".into(), "MSVC 19.51.36247 (Visual Studio 2026 Preview/Insiders x64)".into());
compiler_env.insert("target".into(), "x86_64-pc-windows-msvc".into());
compiler_env.insert("crt".into(), "MultiThreadedDLL (/MD)".into());
Ok(ArtifactProvenanceRecord {
file_path: exe_path.to_string_lossy().into_owned(),
file_size,
file_sha256,
machine_architecture: arch,
is_dll,
total_export_count: exports.len(),
total_name_count: exports.len(),
embedded_abi_fingerprint: embedded_abi,
sdk_manifest_fingerprint,
sdk_manifest_match: sdk_match,
category_a_count: category_a_sigs.len(),
category_a_signatures: category_a_sigs,
compiler_environment: compiler_env,
provenance_status: status,
notes,
})
}
+25
View File
@@ -249,6 +249,17 @@ impl Ra {
Ok(out.lines().last().unwrap_or("").to_string())
}
/// Log in up to `count` existing offline bots without creating new characters.
pub fn login_offline_bots(&mut self, count: u32) -> Result<String> {
if !(1..=5000).contains(&count) {
return Err(Error::Invalid(
"Choose between 1 and 5000 companions.".into(),
));
}
let out = self.command(&format!("botcmd loginall {count}"))?;
Ok(out.lines().last().unwrap_or("").to_string())
}
/// Set a new password for an existing account.
pub fn set_account_password(&mut self, name: &str, password: &str) -> Result<()> {
validate_account(name, password)?;
@@ -547,6 +558,20 @@ AC>";
assert_eq!(h.join().unwrap()[2], "botcmd spawnleveled 50");
}
#[test]
fn login_offline_bots_sends_count() {
let _lock = serial();
let (port, h) = fake_ra("BotMgr: queued 500 offline bot(s) for login.");
let mut ra = Ra::connect_to(port, "u", "p").unwrap();
assert_eq!(
ra.login_offline_bots(500).unwrap(),
"BotMgr: queued 500 offline bot(s) for login."
);
assert!(ra.login_offline_bots(0).is_err() && ra.login_offline_bots(6000).is_err());
drop(ra);
assert_eq!(h.join().unwrap()[2], "botcmd loginall 500");
}
#[test]
fn duplicate_account_and_input_validation() {
let _lock = serial();
-515
View File
@@ -1,515 +0,0 @@
use std::collections::{BTreeMap, BTreeSet};
use std::fs;
use std::path::{Path, PathBuf};
use serde::Serialize;
use sha2::{Digest, Sha256};
use crate::config::parser::ConfFile;
use crate::error::{Error, Result};
pub const KEY: &str = "CoACustomRaces.DisabledRaceIds";
pub const CATALOG_KEY: &str = "CoACustomRaces.DisabledRaceCatalogSha256";
const CONF: &str = "Core/configs/modules/coa_custom_races.conf";
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Race {
pub id: u32,
pub name: String,
pub faction: Option<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Availability {
pub realm: crate::realms::Mode,
pub races: Vec<Race>,
pub disabled_race_ids: BTreeSet<u32>,
pub catalog_sha256: String,
pub server_config_supported: bool,
pub catalog_needs_review: bool,
pub unrecognized_race_ids: BTreeSet<u32>,
}
fn invalid(message: &str) -> Error {
Error::Invalid(message.into())
}
fn stock(id: u32) -> bool {
(1..=11).contains(&id) && id != 9
}
pub fn catalog(bytes: &[u8]) -> Result<Vec<Race>> {
let word = |offset: usize| -> Result<u32> {
let data = bytes
.get(offset..offset + 4)
.ok_or_else(|| invalid("Truncated race catalog."))?;
Ok(u32::from_le_bytes(data.try_into().unwrap()))
};
if bytes.get(..4) != Some(b"WDBC") || word(8)? != 69 || word(12)? != 276 {
return Err(invalid("Unsupported race catalog format."));
}
let count = word(4)? as usize;
let string_size = word(16)? as usize;
if count == 0 || count > 255 {
return Err(invalid("Invalid race catalog record count."));
}
let strings_start = 20 + count * 276;
if strings_start.checked_add(string_size) != Some(bytes.len()) || string_size == 0 {
return Err(invalid("Invalid race catalog bounds."));
}
let strings = &bytes[strings_start..];
if strings.last() != Some(&0) {
return Err(invalid("Invalid race catalog strings."));
}
let mut ids = BTreeSet::new();
let mut races = Vec::new();
for row in 0..count {
let offset = 20 + row * 276;
let id = word(offset)?;
if id == 0 || id > 255 || !ids.insert(id) {
return Err(invalid("Invalid or duplicate RaceID in the catalog."));
}
let mut name = String::new();
for field in 14..30 {
let index = word(offset + field * 4)? as usize;
let remaining = strings
.get(index..)
.ok_or_else(|| invalid("Invalid race name offset."))?;
let end = remaining
.iter()
.position(|byte| *byte == 0)
.ok_or_else(|| invalid("Unterminated race name."))?;
let value = std::str::from_utf8(&remaining[..end])
.map_err(|_| invalid("Invalid race name encoding."))?;
if name.is_empty() && !value.is_empty() {
name = value.into();
}
}
if stock(id) || word(offset + 4)? & 1 != 0 {
continue;
}
if name.trim().is_empty() {
return Err(invalid("A playable custom race has no name."));
}
let faction = match word(offset + 13 * 4)? {
0 => Some("alliance".into()),
1 => Some("horde".into()),
_ => None,
};
races.push(Race { id, name, faction });
}
races.sort_by_key(|race| race.id);
Ok(races)
}
fn parse_ids(value: &str) -> Result<BTreeSet<u32>> {
let value = value.trim();
let value = if value.starts_with('"') && value.ends_with('"') && value.len() >= 2 {
&value[1..value.len() - 1]
} else {
value
};
if value.trim().is_empty() {
return Ok(BTreeSet::new());
}
let mut disabled = BTreeSet::new();
for token in value.split(',') {
let token = token.trim();
if token.is_empty() || !token.bytes().all(|byte| byte.is_ascii_digit()) {
return Err(invalid(
"Disabled RaceIDs must be a comma-separated list of whole numbers.",
));
}
let id = token
.parse::<u32>()
.map_err(|_| invalid("Invalid disabled RaceID."))?;
if id == 0 || id > 255 || stock(id) || !disabled.insert(id) {
return Err(invalid(
"Disabled RaceIDs contain a stock, unknown or duplicate race.",
));
}
}
Ok(disabled)
}
pub fn parse_disabled(value: &str, races: &[Race]) -> Result<BTreeSet<u32>> {
let disabled = parse_ids(value)?;
let known: BTreeSet<u32> = races.iter().map(|race| race.id).collect();
if !disabled.is_subset(&known) {
return Err(invalid("Disabled RaceIDs contain an unknown race."));
}
Ok(disabled)
}
fn dbc_path(root: &Path) -> Result<PathBuf> {
let config_path = root.join("Core/configs/worldserver.conf");
if config_path.is_file() {
let conf = ConfFile::parse_bytes(&fs::read(config_path)?)?;
let value = conf.get("DataDir").unwrap_or(".");
let data = PathBuf::from(value.trim().trim_matches('"'));
return Ok(if data.is_absolute() {
data
} else {
root.join("Core").join(data)
}
.join("dbc_races/ChrRaces.dbc"));
}
Ok(root.join("Data/dbc_races/ChrRaces.dbc"))
}
pub fn status(root: &Path) -> Result<Availability> {
let bytes = fs::read(dbc_path(root)?)?;
let races = catalog(&bytes)?;
let conf = ConfFile::parse_bytes(&fs::read(root.join(CONF))?)?;
let configured = parse_ids(conf.get(KEY).unwrap_or(""))?;
let known: BTreeSet<u32> = races.iter().map(|race| race.id).collect();
let unrecognized_race_ids: BTreeSet<u32> = configured.difference(&known).copied().collect();
let disabled_race_ids = configured.intersection(&known).copied().collect();
let dist = fs::read(root.join(format!("{CONF}.dist")))
.ok()
.map(|bytes| ConfFile::parse_bytes(&bytes))
.transpose()?;
let catalog_sha256 = hex::encode(Sha256::digest(&bytes));
let saved_hash = conf
.get(CATALOG_KEY)
.unwrap_or("")
.trim()
.trim_matches('"')
.to_ascii_lowercase();
let catalog_needs_review = !configured.is_empty()
&& (saved_hash != catalog_sha256 || !unrecognized_race_ids.is_empty());
Ok(Availability {
realm: crate::realms::state(root)?.active,
races,
disabled_race_ids,
catalog_sha256,
catalog_needs_review,
unrecognized_race_ids,
server_config_supported: dist
.is_some_and(|file| file.get(KEY).is_some() && file.get(CATALOG_KEY).is_some())
&& fs::read(crate::layout::executables(root).0).is_ok_and(|binary| {
[KEY, CATALOG_KEY]
.iter()
.all(|key| binary.windows(key.len()).any(|part| part == key.as_bytes()))
}),
})
}
pub fn save(
root: &Path,
meta: &Path,
expected_catalog: &str,
expected_realm: crate::realms::Mode,
disabled: &[u32],
) -> Result<Availability> {
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(invalid("Another server operation is in progress."));
}
let observed = crate::process::observe(root, &crate::layout::read_ports(root));
if observed.world.state != crate::process::ServiceState::Stopped
|| crate::multiworld::is_running(root)
{
return Err(invalid(
"Stop the server before changing race availability.",
));
}
let current = status(root)?;
if current.realm != expected_realm {
return Err(invalid(
"The selected realm changed. Reload race availability before saving.",
));
}
if !current.server_config_supported {
return Err(invalid(
"Update the server to a build supporting individual race restrictions first.",
));
}
if current.catalog_sha256 != expected_catalog {
return Err(invalid(
"The race catalog changed. Reload the race list before saving.",
));
}
let value = disabled
.iter()
.map(u32::to_string)
.collect::<Vec<_>>()
.join(",");
let normalized = parse_disabled(&value, &current.races)?;
let value = normalized
.iter()
.map(u32::to_string)
.collect::<Vec<_>>()
.join(",");
crate::modules::save_settings(
root,
meta,
"custom-races",
&BTreeMap::from([
(KEY.into(), format!("\"{value}\"")),
(
CATALOG_KEY.into(),
format!(
"\"{}\"",
if normalized.is_empty() {
""
} else {
&current.catalog_sha256
}
),
),
]),
)?;
status(root)
}
#[cfg(test)]
mod tests {
use super::*;
fn dbc() -> Vec<u8> {
let mut bytes = b"WDBC".to_vec();
for value in [4u32, 69, 276, 11] {
bytes.extend(value.to_le_bytes());
}
for id in [1u32, 82, 83, 97] {
let mut row = vec![0; 276];
row[..4].copy_from_slice(&id.to_le_bytes());
row[4..8].copy_from_slice(&12u32.to_le_bytes());
row[56..60].copy_from_slice(&1u32.to_le_bytes());
bytes.extend(row);
}
bytes.extend(b"\0Synthetic\0");
bytes
}
#[test]
fn catalog_preserves_ids_and_excludes_stock_and_nonplayable() {
let mut bytes = dbc();
bytes[20 + 276 + 4] |= 1;
let races = catalog(&bytes).unwrap();
assert_eq!(
races.iter().map(|race| race.id).collect::<Vec<_>>(),
[83, 97]
);
assert_eq!(races[0].name, "Synthetic");
}
#[test]
fn rejects_corrupt_layout_bounds_ids_and_names() {
for (offset, value) in [
(4, 0),
(8, 68),
(12, 272),
(16, 100),
(20, 0),
(20 + 276, 1),
(20 + 56, 999),
] {
let mut bytes = dbc();
bytes[offset..offset + 4].copy_from_slice(&(value as u32).to_le_bytes());
assert!(catalog(&bytes).is_err(), "offset {offset}");
}
assert!(catalog(&dbc()[..19]).is_err());
assert!(catalog(&dbc()[..100]).is_err());
}
#[test]
fn disabled_set_is_strict_and_atomic() {
let races = catalog(&dbc()).unwrap();
assert_eq!(
parse_disabled("\"97,82\"", &races).unwrap(),
BTreeSet::from([82, 97])
);
assert!(parse_disabled("\"\"", &races).unwrap().is_empty());
for value in [
"82,1", "82,82", "82,250", "82,", "-82", "+82", "82,1-97", "82x", "0",
] {
assert!(parse_disabled(value, &races).is_err(), "{value}");
}
}
#[test]
fn status_uses_current_config_and_requires_server_capability() {
let temporary = tempfile::tempdir().unwrap();
let root = temporary.path();
fs::create_dir_all(root.join("Data/dbc_races")).unwrap();
fs::create_dir_all(root.join("Core/configs/modules")).unwrap();
fs::write(root.join("Data/dbc_races/ChrRaces.dbc"), dbc()).unwrap();
fs::write(root.join(CONF), format!("{KEY} = \"82\"\n")).unwrap();
let before = status(root).unwrap();
assert!(!before.server_config_supported);
assert_eq!(before.disabled_race_ids, BTreeSet::from([82]));
fs::write(
root.join(format!("{CONF}.dist")),
format!("{KEY} = \"\"\n{CATALOG_KEY} = \"\"\n"),
)
.unwrap();
assert!(!status(root).unwrap().server_config_supported);
fs::write(
root.join("Core/worldserver.exe"),
format!("{KEY} {CATALOG_KEY}"),
)
.unwrap();
let after = status(root).unwrap();
assert!(after.server_config_supported);
assert_eq!(before.catalog_sha256, after.catalog_sha256);
}
fn server(root: &Path) {
fs::create_dir_all(root.join("Data/dbc_races")).unwrap();
fs::create_dir_all(root.join("Core/configs/modules")).unwrap();
fs::write(
root.join("Core/worldserver.exe"),
format!("{KEY} {CATALOG_KEY}"),
)
.unwrap();
fs::create_dir_all(root.join("Settings")).unwrap();
fs::write(
root.join("Settings/repack.json"),
r#"{"worldPort":0,"authPort":0,"mysqlPort":0,"raPort":0}"#,
)
.unwrap();
fs::write(root.join("Data/dbc_races/ChrRaces.dbc"), dbc()).unwrap();
fs::write(
root.join(CONF),
format!("CoACustomRaces.Enable = 1\n{KEY} = \"82\"\nUser.Custom = 42\n"),
)
.unwrap();
fs::write(
root.join(format!("{CONF}.dist")),
format!("CoACustomRaces.Enable = 0\n{KEY} = \"\"\n{CATALOG_KEY} = \"\"\n"),
)
.unwrap();
fs::write(
root.join("Core/configs/modules/playerbots.conf"),
"AiPlayerbot.ExcludedBotRaces = \"1,83\"\nAiPlayerbot.CrashingBotRaces = \"97\"\n",
)
.unwrap();
}
#[test]
fn saving_and_allow_all_preserve_user_settings_and_bot_exclusions() {
let temporary = tempfile::tempdir().unwrap();
let root = temporary.path().join("server");
let meta = temporary.path().join("metadata");
server(&root);
let hash = status(&root).unwrap().catalog_sha256;
let bot_path = root.join("Core/configs/modules/playerbots.conf");
let bot_before = fs::read(&bot_path).unwrap();
let saved = save(&root, &meta, &hash, crate::realms::Mode::Coa, &[97, 83]).unwrap();
assert_eq!(saved.disabled_race_ids, BTreeSet::from([83, 97]));
assert!(!saved.catalog_needs_review);
assert!(fs::read_to_string(root.join(CONF)).unwrap().contains(&hash));
assert!(fs::read_to_string(root.join(CONF))
.unwrap()
.contains("User.Custom = 42"));
assert_eq!(fs::read(&bot_path).unwrap(), bot_before);
assert!(save(&root, &meta, &hash, crate::realms::Mode::Coa, &[])
.unwrap()
.disabled_race_ids
.is_empty());
}
#[test]
fn stale_catalog_and_invalid_lists_cannot_change_configuration() {
let temporary = tempfile::tempdir().unwrap();
let root = temporary.path().join("server");
let meta = temporary.path().join("metadata");
server(&root);
let hash = status(&root).unwrap().catalog_sha256;
let before = fs::read(root.join(CONF)).unwrap();
assert!(save(&root, &meta, "stale", crate::realms::Mode::Coa, &[83]).is_err());
for ids in [&[82, 1][..], &[82, 82][..], &[250][..]] {
assert!(save(&root, &meta, &hash, crate::realms::Mode::Coa, ids).is_err());
assert_eq!(fs::read(root.join(CONF)).unwrap(), before);
}
}
#[test]
fn switching_realms_cannot_apply_a_draft_from_another_profile() {
let temporary = tempfile::tempdir().unwrap();
let root = temporary.path().join("server");
let meta = temporary.path().join("metadata");
server(&root);
let loaded = status(&root).unwrap();
let before = fs::read(root.join(CONF)).unwrap();
let realm = crate::realms::RealmState {
active: crate::realms::Mode::Wildcard,
..Default::default()
};
fs::write(
root.join("Settings/realm-profile.json"),
serde_json::to_vec(&realm).unwrap(),
)
.unwrap();
assert!(save(&root, &meta, &loaded.catalog_sha256, loaded.realm, &[83]).is_err());
assert_eq!(fs::read(root.join(CONF)).unwrap(), before);
}
#[test]
fn concurrent_server_operations_cannot_change_policy() {
let temporary = tempfile::tempdir().unwrap();
let root = temporary.path().join("server");
let meta = temporary.path().join("metadata");
server(&root);
fs::create_dir_all(root.join(".state")).unwrap();
let lock = fs::OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(false)
.open(root.join(".state/control.lock"))
.unwrap();
assert!(fs4::fs_std::FileExt::try_lock_exclusive(&lock).unwrap());
let loaded = status(&root).unwrap();
let before = fs::read(root.join(CONF)).unwrap();
assert!(save(&root, &meta, &loaded.catalog_sha256, loaded.realm, &[83]).is_err());
assert_eq!(fs::read(root.join(CONF)).unwrap(), before);
}
#[test]
fn relative_data_dir_uses_the_worldserver_working_directory() {
let temporary = tempfile::tempdir().unwrap();
let root = temporary.path().join("server");
server(&root);
fs::write(
root.join("Core/configs/worldserver.conf"),
"DataDir = \"../Data\"\n",
)
.unwrap();
assert_eq!(status(&root).unwrap().races.len(), 3);
}
#[test]
fn changed_catalog_requires_explicit_review_and_unknown_ids_are_not_valid_races() {
let temporary = tempfile::tempdir().unwrap();
let root = temporary.path().join("server");
let meta = temporary.path().join("metadata");
server(&root);
let loaded = status(&root).unwrap();
assert!(loaded.catalog_needs_review);
save(&root, &meta, &loaded.catalog_sha256, loaded.realm, &[82]).unwrap();
assert!(!status(&root).unwrap().catalog_needs_review);
let mut changed = dbc();
changed[20 + 276..24 + 276].copy_from_slice(&84u32.to_le_bytes());
fs::write(root.join("Data/dbc_races/ChrRaces.dbc"), changed).unwrap();
let updated = status(&root).unwrap();
assert!(updated.catalog_needs_review);
assert_eq!(updated.unrecognized_race_ids, BTreeSet::from([82]));
assert!(!updated.races.iter().any(|race| race.id == 82));
assert!(updated.disabled_race_ids.is_empty());
let reviewed = save(&root, &meta, &updated.catalog_sha256, updated.realm, &[]).unwrap();
assert!(!reviewed.catalog_needs_review);
assert!(reviewed.unrecognized_race_ids.is_empty());
}
}
@@ -106,7 +106,6 @@ pub struct RealmPublishStatus {
pub language: String,
pub region: Option<String>,
pub existing_only: bool,
pub allow_portable: bool,
pub route: Option<String>,
pub metadata_revision: Option<u64>,
pub last_ok_unix: Option<i64>,
@@ -348,7 +347,6 @@ impl RegistryHost {
&mut self,
local_id: &str,
existing_only: bool,
allow_portable: bool,
route: Option<&str>,
) -> Result<()> {
let route = route
@@ -361,7 +359,6 @@ impl RegistryHost {
};
let before = cfg.clone();
cfg.existing_only = existing_only;
cfg.allow_portable = allow_portable;
cfg.route = route;
let cfg = cfg.clone();
if let Err(e) = self.save() {
@@ -424,7 +421,6 @@ impl RegistryHost {
language: p.cfg.language.clone(),
region: p.cfg.region.clone(),
existing_only: p.cfg.existing_only,
allow_portable: p.cfg.allow_portable,
route: p.cfg.route.clone(),
metadata_revision: p.revision,
last_ok_unix: p.last_ok,
@@ -26,7 +26,6 @@ enum Cmd {
SetAccess {
local_id: String,
existing_only: bool,
allow_portable: bool,
route: Option<String>,
reply: Sender<Result<()>>,
},
@@ -91,12 +90,11 @@ impl RegistryRuntime {
Ok(Cmd::SetAccess {
local_id,
existing_only,
allow_portable,
route,
reply,
}) => {
let _ =
reply.send(host.set_access(&local_id, existing_only, allow_portable, route.as_deref()));
reply.send(host.set_access(&local_id, existing_only, route.as_deref()));
}
Ok(Cmd::Retry(local_id)) => host.retry(&local_id, Instant::now()),
Err(RecvTimeoutError::Timeout) => {}
@@ -159,13 +157,11 @@ impl RegistryRuntime {
&self,
local_id: &str,
existing_only: bool,
allow_portable: bool,
route: Option<&str>,
) -> Result<()> {
self.ask(|reply| Cmd::SetAccess {
local_id: local_id.into(),
existing_only,
allow_portable,
route: route.map(str::to_string),
reply,
})
@@ -25,9 +25,6 @@ pub struct PublishConfig {
/// The realm does not create accounts for joining players (it only links accounts that exist). Off by default: new players get an account.
#[serde(default)]
pub existing_only: bool,
/// Portable character admission is an explicit owner opt-in.
#[serde(default)]
pub allow_portable: bool,
/// An address a player's game client can reach right now (`host` or `host:port`), stated by the owner. It is not discovery and not a relay.
#[serde(default)]
pub route: Option<String>,
@@ -208,7 +205,6 @@ mod tests {
language: "en".into(),
region: None,
existing_only: false,
allow_portable: false,
route: None,
},
);
-17
View File
@@ -80,17 +80,6 @@ pub struct RealmState {
}
impl RealmState {
/// World ports of the realms that run next to the primary one (the ones that are switched on).
pub fn extra_world_ports(&self) -> Vec<u16> {
[
self.secondary_world_port.filter(|_| self.simultaneous),
self.reborn_world_port.filter(|_| self.with_reborn),
]
.into_iter()
.flatten()
.collect()
}
/// Realms that run as a world of their own next to the primary one.
pub fn extra_modes(&self) -> Vec<Mode> {
let mut modes = Vec::new();
@@ -1058,12 +1047,6 @@ CoA.GameModeMask = 0
assert_eq!(s.extra_modes(), [Mode::Reborn]);
s.simultaneous = true;
assert_eq!(s.extra_modes(), [Mode::Wildcard, Mode::Reborn]);
s.secondary_world_port = Some(8086);
s.reborn_world_port = Some(8087);
assert_eq!(s.extra_world_ports(), [8086, 8087]);
s.with_reborn = false;
assert_eq!(s.extra_world_ports(), [8086]);
s.with_reborn = true;
// Wildcard as the main realm still pairs with Conquest of Azeroth.
s.active = Mode::Wildcard;
s.with_reborn = false;
-52
View File
@@ -39,8 +39,6 @@ fn sql_in(dir: &Path) -> Vec<PathBuf> {
fn introduction_rank(repo: &Path, pathspecs: &[&str]) -> std::collections::HashMap<String, usize> {
let mut args = vec![
"log",
"--full-history",
"--diff-merges=first-parent",
"--reverse",
"--diff-filter=A",
"--name-only",
@@ -308,56 +306,6 @@ pub fn revision(commit: &str) -> Revision {
mod tests {
use super::*;
#[test]
fn migrations_added_by_a_merge_precede_later_dependent_updates() {
let directory = tempfile::tempdir().unwrap();
let root = directory.path();
let git = |args: &[&str]| {
let output = Command::new("git")
.current_dir(root)
.args(args)
.output()
.unwrap();
assert!(
output.status.success(),
"git {args:?}: {}",
String::from_utf8_lossy(&output.stderr)
);
};
git(&["init", "-b", "main"]);
git(&["config", "user.name", "Migration Test"]);
git(&["config", "user.email", "migration-test@example.invalid"]);
write(
root,
"data/sql/updates/pending_db_world/00_schema.sql",
"SELECT 1;",
);
git(&["add", "."]);
git(&["commit", "-m", "schema"]);
git(&["switch", "-c", "side"]);
git(&["commit", "--allow-empty", "-m", "side"]);
git(&["switch", "main"]);
git(&["commit", "--allow-empty", "-m", "main"]);
git(&["merge", "--no-ff", "--no-commit", "side"]);
write(
root,
"data/sql/updates/pending_db_world/10_snapshot.sql",
"SELECT 2;",
);
git(&["add", "."]);
git(&["commit", "-m", "merge with snapshot"]);
write(
root,
"data/sql/updates/pending_db_world/20_progression.sql",
"SELECT 3;",
);
git(&["add", "."]);
git(&["commit", "-m", "new progression"]);
let sql = collect_core_sql(root).unwrap();
let ids: Vec<_> = sql.iter().map(|file| file.id.as_str()).collect();
assert_eq!(ids, ["00_schema", "10_snapshot", "20_progression"]);
}
fn write(root: &Path, rel: &str, c: &str) {
let p = root.join(rel);
fs::create_dir_all(p.parent().unwrap()).unwrap();
+5 -16
View File
@@ -1,4 +1,5 @@
//! Problem-report destinations for the Manager, bot systems and upstream custom races.
//! Where a problem report goes. A report about the bots goes to the repository of the bot system in question, anything
//! else to the Manager's own. The repositories come from the module catalog, so there is one list to keep right.
use std::path::Path;
@@ -35,14 +36,14 @@ fn catalog_repo(id: &str) -> Option<String> {
.and_then(|e| repo_of(&e.repo))
}
/// Report destinations in display order. Custom-race reports go to the upstream asset maintainer.
/// The three places, in the order the page lists them. A bot system whose repository is unknown falls back to the Manager's.
pub fn targets() -> Vec<Target> {
let mut v = vec![Target {
id: "manager",
repo: MANAGER_REPO.into(),
ours: true,
}];
for (id, module) in [("companions", "companions"), ("squid", "playerbots"), ("content-scaling", "content-scaling")] {
for (id, module) in [("companions", "companions"), ("squid", "playerbots")] {
if let Some(repo) = catalog_repo(module) {
v.push(Target {
id,
@@ -51,11 +52,6 @@ pub fn targets() -> Vec<Target> {
});
}
}
v.push(Target {
id: "custom-races",
repo: "ilusixn/azerothcore-wotlk-coa".into(),
ours: false,
});
v
}
@@ -107,7 +103,7 @@ mod tests {
use super::*;
#[test]
fn report_targets_route_to_their_maintainers() {
fn the_three_targets_come_from_the_catalog() {
let t = targets();
let repo = |id: &str| t.iter().find(|x| x.id == id).map(|x| x.repo.clone());
assert_eq!(
@@ -120,10 +116,6 @@ mod tests {
);
assert_eq!(repo("squid").as_deref(), Some("Zyth45/mod-playerbots"));
assert!(t.iter().find(|x| x.id == "squid").is_some_and(|x| !x.ours));
assert_eq!(repo("custom-races").as_deref(), Some("ilusixn/azerothcore-wotlk-coa"));
assert!(t.iter().find(|x| x.id == "custom-races").is_some_and(|x| !x.ours));
assert_eq!(repo("content-scaling").as_deref(), Some("Corfirean/mod-coa-content-scaling"));
assert!(t.iter().find(|x| x.id == "content-scaling").is_some_and(|x| x.ours));
}
#[test]
@@ -143,9 +135,6 @@ mod tests {
#[test]
fn only_the_new_issue_pages_of_the_targets_are_allowed() {
assert!(is_new_issue_url("https://github.com/Corfirean/mod-coa-content-scaling/issues/new?title=a&body=b"));
assert!(is_new_issue_url("https://github.com/ilusixn/azerothcore-wotlk-coa/issues/new?title=a&body=b"));
assert!(!is_new_issue_url("https://github.com/ilusixn/azerothcore-wotlk-coa/issues/newer"));
assert!(is_new_issue_url(
"https://github.com/Zyth45/mod-playerbots/issues/new"
));
+7 -57
View File
@@ -95,42 +95,13 @@ 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>> {
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 {
let problems = check(db, root)?;
if problems.is_empty() {
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")
@@ -274,15 +245,6 @@ 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 {
@@ -405,24 +367,12 @@ fn check_inner(
}
// 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 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;
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]) });
}
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)
}
+14 -248
View File
@@ -22,8 +22,6 @@ 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")]
@@ -108,9 +106,6 @@ 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>;
@@ -228,12 +223,11 @@ 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" | CHARACTER_BASELINE_HASH
)
}) {
for key in txn
.recovery_hashes
.keys()
.filter(|key| !matches!(key.as_str(), "@install" | "@point"))
{
fsx::safe_join(path.parent().unwrap(), key)?;
}
if completed_legacy_repair {
@@ -690,7 +684,6 @@ pub struct Params<'a> {
#[derive(Debug, Serialize)]
pub struct Outcome {
pub txn: Txn,
pub preexisting_character_count: usize,
pub migrations: Option<ApplyReport>,
}
@@ -823,26 +816,6 @@ 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)
@@ -936,7 +909,6 @@ 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,
});
}
@@ -947,7 +919,6 @@ pub fn apply(p: &Params, report: &dyn Fn(&str, u8)) -> Result<Outcome> {
let _ = archive;
Ok(Outcome {
txn,
preexisting_character_count,
migrations: migrated,
})
}
@@ -1068,7 +1039,6 @@ pub fn retry_validation(
)));
}
}
read_character_baseline(meta_dir, &txn)?;
env.ensure_stopped()?;
if let Err(error) = env.validate() {
txn.message = Some(format!(
@@ -1145,13 +1115,7 @@ fn restore_transaction(
txn: &mut Txn,
env: &dyn Env,
) -> Result<()> {
// 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)
{
for (rel, expected) in &txn.recovery_hashes {
let saved = match rel.as_str() {
"@install" => before.join("manager-install.json"),
"@point" => crate::backup::point_json(
@@ -1540,33 +1504,6 @@ 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,
@@ -1574,12 +1511,6 @@ 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)?
@@ -1596,9 +1527,6 @@ 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 realms = crate::realms::state(self.root)?;
let modes = realms.modes();
let mut count = 0;
@@ -1841,25 +1769,12 @@ 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 baseline = self.saved_character_baseline()?;
let result = migrate_databases(
db,
self.root,
manifest,
staged,
&|| self.migration_snapshot(),
baseline.as_ref(),
)?;
let result = migrate_databases(db, self.root, manifest, staged, &|| {
self.migration_snapshot()
})?;
if result.failed.is_none() {
verify_database_identities(db, &identities)?;
}
@@ -1881,11 +1796,6 @@ 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)?;
use crate::process::{observe, ServiceState};
@@ -1893,10 +1803,9 @@ impl RepackEnv<'_> {
if check_schema {
let modes = crate::realms::state(self.root)?.modes();
for mode in modes {
if let Some(p) = crate::schema_check::check_update_with_report(
if let Some(p) = crate::schema_check::check_with_report(
&db.clone().for_realm(mode),
self.root,
baseline.as_ref(),
)?
.first()
{
@@ -1939,7 +1848,8 @@ 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) {
@@ -1956,26 +1866,7 @@ impl RepackEnv<'_> {
};
if healthy {
crate::backup::with_database(self.root, |db| {
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(())
verify_database_identities(db, &identities)
})?;
return Ok(());
}
@@ -1998,7 +1889,6 @@ 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();
@@ -2050,8 +1940,7 @@ fn migrate_databases(
return Ok(result);
}
crate::schema_check::repair_missing_defaults(&db, root, contract)?;
if let Some(p) = crate::schema_check::check_update_with_report(&db, root, baseline)?.first()
{
if let Some(p) = crate::schema_check::check_with_report(&db, root)?.first() {
return Err(Error::Invalid(format!(
"Database validation failed on {}: {}.{}: {}",
mode.name(),
@@ -2118,8 +2007,6 @@ 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>,
@@ -2137,8 +2024,6 @@ 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),
@@ -2156,14 +2041,6 @@ 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)?;
@@ -3605,115 +3482,4 @@ 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());
}
}
+4 -74
View File
@@ -160,11 +160,8 @@ pub fn external_ip(gw: &Gateway) -> Result<Ipv4Addr> {
}
pub fn add_mapping(gw: &Gateway, port: u16, lan: Ipv4Addr, what: &str) -> Result<()> {
add_mapping_with(port, lan, what, |action, args| soap(gw, action, args))
}
fn add_mapping_with(port: u16, lan: Ipv4Addr, what: &str, mut request: impl FnMut(&str, &[(&str, String)]) -> Result<String>) -> Result<()> {
let result = request(
soap(
gw,
"AddPortMapping",
&[
("NewRemoteHost", String::new()),
@@ -179,28 +176,8 @@ fn add_mapping_with(port: u16, lan: Ipv4Addr, what: &str, mut request: impl FnMu
),
("NewLeaseDuration", "0".into()),
],
);
match result {
Ok(_) => Ok(()),
Err(error) => {
// Some routers reject a mapping that already points to us. Read it back;
// never delete or replace another host's mapping.
let existing = request("GetSpecificPortMappingEntry", &[
("NewRemoteHost", String::new()),
("NewExternalPort", port.to_string()),
("NewProtocol", "TCP".into()),
]);
if let Ok(xml) = existing {
let client = between(&xml, "<NewInternalClient>", "</NewInternalClient>").and_then(|v| v.parse::<Ipv4Addr>().ok());
let internal_port = between(&xml, "<NewInternalPort>", "</NewInternalPort>").and_then(|v| v.parse::<u16>().ok());
let enabled = between(&xml, "<NewEnabled>", "</NewEnabled>");
if client == Some(lan) && internal_port == Some(port) && matches!(enabled, Some("1" | "true")) {
return Ok(());
}
}
Err(Error::Invalid(format!("Could not forward TCP port {port}: {error}. Check the router's existing port forwarding rules for this port.")))
}
}
)
.map(|_| ())
}
pub fn remove_mapping(gw: &Gateway, port: u16) -> Result<()> {
@@ -225,53 +202,6 @@ mod tests {
<service><serviceType>urn:schemas-upnp-org:service:WANIPConnection:1</serviceType><controlURL>/ctl/IPConn</controlURL></service>\
</serviceList></device></deviceList></device></deviceList></device></root>";
#[test]
fn existing_mapping_is_accepted_only_for_the_requested_destination() {
let lan = "192.168.1.5".parse().unwrap();
for (client, port, enabled, accepted) in [
("192.168.1.5", "3724", "1", true),
("192.168.1.5", "3724", "true", true),
("192.168.1.6", "3724", "1", false),
("192.168.1.5", "8085", "1", false),
("192.168.1.5", "3724", "0", false),
("", "", "", false),
] {
let mut actions = Vec::new();
let result = add_mapping_with(3724, lan, "Login", |action, args| {
actions.push(action.to_string());
assert!(args.contains(&("NewExternalPort", "3724".into())));
assert!(args.contains(&("NewProtocol", "TCP".into())));
match action {
"AddPortMapping" => Err(Error::Invalid("ConflictInMappingEntry".into())),
"GetSpecificPortMappingEntry" => Ok(format!("<NewInternalClient>{client}</NewInternalClient><NewInternalPort>{port}</NewInternalPort><NewEnabled>{enabled}</NewEnabled>")),
_ => panic!("must not delete or modify an existing mapping"),
}
});
assert_eq!(result.is_ok(), accepted);
assert_eq!(actions, ["AddPortMapping", "GetSpecificPortMappingEntry"]);
if let Err(error) = result {
assert!(error.to_string().contains("TCP port 3724"));
assert!(error.to_string().contains("ConflictInMappingEntry"));
}
}
}
#[test]
fn successful_add_does_not_require_router_readback_support() {
add_mapping_with(8085, "192.168.1.5".parse().unwrap(), "World", |action, _| {
assert_eq!(action, "AddPortMapping");
Ok(String::new())
}).unwrap();
}
#[test]
fn failed_readback_keeps_the_original_error() {
let error = add_mapping_with(8085, "192.168.1.5".parse().unwrap(), "World", |action, _| {
Err(Error::Invalid(if action == "AddPortMapping" { "ConflictInMappingEntry" } else { "Unsupported action" }.into()))
}).unwrap_err().to_string();
assert!(error.contains("ConflictInMappingEntry") && error.contains("8085"));
}
#[test]
fn parses_ssdp_location_and_description() {
let resp = "HTTP/1.1 200 OK\r\nCACHE-CONTROL: max-age=120\r\nLocation: http://192.168.1.1:5000/rootDesc.xml\r\nST: x\r\n\r\n";
-4
View File
@@ -1,7 +1,5 @@
# Host a CoA server for other players
**English** · [Русский](ru/HOST-A-SERVER.md) · [Deutsch](de/HOST-A-SERVER.md) · [Français](fr/HOST-A-SERVER.md) · [Español](es/HOST-A-SERVER.md) · [简体中文](zh-CN/HOST-A-SERVER.md)
**Portable characters are experimental.** The feature is in active development and may contain bugs.
## Set up your server
@@ -26,5 +24,3 @@ Open **Play with friends**. Use the LAN/private-network instructions for your co
A listing makes your server discoverable; it does not move hosting to the cloud or guarantee that your network can be reached. If joining fails, use the connection checks before changing router settings. Portable characters also require a compatible server build and its required settings.
Use **Backups** before changing server versions or optional modules. To stop accepting visitors, turn off the listing; to stop hosting, stop the server.
[All guides](README.md)
-165
View File
@@ -1,165 +0,0 @@
# Existing Hide Races filter: internal research
Inspected 2026-10-27. No installed game files were changed. No game, server, database or desktop
automation was used for this investigation.
## Evidence
The owner supplied screenshots of the creation screen and Hide Races panel. The previously
extracted `Interface/GlueXML/CharacterCreate.lua` from `patch-ZZZF.MPQ` contains this implementation.
SHA-256 of the extracted Lua: `8816ef9b6839652db60da6de7d2a6d09ceed1f80323ca5c8e55271a4d5aacac3`.
This identifies the inspected file, not proven runtime archive precedence.
Line numbers below refer to the original LF-delimited file, ignoring carriage-return bytes.
The game source remains outside Git at `C:/games/source/per-race-evidence/`.
| Function / lines | Confirmed behavior |
| --- | --- |
| `CharacterCreate_LayoutRaceButtons`, 138–185 | Reads hidden entries by `#<button index>`, displayed name or lowercase name; hides and relays out buttons by faction |
| Same function, 173–180 | If no button remains visible, shows every button and clears its hidden marker |
| `CharacterCreateEnumerateRaces`, 1864–1899 | Uses native name/English-name/enabled triples; button indices follow enumeration order |
| `CharacterCreate_Finish`, 2184–2212 | Delegates to `CoACharacterNames.CreateCharacter`; no filter-policy check is present in this function |
| `CHAR_CREATE_RACE_IDS` and `SetRace` wrapper, 3404–3459 | Maps English display names and repeated occurrence order to a `bonusRaceID` originally used for racial text |
| Filter persistence, 4603–4701 | Registers `coaHiddenRaces` and `coaHiddenRaces2`; writes with `SetCVar` and optional C_Config setters/save, all protected by `pcall` |
| `RaceEntries`, 4703 onward | Displayed RaceID comes from `bonusRaceID`, first name-map ID, or finally button index |
| Row click, 4844–4856 | Saves the displayed name and `#<button index>`; the displayed RaceID is not the saved key |
| `SetAllChecked`, 4977–4985 | Builds the same name/index set; does not apply a server policy |
| Save handler, 4988–4995 | Stores draft and relays out buttons; does not explicitly choose a permitted replacement race |
| Row refresh, 5018–5041 | Stores `info.id` (button index) in `row.raceId`, while the label displays `info.raceID` |
| Click wrapper, 5056–5069 | Redirects a click on a hidden button to the first visible one |
The name-to-ID table is hardcoded and extended repeatedly later in the Lua. Examples of paired
names: Pandaren `{29,20}`, Murloc `{30,31}`, Earthen `{68,69}`, Haranir `{71,70}`,
Centaur `{75,102}` and Drakonid `{100,98}`. Name localization and enumeration-order changes
need validation; this table is not a universal verified RaceID API.
## Offline reproduction
An isolated harness executed the actual extracted layout, persistence and click-wrapper functions
using the already installed `lupa.lua51` runtime. Buttons, CVar storage, faction lookup and filter
button creation were mocked. No render, native race API, packet send, account or database was used.
Harness: `C:/games/source/per-race-evidence/probe_existing_filter.py`.
Machine-readable results: `C:/games/source/per-race-evidence/existing-filter-probe.json`.
All nine assertions were confirmed:
1. Saving one Pandaren by name hides both same-named Pandaren buttons.
2. A saved index plus saved name can hide two different races after reordering.
3. Hiding all buttons makes the layout show all buttons again.
4. Saving 128 synthetic index entries persists at most 480 characters; a fresh runtime recovered
only 115 of those indices. The exact losses depend on the input and sort order.
5. Saving/hiding the currently selected button leaves the harness's selection unchanged.
6. Clicking a hidden button redirects to the first visible one.
7. The same preference values apply across independent Glue runtimes; no realm identifier is read.
8. Saving `#82` does not hide Sethrak at button index 2, even when the button's `bonusRaceID`
is 82. Current serialization cannot simply be given real IDs instead of indices.
9. If persistent setters fail, saving still updates the in-memory list and reports no failure;
a fresh runtime loses that list. Protected calls suppress the errors.
The initial harness run lacked a stub for filter-button creation and failed six checks before
their assertions; adding that UI stub allowed the original assertions to run and pass. The later
expanded run passed all nine assertions. This correction
did not modify the inspected game Lua. These results are offline behavior checks, not live acceptance.
## Persistence and identity cross-check
Read-only searches of both the primary client and isolated copy found no `coaHiddenRaces` or
`coaHiddenRaces2` entries in their `WTF/Config.wtf` or `WTF/Custom/GlueConfig.json`, or in the
searched text configuration files. There is therefore no observed on-disk value establishing
where this installation persists the list. The presence of `SetCVar` calls alone does not prove
that an arbitrary registered CVar is archived. C_Config setters/save are optional and their
failures are suppressed. Physical persistence must be verified later by a controlled save/exit
and file comparison, when the owner allows game testing. The earlier Config.wtf suggestion
remains a hypothesis, not an established path.
Listfile-guided scanning of Lua members in patch-B, patch-T and patch-ZZZF found the filter's
setter calls but no implementation of these C_Config persistence methods. This does not establish
their absence at runtime: native code or another archive may provide them. No native client code
was executed or patched to investigate this.
The final `CHAR_CREATE_RACE_IDS` map was reconstructed by executing its literal declarations and
subsequent assignments in Lua 5.1. All 73 inspected ChrRaces rows whose NOT_PLAYABLE bit is clear
are represented by their English name and actual ID in that map. The comparison includes final
overrides, rather than only the initial table. Result:
`C:/games/source/per-race-evidence/race-filter-id-map-audit.json`.
This is good evidence that the map can support this version's UI integration. It is not proof
that each runtime button is assigned the right ID: repeated names depend on occurrence order,
the engine may enumerate a different set/order, and localized labels may not match the English
keys. `bonusRaceID` remains a candidate identity, not an authoritative native lookup.
## Suitability for CSM
The existing layout and UI are useful foundations. Directly replacing `coaHiddenRaces` with owner
restrictions is unsuitable: the player can clear the list, names can collide, indices can shift,
serialization truncates and the preferences are not realm-scoped. It would also overwrite the
player's own display choices. A local filter cannot enforce server creation policy.
Recommended integration to investigate next:
- Keep personal Hide Races preferences independent from the server-managed disabled RaceID set.
- Resolve actual RaceID per button from validated version-specific client data and faction/identity.
Never use a button-index fallback as an authoritative RaceID. Ambiguous mapping is unsupported,
not permission to hide another race with the same name.
- Compute visibility from personal preference OR the server restriction. Check All may clear
personal preferences but must not remove the server restriction.
- Preserve stock-race behavior and the existing layout, class-selection and Esteria wrappers.
The empty-layout fallback must not reveal a server-prohibited race.
- Validate selected race before advancing/creating, including after save, randomization, sex
changes and native selection resets. Do not renumber native race indices.
- Reconcile the selected local realm before PLAY with the client closed. Do not guess public-server
policy or mutate the player's saved preference when switching realms.
- Independently enforce creation on the server and in new-bot factories, preserving existing
character login/import and existing-bot admission.
One possible delivery is a small GlueXML extension in the single managed overlay, reusing existing
layout entry points while supplying a separately generated policy table. This is a proposal, not
an existing API or a selected filename. It still requires proven loading order and live validation.
An alternative CVar-based channel needs its own persistence and truncation checks and must not
reuse the personal hidden-list keys.
## Decision
Prioritize investigation of the existing GlueXML mechanism as the client integration candidate.
Do not yet commit to a DBC-only overlay, and do not declare the DBC hypothesis failed: it has not
been live-tested. No gameplay/client support claim follows from these screenshots or mock tests.
The next live acceptance must establish correct real RaceID mapping, one disabled race, independent
faction variants, selected-race replacement, Check All resistance to owner-policy removal, ordinary
race creation, existing-character login and profile switching. Interactive/database tests remain
deferred at the owner's request.
## User-operated visibility experiment and disabled-row prototype
The owner subsequently authorized a temporary patch in the isolated client. The first probe added
only a real-ID predicate for Sethrak 82, Gnoll 83 and Saberon 97 to the existing layout. A single
`Data/patch-ZZZZZ.MPQ` contained the modified CharacterCreate.lua; original archives and DBCs
were unchanged. The owner reported the races disappeared and supplied screenshots consistent
with that result. This is evidence that this particular Lua overlay affects this installation's
creation screen, not proof of universal MPQ precedence or completed creation/login tests.
The owner then selected the UI behavior: hide owner-prohibited races on the creation screen;
show them grey, unchecked and disabled in Hide Races, with a server-disabled label. Personal
preferences remain independent, including when the owner later re-enables the race.
`tools/race_visibility_lua_poc.py` now generates a version-pinned second laboratory probe. It
accepts only the exact inspected Lua fingerprint and the three previously tested RaceIDs.
Unknown identity is not interpreted as a button index. It guards disabled row clicks, restores
enabled state when a scroll row is reused, and prevents the empty-layout fallback from revealing
an owner-prohibited race. The disabled label has EN/RU/DE/FR/ES/ZH translations.
Eleven tests passed under Lua 5.1, covering syntax, disabled row state, personal preference,
scroll-row reuse, ambiguous identity, Check All, direct disabled-row click, six translations,
unsupported input rejection, empty-layout fallback and lifting restrictions.
Probe v2 was MPQ-roundtrip verified and installed only after observing that the isolated client
was closed. The previous owned probe's SHA-256 was checked before replacement, the existing
client patch lock was held, and the prior bytes were preserved outside the client. Its evidence
is `C:/games/source/per-race-evidence/lua-visibility-probe-v2/report.json`.
The primary client, all databases and all server processes were untouched.
This prototype still contains a fixed laboratory restriction set, not the future server-driven
policy. The owner confirmed grey, unchecked rows for the three probe races in game and supplied
screenshots. Selected-race validation, realm policy
reconciliation, source update handling, server enforcement and new-bot integration remain work.
-145
View File
@@ -1,145 +0,0 @@
# Per-race toggles: internal design and implementation status
This is an internal specification and work-in-progress record, not a released user guide.
Current verdict: **PARTIAL**. Client hiding and disabled rows were confirmed by the owner;
server policy, new-bot integration and Manager controls are now implemented in feature branches.
Native build qualification and server gameplay acceptance are still pending.
See [audit](../PER_RACE_TOGGLES_AUDIT.md) and [verification record](PER_RACE_TOGGLES_TESTS.md).
## Verified data and outstanding client decision
The local manifest identifies CoA Custom 1.9.2. The candidate source archive is `patch-ZZZF.MPQ`.
Its ChrRaces has WDBC layout 95/69/276/2428 (records/fields/record bytes/string bytes).
Its DBC SHA-256 is `b78635b08bf0bd63d2898fce97c1fb162c8a9c41632703172eefa88bae79061f`.
Observed IDs include Sethrak 82, Gnoll 83 and Saberon 97, all initially Flags 12.
The experiment sets `originalFlags | 0x01` only for selected IDs. Empty selection preserves
every original byte. Each run reads the explicitly selected source MPQ anew; it never consumes
the previous generated DBC. Re-enabling must restore the original record, including an original
NOT_PLAYABLE bit if present; it must not make an originally nonplayable race playable.
These observations do not qualify a client version. Actual archive precedence, menu behavior,
other-race creation and existing-character login are untested. No managed overlay filename has
been chosen. The tool does not infer precedence from filename sorting.
## Intended integration
```mermaid
flowchart TD
P[Existing realm configuration snapshot] --> S[Server creation policy]
P --> G[Availability generation, after client qualification]
O[Original effective client DBC] --> G
G --> V[Validate bytes and MPQ roundtrip]
V --> T[Existing client lock and transaction journal]
T --> M[One managed overlay]
S --> H[Normal account creation hook]
S --> C[Companions new-character creation]
S --> Q[SQUID new-character creation]
```
The new server key is `CoACustomRaces.DisabledRaceIds` in the existing module config.
It requires a newly built server; no installed server binary has been replaced. Empty or missing
key retains the previous master-switch behavior.
Validate the entire set before applying it; reject malformed, unknown and stock IDs without a
partial policy. Validate identity against effective server/client data, not numeric ranges alone.
Creation policy is independent of login and import. It must not modify existing characters,
appearance, items, spells, progress or Portable Characters identity. Bot creation additionally
obeys master switches, module switches, user exclusions and crashing-race restrictions. Existing
bot admission must not inherit a new-character restriction accidentally.
Use current module configuration, additive `.dist` merge and `Settings/realm-profiles/` snapshots.
Do not introduce another authoritative policy store. The future client record is provenance and
ownership metadata, not a replacement for the realm configuration.
Local PLAY must reconcile the selected profile before launch while the client is closed, using
the same `.coa-races.lock` as package operations. Shared clients have one currently installed
overlay; remote policies cannot be guessed. Unknown formats or conflicting ownership must fail
with a truthful status. Client and server application status must be separate in the UI.
Client repair/update must invalidate the previous overlay when the original effective DBC
changes and regenerate from the new original only after compatibility checks. Empty restrictions
must remove only the verified CSM-owned overlay. Actual install/recovery/update behavior is
not implemented by the offline tool.
## Offline tool
`tools/race_availability_poc.py` extracts with an explicitly supplied, existing Unicode StormLib
DLL. That DLL is a laboratory dependency only; no Manager/user dependency has been selected.
The tool writes `original.dbc`, `generated.dbc`, `experiment.MPQ` and `report.json` to a new output
directory after successful verification. It never installs an overlay, edits an input MPQ or
launches a process. The archive contains one game payload plus StormLib's internal listfile.
The fingerprint includes original DBC hash, sorted unique disabled IDs, algorithm version and
recorded client profile. It supports reproducibility checks; runtime caching is not implemented.
An empty selection still produces an offline test artifact so byte equality can be checked;
production empty-set removal is a separate, unimplemented requirement.
No game files or DLLs are checked into Git. Tests generate synthetic DBC/MPQ fixtures locally.
No export/distribution feature, release-channel change or publication is included.
## Remaining acceptance gate
The owner subsequently confirmed the Lua visibility and disabled-row probes through screenshots.
The selected client approach reuses the existing GlueXML filter rather than changing DBC flags.
This does not establish whether the earlier DBC-bit hypothesis works.
The owner deferred database/server testing while another server runs bot tests.
Do not launch the game, servers or MySQL or capture/control the screen without renewed authorization.
Use the owner-confirmed GlueXML approach for the next client integration stage. It preserves
the original DBC. The DBC-bit approach has not been declared incompatible; it was not live-tested.
## Server controls implemented in the feature branches
### Maintenance when new races are added
Whenever upstream adds races, include every new playable custom RaceID in the availability
list and verify its name and Horde/Alliance grouping. The Manager reads this list from the
installed server catalog automatically; update the server catalog rather than maintaining a
second hardcoded UI list. Review and explicitly save existing restrictions after the catalog
changes, preserving the owner's choices for unchanged IDs.
Also update and verify the client Lua RaceID mapping and filtering for the new races. A race
appearing in the Manager does not by itself establish client support. Check creation restrictions
and new-bot generation in both CoA Companions and SQUID, retaining user and crashing-race exclusions.
### Current implementation
Manager exposes a versioned catalog read from the server's `DataDir/dbc_races/ChrRaces.dbc`, with
strict WDBC layout/ID/name validation and stock/nonplayable rows excluded. The UI supports search,
counts, per-race allow checkboxes, Allow all, explicit Save/Discard and navigation guards. New
strings exist in all six Manager languages.
Saving requires a stopped server, no unfinished update, the existing control lock, an unchanged
catalog SHA-256 and the same selected realm as the loaded draft.
It uses the normal module backup/config writer. Servers whose distributed configuration does
not declare the new key cannot be configured through this control. The executable is also checked
for the key, following existing realm capability detection. The UI reports saved settings
and restart requirements, not a verified running-server Applied status. Template detection does
not independently attest the identity of a manually modified server executable.
Saved restrictions include the source catalog SHA-256. A changed catalog or orphaned IDs requires
explicit review and save; simply opening the panel does not migrate settings. Core and the offline
bot factory reject a mismatched bound catalog before creating characters. Empty hashes remain
supported for manually authored legacy configurations.
The core module stages a whole policy, validates configured IDs against loaded server race data,
and applies it atomically on startup/reload. Invalid input retains the previous policy; on an
initial invalid configuration, new custom creation remains disabled. Stock creation remains
available. The normal account hook remains in place and import/login paths are unchanged.
CoA Companions' common clone entry calls the account creation hook before inserting a new bot;
its selection also preserves explicit crashing exclusions. SQUID's random factory calls the
same hook while constructing candidate races, without adding owner restrictions to existing-bot
admission lists. The offline Companions factory reads configuration and filters prohibited
templates before creating accounts or generating insert SQL. No SQL was executed for verification.
The old Manager synchronization now preserves explicit user race exclusions. It only replaces
lists carrying its old ownership comment with an exact known generated value. Crashing-race
settings are never rewritten. BotsEnable is read directly from the Custom Races configuration
when available rather than inferred from unrelated exclusion choices.
Automatic production client synchronization and client update invalidation remain unimplemented.
Server-side catalog binding is implemented. The fixed three-race test overlay is not automatically changed
by these new server controls. This limitation is explicitly visible in the Manager UI.
-92
View File
@@ -1,92 +0,0 @@
# Per-race toggles: internal verification record
Date: 2026-10-27. Verdict: **PARTIAL**. Scope: source implementation, native builds and offline verification; live acceptance remains pending.
Latest source implementation checks additionally include:
- Manager catalog/configuration tests: 10 passed, including catalog binding, unknown-ID review, stale/invalid input rejection,
Allow all, preserving unknown configuration keys and leaving bot exclusions unchanged.
- Focused Manager race regression selection: 34 passed, 3 ignored because they require release
archives or another writable volume. The three ignored tests are not counted as passes.
- Frontend TypeScript/Vite build: passed after correcting the new component's error rendering.
- Existing i18n and module-settings checks: passed; new keys exist in all six languages.
- Core production-module harness: passed with synthetic Config/DBC stubs through verify_all.
- Companions production selector harness and five offline-factory policy tests: passed without
running a MySQL client or server.
- Complete native core build with staged Companions and SQUID: passed in the dedicated
`build-utf8` directory. Final source/build/harness verification passed in
`C:/games/source/per-race-core/.cache/verify-all/20261027-112640/report.json`.
Unit and gameplay stages were skipped. No installed binaries or services were changed.
- Rust Clippy with warnings denied: passed for coa-core.
- Final Tauri debug application build: passed after the catalog-review changes. Artifact:
`C:/games/source/per-race-manager/target/debug/coa-server-manager.exe`.
Frontend bundle-size and localized linker-output warnings were emitted; neither failed the build.
The first native configure lacked an OpenSSL root. A subsequent build was deliberately stopped
when its MSVC dependency prefix was found misencoded. The replacement uses the existing dynamic
OpenSSL/MySQL development libraries and a fresh UTF-8 environment. These earlier verify_all runs
ended FAILED and are not successful build evidence.
## Executed automated checks
Run from the Manager feature checkout:
```powershell
$env:COA_TEST_STORMLIB = '<absolute path to an existing Unicode StormLib DLL>'
python -B -m unittest discover -s tools -p 'test_race_availability_*.py' -v
```
The recorded run used the bundled repack Python at
`C:/games/CoA Server 2/Runtime/python/python.exe` and the existing DLL at
`C:/Users/Dion/AppData/Local/Programs/Python/Python311/Lib/site-packages/pympq/StormLib.dll`.
No database or game process is used. Without the explicit DLL environment variable, MPQ tests
are skipped; that is not equivalent to the recorded full pass.
| Group | Result | Actual scope |
| --- | --- | --- |
| DBC and fingerprint | PASS, 17 tests | Exact changed bytes; 1/5/50 IDs; other bits; original restoration; duplicate normalization; stock/unknown IDs; duplicate/invalid table IDs; corrupt/truncated/unknown layouts; localized name bounds and UTF-8; source/profile/set fingerprint inputs |
| Synthetic MPQ | PASS, 8 tests | 1/50 IDs produce one archive; one game payload; extraction equality; identical regenerated DBC/fingerprint; source unchanged; existing output preserved; packaging/readback/read/input errors publish no result; empty set preserves bytes |
| Total | PASS, 25 tests, zero skipped | Offline files only |
| Real three-race DBC/MPQ | PASS | Sethrak 82, Gnoll 83, Saberon 97; only Flags 12 → 13; one MPQ; re-extracted DBC equals expected; original MPQ hash unchanged |
| Existing filter behavior | CONFIRMED, 9 offline assertions | Original extracted Lua functions under Lua 5.1 with UI/CVar mocks; see existing-filter research |
| English name/ID map vs original DBC | PASS, 73 rows with NOT_PLAYABLE clear | Every inspected ID appears in the final literal Lua name map; runtime button identity remains unverified |
| Managed disabled-row Lua probe | PASS, 11 tests | Lua 5.1 syntax; grey/unchecked/disabled rows; personal choices; scroll reuse; unknown identity; Check All; click guard; six languages; input rejection; layout fallback; lifting restrictions |
| First Lua visibility probe | USER-OBSERVED | Owner reported Sethrak/Gnoll/Saberon absent and supplied screenshots; creation, login and grey rows not tested |
An initial new MPQ assertion expected one block-table entry and failed for both cardinalities.
Inspection showed StormLib also writes `(listfile)`. The corrected check requires two entries
and verifies the listfile names exactly one game file. All 25 tests then passed. This was a test
assumption correction, not a change to the functional requirement of one overlay.
Local evidence for real game files stays outside Git:
`C:/games/source/per-race-evidence/multiple-races-offline/report.json`.
Original DBC hash: `b78635b08bf0bd63d2898fce97c1fb162c8a9c41632703172eefa88bae79061f`.
Generated three-race DBC hash: `243fb36837b76ebd6943da574cc095be548b4530be7f06487debea6703db10d3`.
## Unexecuted checks
| Scope | Status | Reason |
| --- | --- | --- |
| Effective running-client DBC and general MPQ load order | NOT RUN | First Lua probe visibly affected this one installation, but effective DBC/general precedence remain unverified |
| LIVE-01 one disabled race | NOT RUN | Requires client and isolated server |
| LIVE-02 multiple disabled races and re-enable | NOT RUN | Requires client and isolated server |
| LIVE-03 existing character data/login | NOT RUN | No database/login testing performed |
| LIVE-04 bot generation, both systems separately | NOT RUN | Other bot tests are in progress; MySQL must remain untouched |
| LIVE-05 Portable Characters | NOT RUN | Requires disposable realm/database setup |
| LIVE-06 client repair/update | NOT RUN | Runtime overlay integration not implemented |
| LIVE-07 shared client | NOT RUN | Runtime profile reconciliation not implemented |
| Server config/parser/hook tests | PASS, offline | Actual module compiled with Config/DBC/crypto stubs; native build also passed |
| Client transaction crash/recovery matrix | NOT RUN | Offline result staging is not client install/recovery |
| Manager visual interaction | NOT RUN | Owner requested no screen capture/control; translation checks and frontend build passed |
| Full Rust workspace tests | NOT RUN | Focused race tests and native Manager build used instead |
| C++ build and verify_all | PASS, source/build/harness | No server/database process started; gameplay excluded |
| Release packaging and upgrades | NOT RUN | No release or runtime implementation prepared |
The copied client initially displayed a missing-critical-files message and crashed on exit.
The fault address maps to AMD's AMDXN32.DLL; root cause is unresolved. No experimental overlay
was installed at the time of that crash. Later Lua probes were installed only in the isolated copy,
and the owner confirmed hidden races and disabled grey rows. Creation could not be checked.
Neither observation is an availability live-test pass.
Existing character data and original game archives were not changed. No SQL was executed.
The feature must not be declared READY on these results.
-12
View File
@@ -1,7 +1,5 @@
# Take your character with you
**English** · [Русский](ru/PORTABLE-CHARACTERS.md) · [Deutsch](de/PORTABLE-CHARACTERS.md) · [Français](fr/PORTABLE-CHARACTERS.md) · [Español](es/PORTABLE-CHARACTERS.md) · [简体中文](zh-CN/PORTABLE-CHARACTERS.md)
**Portable characters are experimental.** The feature is in active development and may contain bugs.
Portable characters let you keep a saved character in the Manager and play it on compatible realms (Conquest of Azeroth and Wildcard).
@@ -52,13 +50,3 @@ A realm with a lower level cap may play your character at a lower level. Check t
## Saved versions and conflicts
Use **Saved versions** to see when progress was saved. If the Manager reports a conflict, follow its explanation before continuing. Avoid playing two copies at once, and keep normal server backups as well.
[All guides](README.md)
## Portable access and relay
In the realm's Public list card, enable “Allow portable characters on this realm” and save. It is off until the owner opts in. Turning it off blocks new exports and imports; it does not delete saved characters. Keep the host Manager running. The control connection and game relay have separate status indicators: a connected control channel does not establish a game tunnel. Characters stay within their original ruleset (CoA, Wildcard or Warcraft Reborn); changing servers does not convert their ruleset.
Keep both Managers running. Saving resumes after reconnecting or restarting, and later logins stay monitored. Wait for saving before switching realms. Your installed servers use local preparation and recovery. Experimental limitation: an older existing copy on another host cannot yet be refreshed automatically while its worldserver runs. Returning may require host maintenance. The stale copy is blocked and your canonical character stays saved. Do not delete the character or reinstall the server to bypass this message.
Stop the server before enabling this for the first time. Saving prepares portable sessions for its next start; disabling access leaves ongoing sessions intact.
-2
View File
@@ -1,7 +1,5 @@
# Guides and screenshots
**English** · [Русский](ru/README.md) · [Deutsch](de/README.md) · [Français](fr/README.md) · [Español](es/README.md) · [简体中文](zh-CN/README.md)
- [Screenshot gallery](SCREENSHOTS.md) — explore the interface and its main features.
- [Host your own server](HOST-A-SERVER.md) — install a server, invite friends and publish a realm listing.
- [Portable characters · Experimental](PORTABLE-CHARACTERS.md) — save an existing character and use compatible realms.
-2
View File
@@ -1,7 +1,5 @@
# Updates, backups and repair
**English** · [Русский](ru/REPAIR_AND_REALMS.md) · [Deutsch](de/REPAIR_AND_REALMS.md) · [Français](fr/REPAIR_AND_REALMS.md) · [Español](es/REPAIR_AND_REALMS.md) · [简体中文](zh-CN/REPAIR_AND_REALMS.md)
## Update your server
Select your server in the Manager. When an update is available, choose **UPDATE** and follow the prompts. Keep the Manager open until it finishes: it stops the server, creates a recovery point and checks the updated server.
+19 -3
View File
@@ -1,25 +1,41 @@
# CoA Server Manager 0.7.0
**English** · [Русский](ru/SCREENSHOTS.md) · [Deutsch](de/SCREENSHOTS.md) · [Français](fr/SCREENSHOTS.md) · [Español](es/SCREENSHOTS.md) · [简体中文](zh-CN/SCREENSHOTS.md)
### Your server, a few clicks away
![Your server, a few clicks away](screenshots/setup.png)
### Your server at a glance
![Your server at a glance](screenshots/overview.png)
### Build your own adventuring company
![Build your own adventuring company](screenshots/bots.png)
### Manage your server modules
![Manage your server modules](screenshots/modules.png)
### Your client, ready to play
![Your client, ready to play](screenshots/client.png)
### Keep your progress safe
![Keep your progress safe](screenshots/backups.png)
### Bring your friends along
![Bring your friends along](screenshots/friends.png)
### Find your next realm
![Find your next realm](screenshots/realms.png)
### Portable characters · Experimental
![Portable characters · Experimental](screenshots/portable.png)
![Make a character portable · Experimental](screenshots/remote-character.png)
### Make a character portable · Experimental
[All guides](README.md)
![Make a character portable · Experimental](screenshots/remote-character.png)
-2
View File
@@ -1,7 +1,5 @@
# Warcraft Reborn
**English** · [Русский](ru/WARCRAFT-REBORN.md) · [Deutsch](de/WARCRAFT-REBORN.md) · [Français](fr/WARCRAFT-REBORN.md) · [Español](es/WARCRAFT-REBORN.md) · [简体中文](zh-CN/WARCRAFT-REBORN.md)
Choose **Warcraft Reborn** on Overview to create or switch to this realm. The
installed worldserver must contain Warcraft Reborn support; an old build is
refused before any databases are created. Stop the client before switching to
Loaded 100 of 269 files, more files were not shown because too many files have changed in this diff. Show more