mirror of
https://github.com/Corfirean/coa-server-manager.git
synced 2026-11-19 03:25:56 +00:00
Compare commits
61
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8e1eb825df | ||
|
|
4fcf0dde3f | ||
|
|
e4791fc45c | ||
|
|
af82963f35 | ||
|
|
321ac597ce | ||
|
|
925a81f4f2 | ||
|
|
df1901ea90 | ||
|
|
569d5fffc4 | ||
|
|
7888dbc763 | ||
|
|
f0e8a8c12f | ||
|
|
af5a9717d4 | ||
|
|
bf2fffcffa | ||
|
|
4a99dd3a6a | ||
|
|
306003b698 | ||
|
|
d9be2b9d82 | ||
|
|
81b040ef02 | ||
|
|
5fdee1d658 | ||
|
|
4e1f548012 | ||
|
|
b3ee94071d | ||
|
|
76dc7452de | ||
|
|
02e3a9e4e6 | ||
|
|
8addc97bc5 | ||
|
|
57807b9769 | ||
|
|
7e29a9f2ec | ||
|
|
af9f148889 | ||
|
|
92385cf569 | ||
|
|
b00e732c7f | ||
|
|
594bdee594 | ||
|
|
d4408a0e92 | ||
|
|
b61a186470 | ||
|
|
9e9778af74 | ||
|
|
d5f1e9cc83 | ||
|
|
aa25e9c721 | ||
|
|
1fd3a5482e | ||
|
|
2715170622 | ||
|
|
8801c6f308 | ||
|
|
341f2f0230 | ||
|
|
4d59ce8cb1 | ||
|
|
de90418e84 | ||
|
|
3b75d37ce4 | ||
|
|
1bc4060121 | ||
|
|
6038eacea5 | ||
|
|
83e87d49fc | ||
|
|
0189e3eebf | ||
|
|
5544d62c23 | ||
|
|
93784af0d9 | ||
|
|
ff09d3d056 | ||
|
|
ed2b1291cb | ||
|
|
e033cfbc92 | ||
|
|
154fdfb0e9 | ||
|
|
79e9e85fac | ||
|
|
a48717340b | ||
|
|
351ace1c56 | ||
|
|
ba143e1ccd | ||
|
|
5343020bed | ||
|
|
9d135765cd | ||
|
|
58a99f0a6d | ||
|
|
d9c10c4564 | ||
|
|
dc05b2cd3c | ||
|
|
df102f16fa | ||
|
|
5963e97c59 |
No files matched your search
@@ -51,3 +51,16 @@ 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.
|
||||
@@ -8,6 +8,70 @@ 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.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.
|
||||
|
||||
**Portable Characters are experimental and may contain bugs.**
|
||||
|
||||
- Updated Custom Races client patches to the complete 1.8.3 package.
|
||||
- Race patch installation now includes the hide-armor and talent-reset addons.
|
||||
|
||||
[Release](https://github.com/Corfirean/coa-server-manager/releases/tag/v0.7.1) · [Source changes](https://github.com/Corfirean/coa-server-manager/compare/v0.7.0...v0.7.1)
|
||||
|
||||
[Guides and screenshots](https://github.com/Corfirean/coa-server-manager/blob/master/docs/README.md)
|
||||
|
||||
## 0.7.0 — 2026-10-21
|
||||
|
||||
Portable transfers into Warcraft Reborn are not supported yet.
|
||||
|
||||
Generated
+3
-3
@@ -586,7 +586,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "coa-core"
|
||||
version = "0.7.1"
|
||||
version = "0.8.2"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"chrono",
|
||||
@@ -634,7 +634,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "coa-release"
|
||||
version = "0.7.1"
|
||||
version = "0.8.2"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"coa-core",
|
||||
@@ -643,7 +643,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "coa-server-manager"
|
||||
version = "0.7.1"
|
||||
version = "0.8.2"
|
||||
dependencies = [
|
||||
"coa-control-proto",
|
||||
"coa-core",
|
||||
|
||||
+1
-1
@@ -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.7.1"
|
||||
version = "0.8.2"
|
||||
edition = "2021"
|
||||
license = "AGPL-3.0-only"
|
||||
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
# 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.
|
||||
|
||||

|
||||
|
||||
## 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 |
|
||||
|---|---|
|
||||
|  |  |
|
||||
|
||||
| Begleiter | Sicherungen |
|
||||
|---|---|
|
||||
|  |  |
|
||||
|
||||
[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.
|
||||
@@ -0,0 +1,84 @@
|
||||
# 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.
|
||||
|
||||

|
||||
|
||||
## 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 |
|
||||
|---|---|
|
||||
|  |  |
|
||||
|
||||
| Compañeros | Copias de seguridad |
|
||||
|---|---|
|
||||
|  |  |
|
||||
|
||||
[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.
|
||||
@@ -0,0 +1,84 @@
|
||||
# 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.
|
||||
|
||||

|
||||
|
||||
## 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 |
|
||||
|---|---|
|
||||
|  |  |
|
||||
|
||||
| Compagnons | Sauvegardes |
|
||||
|---|---|
|
||||
|  |  |
|
||||
|
||||
[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.
|
||||
@@ -1,5 +1,7 @@
|
||||
# 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:
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
# 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/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/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. Лицензия менеджера на них **не распространяется**.
|
||||
@@ -0,0 +1,84 @@
|
||||
# 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/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/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 服务器客户端,**不属于**管理器许可的授权范围。
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
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.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
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.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
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.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
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.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
area: manager
|
||||
type: fixed
|
||||
audience: admins
|
||||
title: Online player counts correctly separate random bots from players
|
||||
---
|
||||
The server browser and overview now count SQUID random bots as bots, using the server's configured bot account prefix.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
area: manager
|
||||
type: fixed
|
||||
audience: admins
|
||||
title: Custom races work with shared addon folders on another drive
|
||||
---
|
||||
Installing, switching and removing custom races now supports linked addon folders on another drive, including recovery after an interrupted operation.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
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.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
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.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
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.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
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.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
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.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
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.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
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.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
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.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
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.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
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.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
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.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
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.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
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.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
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.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
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.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
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.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
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.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
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.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
area: manager
|
||||
type: fixed
|
||||
audience: admins
|
||||
title: Starting a server sets the character classes of the realm chosen on Overview
|
||||
---
|
||||
A new Conquest of Azeroth server could show two class models, or none, on the character creation screen. The Manager now sets the model of the chosen realm before every start.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
area: manager
|
||||
type: added
|
||||
audience: admins
|
||||
title: Start Wildcard and Warcraft Reborn together with Conquest of Azeroth
|
||||
---
|
||||
Settings now has two options, one for Wildcard and one for Warcraft Reborn. Turn on either one, or both to run all three realms at once, each with its own characters and port.
|
||||
+119
-1
@@ -112,6 +112,8 @@
|
||||
"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",
|
||||
@@ -119,7 +121,24 @@
|
||||
"Corfirean/coa-server-manager:20261021-custom-races-switching.md",
|
||||
"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:20261021-warcraft-reborn-realm.md",
|
||||
"Corfirean/coa-server-manager:20261022-custom-races-client.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-merged-database-migration-order.md"
|
||||
],
|
||||
"releases": [
|
||||
{
|
||||
@@ -603,6 +622,105 @@
|
||||
"links": [
|
||||
"[Player guides and screenshots](https://github.com/Corfirean/coa-server-manager/tree/d22ff09ac6fd7628aac14d90ec23f547cd9b4bf1/docs)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"tag": "v0.7.1",
|
||||
"version": "0.7.1",
|
||||
"date": "2026-10-22",
|
||||
"url": "https://github.com/Corfirean/coa-server-manager/releases/tag/v0.7.1",
|
||||
"notes": [
|
||||
"Updated Custom Races client patches to the complete 1.8.3 package",
|
||||
"Race patch installation now includes the hide-armor and talent-reset addons"
|
||||
],
|
||||
"commit": "8d2befd7f08532b2cb9e0bf2f973bb631f3890e5",
|
||||
"experimentalFeatures": [
|
||||
"portable-characters"
|
||||
],
|
||||
"compare": "https://github.com/Corfirean/coa-server-manager/compare/v0.7.0...v0.7.1",
|
||||
"notice": "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.",
|
||||
"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"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -15,6 +15,15 @@ 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 {
|
||||
@@ -103,6 +112,16 @@ pub enum Request {
|
||||
TransferOffer {
|
||||
transfer_id: Uuid,
|
||||
character_id: Uuid,
|
||||
ruleset: String,
|
||||
canonical_revision: u64,
|
||||
content_hash: String,
|
||||
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,
|
||||
@@ -127,6 +146,24 @@ 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,
|
||||
@@ -171,6 +208,22 @@ 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,
|
||||
@@ -189,6 +242,7 @@ pub enum Response {
|
||||
/// appearance and vanity ids the Host holds for the account (kind -> ids).
|
||||
Claimed {
|
||||
character_id: Uuid,
|
||||
ruleset: String,
|
||||
sha256: String,
|
||||
payload: String,
|
||||
collections: BTreeMap<String, Vec<u32>>,
|
||||
@@ -245,7 +299,10 @@ pub fn decode_request(bytes: &[u8]) -> Result<Request> {
|
||||
.map_err(|_| ControlError::Invalid("a request is not valid".into()))?;
|
||||
if !matches!(
|
||||
&r,
|
||||
Request::TransferOffer { .. } | Request::TransferChunk { .. }
|
||||
Request::TransferOffer { .. }
|
||||
| Request::OwnedTransferOffer { .. }
|
||||
| Request::TransferChunk { .. }
|
||||
| Request::SessionAck { .. }
|
||||
) && bytes.len() > MAX_CONTROL_REQUEST_BYTES
|
||||
{
|
||||
return Err(ControlError::Limit(
|
||||
@@ -253,6 +310,34 @@ 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, ..
|
||||
} => {
|
||||
@@ -273,11 +358,22 @@ pub fn decode_request(bytes: &[u8]) -> Result<Request> {
|
||||
return invalid("the client name is too long")
|
||||
}
|
||||
Request::TransferOffer {
|
||||
ruleset,
|
||||
content_hash,
|
||||
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");
|
||||
}
|
||||
if content_hash.len() != 64 || !content_hash.chars().all(|c| c.is_ascii_hexdigit()) {
|
||||
return invalid("transfer content hash must be 64 hex characters");
|
||||
}
|
||||
@@ -430,6 +526,7 @@ mod tests {
|
||||
let offer = Request::TransferOffer {
|
||||
transfer_id: tid,
|
||||
character_id: cid,
|
||||
ruleset: "coa".into(),
|
||||
canonical_revision: 5,
|
||||
content_hash: hash.clone(),
|
||||
total_size: 1024,
|
||||
@@ -442,6 +539,7 @@ mod tests {
|
||||
let bad_hash = Request::TransferOffer {
|
||||
transfer_id: tid,
|
||||
character_id: cid,
|
||||
ruleset: "coa".into(),
|
||||
canonical_revision: 5,
|
||||
content_hash: "too_short".into(),
|
||||
total_size: 1024,
|
||||
@@ -466,5 +564,21 @@ mod tests {
|
||||
};
|
||||
let resp_dec = decode_response(&encode_response(&resp)).unwrap();
|
||||
assert_eq!(resp, resp_dec);
|
||||
|
||||
// Control protocol v2 requires ruleset in TransferOffer; missing is rejected
|
||||
let missing_ruleset_json = serde_json::json!({
|
||||
"op": "transfer_offer",
|
||||
"transfer_id": tid,
|
||||
"character_id": cid,
|
||||
"canonical_revision": 5,
|
||||
"content_hash": hash,
|
||||
"total_size": 1024,
|
||||
"collections": {}
|
||||
});
|
||||
let encoded_missing = serde_json::to_vec(&missing_ruleset_json).unwrap();
|
||||
assert!(
|
||||
decode_request(&encoded_missing).is_err(),
|
||||
"missing ruleset in v2 must be rejected"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -112,6 +112,10 @@ 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());
|
||||
@@ -122,7 +126,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}",
|
||||
crate::CONTROL_PROTOCOL_VERSION
|
||||
COORDINATOR_PROTOCOL_VERSION
|
||||
)
|
||||
.into_bytes()
|
||||
}
|
||||
@@ -130,7 +134,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}",
|
||||
crate::CONTROL_PROTOCOL_VERSION,
|
||||
COORDINATOR_PROTOCOL_VERSION,
|
||||
player.hyphenated()
|
||||
)
|
||||
.into_bytes()
|
||||
@@ -277,6 +281,14 @@ 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])
|
||||
}
|
||||
|
||||
@@ -16,7 +16,7 @@ pub mod coord;
|
||||
pub mod noise;
|
||||
pub mod relay;
|
||||
|
||||
pub const CONTROL_PROTOCOL_VERSION: u32 = 1;
|
||||
pub const CONTROL_PROTOCOL_VERSION: u32 = 2;
|
||||
|
||||
#[derive(Debug, thiserror::Error, PartialEq, Eq)]
|
||||
pub enum ControlError {
|
||||
|
||||
@@ -90,6 +90,7 @@ fn test_app_request_hostile_limits_and_validation() {
|
||||
let offer = Request::TransferOffer {
|
||||
transfer_id: Uuid::now_v7(),
|
||||
character_id: Uuid::now_v7(),
|
||||
ruleset: "coa".into(),
|
||||
canonical_revision: 1,
|
||||
content_hash: "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef".into(),
|
||||
total_size: 1024,
|
||||
@@ -105,6 +106,7 @@ fn test_app_request_hostile_limits_and_validation() {
|
||||
let bad_hash_offer = Request::TransferOffer {
|
||||
transfer_id: Uuid::now_v7(),
|
||||
character_id: Uuid::now_v7(),
|
||||
ruleset: "coa".into(),
|
||||
canonical_revision: 1,
|
||||
content_hash: "not_a_valid_hex_hash".into(),
|
||||
total_size: 1024,
|
||||
@@ -112,6 +114,18 @@ fn test_app_request_hostile_limits_and_validation() {
|
||||
};
|
||||
assert!(decode_request(&encode_request(&bad_hash_offer)).is_err());
|
||||
|
||||
// 4b. Invalid ruleset rejected
|
||||
let bad_ruleset_offer = Request::TransferOffer {
|
||||
transfer_id: Uuid::now_v7(),
|
||||
character_id: Uuid::now_v7(),
|
||||
ruleset: "invalid_ruleset".into(),
|
||||
canonical_revision: 1,
|
||||
content_hash: "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef".into(),
|
||||
total_size: 1024,
|
||||
collections: BTreeMap::new(),
|
||||
};
|
||||
assert!(decode_request(&encode_request(&bad_ruleset_offer)).is_err());
|
||||
|
||||
// 5. TransferChunk offset out of bounds
|
||||
let bad_offset_chunk = Request::TransferChunk {
|
||||
transfer_id: Uuid::now_v7(),
|
||||
|
||||
@@ -1,57 +1,124 @@
|
||||
//! Read-only audit, or explicit SQL checks on a disposable database fixture.
|
||||
use coa_core::{db::{Account, Db}, migrations::{self, Store}, manifest::Manifest, realms::Mode};
|
||||
use coa_core::{
|
||||
db::{Account, Db},
|
||||
manifest::Manifest,
|
||||
migrations::{self, Store},
|
||||
realms::Mode,
|
||||
};
|
||||
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let args: Vec<_> = std::env::args().collect();
|
||||
if args.len() < 3 { return Err("usage: migration_plan <root> <signed-manifest> [--apply|--sql-only <migration-directory>]".into()); }
|
||||
let root = std::path::Path::new(&args[1]);
|
||||
let bytes = std::fs::read(&args[2])?;
|
||||
let signature = std::fs::read_to_string(format!("{}.sig",args[2]))?;
|
||||
coa_core::signing::verify(&bytes, &signature, coa_core::signing::EMBEDDED_PUBLIC_KEY)?;
|
||||
let manifest = Manifest::parse(&bytes)?;
|
||||
for (index,mode) in [Mode::Coa, Mode::Wildcard].into_iter().enumerate() {
|
||||
let db = Db::from_repack(root, Account::Admin)?.for_realm(mode);
|
||||
let rows = db.load_readonly()?;
|
||||
let relevant: Vec<_> = rows.iter().filter(|r| r.id == "rev_20260903_01_live_class_baseline").map(|r| format!("{} {:?} {}",r.db,r.status,r.baseline)).collect();
|
||||
println!("{} baseline history: {:?}",mode.name(),relevant);
|
||||
let list: Vec<_> = manifest.migrations.iter().filter(|m|index==0 || m.db!="auth").cloned().collect();
|
||||
let plan = migrations::status(&db,&list)?;
|
||||
println!("{} pending: {:?}",mode.name(),plan.iter().filter(|m|m.status!=migrations::Status::Applied).map(|m|(&m.db,&m.id,m.status)).collect::<Vec<_>>());
|
||||
}
|
||||
if args.get(3).is_some_and(|s| s == "--apply" || s == "--sql-only") {
|
||||
assert!(root.file_name().unwrap().to_string_lossy().starts_with("update-database-diagnosis-") && root.join(".coa-update-fixture").is_file(), "Only disposable fixture roots may be changed");
|
||||
if args[3] == "--sql-only" {
|
||||
let db = Db::from_repack(root, Account::Admin)?.for_realm(Mode::Coa);
|
||||
let identity = || -> coa_core::Result<String> {
|
||||
let mut rows = String::new();
|
||||
for (schema,table,columns) in [("acore_auth","account","id,HEX(username)"),("acore_characters","characters","guid,account,HEX(name)"),("acore_characters_wildcard","characters","guid,account,HEX(name)")] {
|
||||
rows.push_str(schema);
|
||||
rows.push_str(&db.query(&format!("SELECT {columns} FROM {schema}.{table} ORDER BY 1;"))?);
|
||||
let args: Vec<_> = std::env::args().collect();
|
||||
if args.len() < 3 {
|
||||
return Err("usage: migration_plan <root> <signed-manifest> [--apply|--sql-only <migration-directory>]".into());
|
||||
}
|
||||
Ok(coa_core::fsx::sha256_bytes(rows.as_bytes()))
|
||||
};
|
||||
let before = identity()?;
|
||||
migrations::verify_files(&manifest.migrations,std::path::Path::new(&args[4]))?;
|
||||
for (index,mode) in [Mode::Coa,Mode::Wildcard].into_iter().enumerate() {
|
||||
let realm_db = db.clone().for_realm(mode);
|
||||
let list: Vec<_> = manifest.migrations.iter().filter(|m|index==0 || m.db!="auth").cloned().collect();
|
||||
let result = migrations::apply_pending(&realm_db,&list,std::path::Path::new(&args[4]),&||Ok("disposable fixture".into()))?;
|
||||
println!("{} SQL result: {}",mode.name(),serde_json::to_string(&result)?);
|
||||
if result.failed.is_some() {return Err("SQL failed; fixture preserved".into());}
|
||||
}
|
||||
assert_eq!(before,identity()?,"Account or character identity changed");
|
||||
println!("Account and character identities preserved: {}",before);
|
||||
let capture = root.join("captured-schema");
|
||||
coa_core::schema_check::capture(&db,&capture)?;
|
||||
println!("Captured schema SHA256: {}",coa_core::fsx::sha256_file(&capture.join(coa_core::schema_check::CONTRACT))?);
|
||||
return Ok(());
|
||||
}
|
||||
if args.len() != 5 { return Err("Migration directory required".into()); }
|
||||
use coa_core::update::{Env, RepackEnv};
|
||||
let meta = coa_core::registry::metadata_dir_for(root)?;
|
||||
let env = RepackEnv { root, meta_dir: &meta };
|
||||
let result = env.migrate(&manifest, std::path::Path::new(&args[4]));
|
||||
let _ = coa_core::driver::run(root, coa_core::driver::Verb::StopAll);
|
||||
println!("Application result: {}",serde_json::to_string(&result?)?);
|
||||
}
|
||||
Ok(())
|
||||
let root = std::path::Path::new(&args[1]);
|
||||
let bytes = std::fs::read(&args[2])?;
|
||||
let signature = std::fs::read_to_string(format!("{}.sig", args[2]))?;
|
||||
coa_core::signing::verify(&bytes, &signature, coa_core::signing::EMBEDDED_PUBLIC_KEY)?;
|
||||
let manifest = Manifest::parse(&bytes)?;
|
||||
for (index, mode) in [Mode::Coa, Mode::Wildcard].into_iter().enumerate() {
|
||||
let db = Db::from_repack(root, Account::Admin)?.for_realm(mode);
|
||||
let rows = db.load_readonly()?;
|
||||
let relevant: Vec<_> = rows
|
||||
.iter()
|
||||
.filter(|r| r.id == "rev_20260903_01_live_class_baseline")
|
||||
.map(|r| format!("{} {:?} {}", r.db, r.status, r.baseline))
|
||||
.collect();
|
||||
println!("{} baseline history: {:?}", mode.name(), relevant);
|
||||
let list: Vec<_> = manifest
|
||||
.migrations
|
||||
.iter()
|
||||
.filter(|m| index == 0 || m.db != "auth")
|
||||
.cloned()
|
||||
.collect();
|
||||
let plan = migrations::status(&db, &list)?;
|
||||
println!(
|
||||
"{} pending: {:?}",
|
||||
mode.name(),
|
||||
plan.iter()
|
||||
.filter(|m| m.status != migrations::Status::Applied)
|
||||
.map(|m| (&m.db, &m.id, m.status))
|
||||
.collect::<Vec<_>>()
|
||||
);
|
||||
}
|
||||
if args
|
||||
.get(3)
|
||||
.is_some_and(|s| s == "--apply" || s == "--sql-only")
|
||||
{
|
||||
assert!(
|
||||
root.file_name()
|
||||
.unwrap()
|
||||
.to_string_lossy()
|
||||
.starts_with("update-database-diagnosis-")
|
||||
&& root.join(".coa-update-fixture").is_file(),
|
||||
"Only disposable fixture roots may be changed"
|
||||
);
|
||||
if args[3] == "--sql-only" {
|
||||
let db = Db::from_repack(root, Account::Admin)?.for_realm(Mode::Coa);
|
||||
let identity = || -> coa_core::Result<String> {
|
||||
let mut rows = String::new();
|
||||
for (schema, table, columns) in [
|
||||
("acore_auth", "account", "id,HEX(username)"),
|
||||
("acore_characters", "characters", "guid,account,HEX(name)"),
|
||||
(
|
||||
"acore_characters_wildcard",
|
||||
"characters",
|
||||
"guid,account,HEX(name)",
|
||||
),
|
||||
] {
|
||||
rows.push_str(schema);
|
||||
rows.push_str(&db.query(&format!(
|
||||
"SELECT {columns} FROM {schema}.{table} ORDER BY 1;"
|
||||
))?);
|
||||
}
|
||||
Ok(coa_core::fsx::sha256_bytes(rows.as_bytes()))
|
||||
};
|
||||
let before = identity()?;
|
||||
migrations::verify_files(&manifest.migrations, std::path::Path::new(&args[4]))?;
|
||||
for (index, mode) in [Mode::Coa, Mode::Wildcard].into_iter().enumerate() {
|
||||
let realm_db = db.clone().for_realm(mode);
|
||||
let list: Vec<_> = manifest
|
||||
.migrations
|
||||
.iter()
|
||||
.filter(|m| index == 0 || m.db != "auth")
|
||||
.cloned()
|
||||
.collect();
|
||||
let result = migrations::apply_pending(
|
||||
&realm_db,
|
||||
&list,
|
||||
std::path::Path::new(&args[4]),
|
||||
&|| Ok("disposable fixture".into()),
|
||||
)?;
|
||||
println!(
|
||||
"{} SQL result: {}",
|
||||
mode.name(),
|
||||
serde_json::to_string(&result)?
|
||||
);
|
||||
if result.failed.is_some() {
|
||||
return Err("SQL failed; fixture preserved".into());
|
||||
}
|
||||
}
|
||||
assert_eq!(before, identity()?, "Account or character identity changed");
|
||||
println!("Account and character identities preserved: {}", before);
|
||||
let capture = root.join("captured-schema");
|
||||
coa_core::schema_check::capture(&db, &capture)?;
|
||||
println!(
|
||||
"Captured schema SHA256: {}",
|
||||
coa_core::fsx::sha256_file(&capture.join(coa_core::schema_check::CONTRACT))?
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
if args.len() != 5 {
|
||||
return Err("Migration directory required".into());
|
||||
}
|
||||
use coa_core::update::{Env, RepackEnv};
|
||||
let meta = coa_core::registry::metadata_dir_for(root)?;
|
||||
let env = RepackEnv {
|
||||
root,
|
||||
meta_dir: &meta,
|
||||
};
|
||||
let result = env.migrate(&manifest, std::path::Path::new(&args[4]));
|
||||
let _ = coa_core::driver::run(root, coa_core::driver::Verb::StopAll);
|
||||
println!("Application result: {}", serde_json::to_string(&result?)?);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -457,7 +457,7 @@ fn run() -> Result<(), String> {
|
||||
}
|
||||
("collection-states", [out]) => {
|
||||
let states = OwnerService::new(&mut store)
|
||||
.collection_states()
|
||||
.collection_states(coa_core::portable::Ruleset::Coa)
|
||||
.map_err(|e| e.to_string())?;
|
||||
for s in &states {
|
||||
println!(
|
||||
@@ -618,7 +618,7 @@ fn run() -> Result<(), String> {
|
||||
let set =
|
||||
coa_core::portable::collection::IdSet::from_ids(ids).map_err(|e| e.to_string())?;
|
||||
let merge = store
|
||||
.merge_collection(profile, kind, &set)
|
||||
.merge_collection(profile, coa_core::portable::Ruleset::Coa, kind, &set)
|
||||
.map_err(|e| e.to_string())?;
|
||||
println!(
|
||||
"{kind}: {} id(s) added{}",
|
||||
@@ -633,7 +633,7 @@ fn run() -> Result<(), String> {
|
||||
let profile = store.default_profile().map_err(|e| e.to_string())?;
|
||||
for kind in coa_core::portable::session::protocol::COLLECTION_KINDS {
|
||||
match store
|
||||
.collection_info(profile, kind)
|
||||
.collection_info(profile, coa_core::portable::Ruleset::Coa, kind)
|
||||
.map_err(|e| e.to_string())?
|
||||
{
|
||||
Some(i) => println!(
|
||||
|
||||
@@ -1,28 +1,62 @@
|
||||
//! Exercise the production updater only on a disposable copy of an installed server.
|
||||
use coa_core::{registry::MetaDir, update::{self, Env, RepackEnv}};
|
||||
fn main() -> Result<(),Box<dyn std::error::Error>> {
|
||||
let args:Vec<_>=std::env::args().collect();
|
||||
if args.len()!=3 && args.len()!=4 {return Err("usage: upgrade_fixture <disposable-root> <signed-package-directory>".into());}
|
||||
let root=std::path::Path::new(&args[1]);
|
||||
assert!(root.file_name().unwrap().to_string_lossy().starts_with("coa-schema-fixture-real") && root.join(".coa-update-fixture").is_file(),"Disposable fixture required");
|
||||
let meta=coa_core::registry::metadata_dir_for(root)?;
|
||||
let (_,installed)=MetaDir::open(&meta)?;
|
||||
assert_eq!(coa_core::fsx::canonicalize_lenient(std::path::Path::new(&installed.server_path))?,coa_core::fsx::canonicalize_lenient(root)?,"Fixture metadata must point to the copy");
|
||||
assert!(installed.client_path.is_none(),"Detach the real client from fixture metadata");
|
||||
let env=RepackEnv{root,meta_dir:&meta};
|
||||
if args.get(3).is_some_and(|flag|flag=="--validate-only") {
|
||||
let result=env.validate();
|
||||
let _=coa_core::driver::run(root,coa_core::driver::Verb::StopAll);
|
||||
result?;
|
||||
println!("Startup and identity validation passed");
|
||||
return Ok(());
|
||||
}
|
||||
let outcome=update::apply(&update::Params{root,meta_dir:&meta,source:coa_core::pkgsource::Source::Dir(args[2].clone().into()),trusted_key:coa_core::signing::EMBEDDED_PUBLIC_KEY,cancel:Default::default(),resolutions:Default::default(),env:&env,fail_after_ops:None},&|phase,percent|println!("{percent}% {phase}"));
|
||||
let stopped=coa_core::driver::run(root,coa_core::driver::Verb::StopAll);
|
||||
println!("Shutdown after test: {:?}",stopped.map(|r|r.ok));
|
||||
let outcome=outcome?;
|
||||
println!("Final transaction: {:?}",outcome.txn.state);
|
||||
env.ensure_stopped()?;
|
||||
assert_eq!(outcome.txn.state,update::State::Committed);
|
||||
Ok(())
|
||||
use coa_core::{
|
||||
registry::MetaDir,
|
||||
update::{self, Env, RepackEnv},
|
||||
};
|
||||
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let args: Vec<_> = std::env::args().collect();
|
||||
if args.len() != 3 && args.len() != 4 {
|
||||
return Err("usage: upgrade_fixture <disposable-root> <signed-package-directory>".into());
|
||||
}
|
||||
let root = std::path::Path::new(&args[1]);
|
||||
assert!(
|
||||
root.file_name()
|
||||
.unwrap()
|
||||
.to_string_lossy()
|
||||
.starts_with("coa-schema-fixture-real")
|
||||
&& root.join(".coa-update-fixture").is_file(),
|
||||
"Disposable fixture required"
|
||||
);
|
||||
let meta = coa_core::registry::metadata_dir_for(root)?;
|
||||
let (_, installed) = MetaDir::open(&meta)?;
|
||||
assert_eq!(
|
||||
coa_core::fsx::canonicalize_lenient(std::path::Path::new(&installed.server_path))?,
|
||||
coa_core::fsx::canonicalize_lenient(root)?,
|
||||
"Fixture metadata must point to the copy"
|
||||
);
|
||||
assert!(
|
||||
installed.client_path.is_none(),
|
||||
"Detach the real client from fixture metadata"
|
||||
);
|
||||
let env = RepackEnv {
|
||||
root,
|
||||
meta_dir: &meta,
|
||||
};
|
||||
if args.get(3).is_some_and(|flag| flag == "--validate-only") {
|
||||
let result = env.validate();
|
||||
let _ = coa_core::driver::run(root, coa_core::driver::Verb::StopAll);
|
||||
result?;
|
||||
println!("Startup and identity validation passed");
|
||||
return Ok(());
|
||||
}
|
||||
let outcome = update::apply(
|
||||
&update::Params {
|
||||
root,
|
||||
meta_dir: &meta,
|
||||
source: coa_core::pkgsource::Source::Dir(args[2].clone().into()),
|
||||
trusted_key: coa_core::signing::EMBEDDED_PUBLIC_KEY,
|
||||
cancel: Default::default(),
|
||||
resolutions: Default::default(),
|
||||
env: &env,
|
||||
fail_after_ops: None,
|
||||
},
|
||||
&|phase, percent| println!("{percent}% {phase}"),
|
||||
);
|
||||
let stopped = coa_core::driver::run(root, coa_core::driver::Verb::StopAll);
|
||||
println!("Shutdown after test: {:?}", stopped.map(|r| r.ok));
|
||||
let outcome = outcome?;
|
||||
println!("Final transaction: {:?}", outcome.txn.state);
|
||||
env.ensure_stopped()?;
|
||||
assert_eq!(outcome.txn.state, update::State::Committed);
|
||||
Ok(())
|
||||
}
|
||||
@@ -261,7 +261,9 @@ pub fn config_files(root: &Path) -> Vec<String> {
|
||||
for e in rd.flatten() {
|
||||
let n = e.file_name().to_string_lossy().to_string();
|
||||
// database.json holds generated database passwords; it is launcher state, not configuration.
|
||||
if e.path().is_file() && (n.contains(".template") || n == "repack.json" || n == "docker.json") {
|
||||
if e.path().is_file()
|
||||
&& (n.contains(".template") || n == "repack.json" || n == "docker.json")
|
||||
{
|
||||
out.push(format!("Settings/{n}"));
|
||||
}
|
||||
}
|
||||
@@ -381,12 +383,19 @@ pub fn create(
|
||||
let build = || -> Result<Vec<Component>> {
|
||||
let mut components = Vec::new();
|
||||
let realm = crate::realms::state(root)?;
|
||||
let mut databases: Vec<(String, &str)> = wanted_databases(kind).iter()
|
||||
.map(|name| Ok((name.to_string(), realm.active.schema(name)?))).collect::<Result<_>>()?;
|
||||
let mut databases: Vec<(String, &str)> = wanted_databases(kind)
|
||||
.iter()
|
||||
.map(|name| Ok((name.to_string(), realm.active.schema(name)?)))
|
||||
.collect::<Result<_>>()?;
|
||||
if kind != Kind::Config {
|
||||
for other in realm.modes().into_iter().filter(|m| *m != realm.active) {
|
||||
databases.push((format!("{}-characters", other.name()), other.schema("characters")?));
|
||||
if kind == Kind::Full { databases.push((format!("{}-world", other.name()), other.schema("world")?)); }
|
||||
databases.push((
|
||||
format!("{}-characters", other.name()),
|
||||
other.schema("characters")?,
|
||||
));
|
||||
if kind == Kind::Full {
|
||||
databases.push((format!("{}-world", other.name()), other.schema("world")?));
|
||||
}
|
||||
}
|
||||
}
|
||||
if kind != Kind::Config && with_database(root, |db| db.schema_exists("acore_playerbots"))? {
|
||||
@@ -427,16 +436,24 @@ pub fn create(
|
||||
return Err(e);
|
||||
}
|
||||
};
|
||||
let mysql_snapshot = if kind == Kind::Full && matches!(trigger, Trigger::BeforeUpdate | Trigger::BeforeRepair) && cfg!(windows) && !crate::docker::is_docker(root) {
|
||||
let mysql_snapshot = if kind == Kind::Full
|
||||
&& matches!(trigger, Trigger::BeforeUpdate | Trigger::BeforeRepair)
|
||||
&& cfg!(windows)
|
||||
&& !crate::docker::is_docker(root)
|
||||
{
|
||||
progress("Saving a complete stopped MySQL recovery copy");
|
||||
match crate::mysql_snapshot::capture(root, &partial) {
|
||||
Ok(snapshot) => Some(snapshot),
|
||||
Err(error) => {
|
||||
if let Ok(owned) = fsx::ensure_within(&backups_dir(meta), &partial) { let _ = fs::remove_dir_all(owned); }
|
||||
if let Ok(owned) = fsx::ensure_within(&backups_dir(meta), &partial) {
|
||||
let _ = fs::remove_dir_all(owned);
|
||||
}
|
||||
return Err(error);
|
||||
}
|
||||
}
|
||||
} else { None };
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let point = RecoveryPoint {
|
||||
realm: crate::realms::state(root)?.active,
|
||||
schema: 1,
|
||||
@@ -485,7 +502,9 @@ pub fn verify(meta: &Path, id: &str) -> Result<VerifyReport> {
|
||||
let dir = point_dir(meta, id)?;
|
||||
let mut problems = Vec::new();
|
||||
if let Some(snapshot) = &point.mysql_snapshot {
|
||||
if let Err(error) = crate::mysql_snapshot::verify(&dir, snapshot) { problems.push(error.to_string()); }
|
||||
if let Err(error) = crate::mysql_snapshot::verify(&dir, snapshot) {
|
||||
problems.push(error.to_string());
|
||||
}
|
||||
}
|
||||
let mut names = std::collections::BTreeSet::new();
|
||||
let mut schemas = std::collections::BTreeSet::new();
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! Signed channel pointers select one immutable package for an entire transaction.
|
||||
use serde::{Deserialize, Serialize};
|
||||
use crate::{Error, Result};
|
||||
use crate::pkgsource::{fetch_small, Source};
|
||||
use crate::{Error, Result};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
@@ -21,15 +21,22 @@ pub struct Envelope {
|
||||
}
|
||||
|
||||
pub fn verify(bytes: &[u8], channel: &str, key: &str) -> Result<Pointer> {
|
||||
let envelope: Envelope = serde_json::from_slice(bytes).map_err(|e| Error::InvalidManifest(e.to_string()))?;
|
||||
let envelope: Envelope =
|
||||
serde_json::from_slice(bytes).map_err(|e| Error::InvalidManifest(e.to_string()))?;
|
||||
crate::signing::verify(envelope.payload.as_bytes(), &envelope.signature, key)?;
|
||||
let pointer: Pointer = serde_json::from_str(&envelope.payload).map_err(|e| Error::InvalidManifest(e.to_string()))?;
|
||||
if pointer.schema != 1 || pointer.channel != channel
|
||||
let pointer: Pointer = serde_json::from_str(&envelope.payload)
|
||||
.map_err(|e| Error::InvalidManifest(e.to_string()))?;
|
||||
if pointer.schema != 1
|
||||
|| pointer.channel != channel
|
||||
|| pointer.release_tag != format!("server-{}", pointer.version)
|
||||
|| pointer.version.is_empty()
|
||||
|| !pointer.version.bytes().all(|b| b.is_ascii_digit() || b == b'.')
|
||||
|| !pointer
|
||||
.version
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_digit() || b == b'.')
|
||||
|| pointer.snapshot.len() != 64
|
||||
|| !pointer.snapshot.bytes().all(|b| b.is_ascii_hexdigit()) {
|
||||
|| !pointer.snapshot.bytes().all(|b| b.is_ascii_hexdigit())
|
||||
{
|
||||
return Err(Error::InvalidManifest("Invalid channel pointer".into()));
|
||||
}
|
||||
Ok(pointer)
|
||||
@@ -39,21 +46,37 @@ pub fn resolve(channel: &str) -> Result<Source> {
|
||||
if channel != "stable" && channel != "edge" {
|
||||
return Err(Error::InvalidManifest("Unknown release channel".into()));
|
||||
}
|
||||
let source = Source::Url("https://raw.githubusercontent.com/Corfirean/coa-server-build/channels".into());
|
||||
let source =
|
||||
Source::Url("https://raw.githubusercontent.com/Corfirean/coa-server-build/channels".into());
|
||||
let bytes = fetch_small(&source, &format!("{channel}.json"))?;
|
||||
let pointer = verify(&bytes, channel, crate::signing::EMBEDDED_PUBLIC_KEY)?;
|
||||
Ok(Source::Url(format!("https://github.com/Corfirean/coa-server-build/releases/download/{}", pointer.release_tag)))
|
||||
Ok(Source::Url(format!(
|
||||
"https://github.com/Corfirean/coa-server-build/releases/download/{}",
|
||||
pointer.release_tag
|
||||
)))
|
||||
}
|
||||
|
||||
pub fn sign(pointer: &Pointer, seed: &str) -> Result<Vec<u8>> {
|
||||
use base64::{engine::general_purpose::STANDARD, Engine};
|
||||
use ed25519_dalek::{Signer, SigningKey};
|
||||
let seed: [u8; 32] = STANDARD.decode(seed.trim()).map_err(|_| Error::Invalid("Invalid signing key".into()))?
|
||||
.try_into().map_err(|_| Error::Invalid("Invalid signing key length".into()))?;
|
||||
let seed: [u8; 32] = STANDARD
|
||||
.decode(seed.trim())
|
||||
.map_err(|_| Error::Invalid("Invalid signing key".into()))?
|
||||
.try_into()
|
||||
.map_err(|_| Error::Invalid("Invalid signing key length".into()))?;
|
||||
let payload = serde_json::to_string(pointer).map_err(|e| Error::Invalid(e.to_string()))?;
|
||||
let signature = STANDARD.encode(SigningKey::from_bytes(&seed).sign(payload.as_bytes()).to_bytes());
|
||||
let bytes = serde_json::to_vec(&Envelope { payload, signature }).map_err(|e| Error::Invalid(e.to_string()))?;
|
||||
verify(&bytes, &pointer.channel, crate::signing::EMBEDDED_PUBLIC_KEY)?;
|
||||
let signature = STANDARD.encode(
|
||||
SigningKey::from_bytes(&seed)
|
||||
.sign(payload.as_bytes())
|
||||
.to_bytes(),
|
||||
);
|
||||
let bytes = serde_json::to_vec(&Envelope { payload, signature })
|
||||
.map_err(|e| Error::Invalid(e.to_string()))?;
|
||||
verify(
|
||||
&bytes,
|
||||
&pointer.channel,
|
||||
crate::signing::EMBEDDED_PUBLIC_KEY,
|
||||
)?;
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
@@ -67,12 +90,21 @@ mod tests {
|
||||
let sk = SigningKey::from_bytes(&[17; 32]);
|
||||
let payload = serde_json::to_string(pointer).unwrap();
|
||||
let signature = STANDARD.encode(sk.sign(payload.as_bytes()).to_bytes());
|
||||
(serde_json::to_vec(&Envelope { payload, signature }).unwrap(), STANDARD.encode(sk.verifying_key().to_bytes()))
|
||||
(
|
||||
serde_json::to_vec(&Envelope { payload, signature }).unwrap(),
|
||||
STANDARD.encode(sk.verifying_key().to_bytes()),
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn verifies_identity_signature_and_immutable_tag() {
|
||||
let mut p = Pointer { schema: 1, channel: "stable".into(), version: "0.261010.40".into(), release_tag: "server-0.261010.40".into(), snapshot: "a".repeat(64) };
|
||||
let mut p = Pointer {
|
||||
schema: 1,
|
||||
channel: "stable".into(),
|
||||
version: "0.261010.40".into(),
|
||||
release_tag: "server-0.261010.40".into(),
|
||||
snapshot: "a".repeat(64),
|
||||
};
|
||||
let (bytes, key) = signed(&p);
|
||||
assert_eq!(verify(&bytes, "stable", &key).unwrap().version, p.version);
|
||||
assert!(verify(&bytes, "edge", &key).is_err());
|
||||
|
||||
@@ -417,11 +417,21 @@ pub fn launch(client: &Path) -> Result<u32> {
|
||||
return crate::wine::launch(client, exe);
|
||||
}
|
||||
let executable = client.join(exe);
|
||||
let spawn = || Command::new(&executable).current_dir(client).spawn().map(|child| child.id());
|
||||
let spawn = || {
|
||||
Command::new(&executable)
|
||||
.current_dir(client)
|
||||
.spawn()
|
||||
.map(|child| child.id())
|
||||
};
|
||||
#[cfg(windows)]
|
||||
{ launch_with_elevation_fallback(spawn, || launch_elevated(&executable, client)).map_err(Into::into) }
|
||||
{
|
||||
launch_with_elevation_fallback(spawn, || launch_elevated(&executable, client))
|
||||
.map_err(Into::into)
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
{ spawn().map_err(Into::into) }
|
||||
{
|
||||
spawn().map_err(Into::into)
|
||||
}
|
||||
}
|
||||
|
||||
/// Start normally first; ask Windows for elevation only when the client requires it (ERROR_ELEVATION_REQUIRED, 740).
|
||||
@@ -443,9 +453,15 @@ fn launch_elevated(executable: &Path, directory: &Path) -> std::io::Result<u32>
|
||||
use std::os::windows::ffi::OsStrExt;
|
||||
use windows_sys::Win32::Foundation::CloseHandle;
|
||||
use windows_sys::Win32::System::Threading::GetProcessId;
|
||||
use windows_sys::Win32::UI::Shell::{ShellExecuteExW, SHELLEXECUTEINFOW, SEE_MASK_NOCLOSEPROCESS, SEE_MASK_NOASYNC};
|
||||
use windows_sys::Win32::UI::Shell::{
|
||||
ShellExecuteExW, SEE_MASK_NOASYNC, SEE_MASK_NOCLOSEPROCESS, SHELLEXECUTEINFOW,
|
||||
};
|
||||
use windows_sys::Win32::UI::WindowsAndMessaging::SW_SHOWNORMAL;
|
||||
let file: Vec<u16> = executable.as_os_str().encode_wide().chain(Some(0)).collect();
|
||||
let file: Vec<u16> = executable
|
||||
.as_os_str()
|
||||
.encode_wide()
|
||||
.chain(Some(0))
|
||||
.collect();
|
||||
let cwd: Vec<u16> = directory.as_os_str().encode_wide().chain(Some(0)).collect();
|
||||
let verb: Vec<u16> = "runas".encode_utf16().chain(Some(0)).collect();
|
||||
let mut info = SHELLEXECUTEINFOW {
|
||||
@@ -457,12 +473,22 @@ fn launch_elevated(executable: &Path, directory: &Path) -> std::io::Result<u32>
|
||||
nShow: SW_SHOWNORMAL,
|
||||
..Default::default()
|
||||
};
|
||||
if unsafe { ShellExecuteExW(&mut info) } == 0 { return Err(std::io::Error::last_os_error()); }
|
||||
if info.hProcess.is_null() { return Err(std::io::Error::other("Windows did not return the game process handle.")); }
|
||||
if unsafe { ShellExecuteExW(&mut info) } == 0 {
|
||||
return Err(std::io::Error::last_os_error());
|
||||
}
|
||||
if info.hProcess.is_null() {
|
||||
return Err(std::io::Error::other(
|
||||
"Windows did not return the game process handle.",
|
||||
));
|
||||
}
|
||||
let pid = unsafe { GetProcessId(info.hProcess) };
|
||||
let error = std::io::Error::last_os_error();
|
||||
unsafe { CloseHandle(info.hProcess); }
|
||||
if pid == 0 { return Err(error); }
|
||||
unsafe {
|
||||
CloseHandle(info.hProcess);
|
||||
}
|
||||
if pid == 0 {
|
||||
return Err(error);
|
||||
}
|
||||
Ok(pid)
|
||||
}
|
||||
|
||||
@@ -585,11 +611,29 @@ mod tests {
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn elevation_is_requested_only_when_windows_requires_it() {
|
||||
assert_eq!(launch_with_elevation_fallback(|| Ok(17), || panic!("unneeded elevation")).unwrap(), 17);
|
||||
assert_eq!(launch_with_elevation_fallback(|| Err(std::io::Error::from_raw_os_error(740)), || Ok(23)).unwrap(), 23);
|
||||
let error = launch_with_elevation_fallback(|| Err(std::io::Error::from_raw_os_error(2)), || panic!("wrong error elevated")).unwrap_err();
|
||||
assert_eq!(
|
||||
launch_with_elevation_fallback(|| Ok(17), || panic!("unneeded elevation")).unwrap(),
|
||||
17
|
||||
);
|
||||
assert_eq!(
|
||||
launch_with_elevation_fallback(
|
||||
|| Err(std::io::Error::from_raw_os_error(740)),
|
||||
|| Ok(23)
|
||||
)
|
||||
.unwrap(),
|
||||
23
|
||||
);
|
||||
let error = launch_with_elevation_fallback(
|
||||
|| Err(std::io::Error::from_raw_os_error(2)),
|
||||
|| panic!("wrong error elevated"),
|
||||
)
|
||||
.unwrap_err();
|
||||
assert_eq!(error.raw_os_error(), Some(2));
|
||||
let cancelled = launch_with_elevation_fallback(|| Err(std::io::Error::from_raw_os_error(740)), || Err(std::io::Error::from_raw_os_error(1223))).unwrap_err();
|
||||
let cancelled = launch_with_elevation_fallback(
|
||||
|| Err(std::io::Error::from_raw_os_error(740)),
|
||||
|| Err(std::io::Error::from_raw_os_error(1223)),
|
||||
)
|
||||
.unwrap_err();
|
||||
assert_eq!(cancelled.raw_os_error(), Some(1223));
|
||||
}
|
||||
|
||||
@@ -620,7 +664,10 @@ mod tests {
|
||||
assert!(sync_realm(&c, &meta, crate::realms::Mode::Wildcard).unwrap());
|
||||
assert_eq!(fs::read(c.join("WTF/Config.wtf")).unwrap(), original);
|
||||
assert!(sync_realm(&c, &meta, crate::realms::Mode::Reborn).unwrap());
|
||||
assert_eq!(fs::read(c.join("WTF/Config.wtf")).unwrap(), b"SET sound 1\r\nSET realmName \"Warcraft Reborn\"\r\n");
|
||||
assert_eq!(
|
||||
fs::read(c.join("WTF/Config.wtf")).unwrap(),
|
||||
b"SET sound 1\r\nSET realmName \"Warcraft Reborn\"\r\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
pub mod merge;
|
||||
pub mod parser;
|
||||
pub mod portable;
|
||||
pub mod schema;
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
@@ -1033,6 +1034,53 @@ 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();
|
||||
|
||||
@@ -0,0 +1,175 @@
|
||||
//! 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
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -61,8 +61,16 @@ pub fn lines_from_text(text: &str, filter: Option<&str>, max_lines: usize) -> Ve
|
||||
let out: Vec<Line> = text
|
||||
.lines()
|
||||
.filter(|l| !l.trim().is_empty())
|
||||
.filter(|l| needle.as_ref().map(|n| l.to_lowercase().contains(n)).unwrap_or(true))
|
||||
.map(|l| Line { level: classify(l), text: crate::diag::redact(l) })
|
||||
.filter(|l| {
|
||||
needle
|
||||
.as_ref()
|
||||
.map(|n| l.to_lowercase().contains(n))
|
||||
.unwrap_or(true)
|
||||
})
|
||||
.map(|l| Line {
|
||||
level: classify(l),
|
||||
text: crate::diag::redact(l),
|
||||
})
|
||||
.collect();
|
||||
let skip = out.len().saturating_sub(max_lines);
|
||||
out.into_iter().skip(skip).collect()
|
||||
|
||||
@@ -63,9 +63,47 @@ 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> {
|
||||
find_access(&self.descriptors, &(self.installs)(), local_id)
|
||||
.ok_or_else(|| Error::Invalid("That realm is not known to this Manager.".into()))
|
||||
let access =
|
||||
find_access(&self.descriptors, &(self.installs)(), local_id).ok_or_else(|| {
|
||||
Error::Invalid(format!(
|
||||
"That realm is not known to this Manager: {local_id}"
|
||||
))
|
||||
})?;
|
||||
if let Some((_base, rs)) = local_id.split_once(':') {
|
||||
let expected_mode = match rs {
|
||||
"coa" => crate::realms::Mode::Coa,
|
||||
"wildcard" => crate::realms::Mode::Wildcard,
|
||||
"reborn" => crate::realms::Mode::Reborn,
|
||||
_ => {
|
||||
return Err(Error::Invalid(format!(
|
||||
"Malformed or unknown ruleset suffix in local_id: {rs}"
|
||||
)))
|
||||
}
|
||||
};
|
||||
if access.mode != Some(expected_mode) {
|
||||
return Err(Error::Invalid(format!(
|
||||
"Realm access mode {:?} does not match expected ruleset in local_id {local_id}",
|
||||
access.mode
|
||||
)));
|
||||
}
|
||||
}
|
||||
Ok(access)
|
||||
}
|
||||
|
||||
fn account(&self, local_id: &str, filter: &str) -> Result<Option<AccountRow>> {
|
||||
@@ -84,11 +122,73 @@ 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)?;
|
||||
let db = access.db()?;
|
||||
let ruleset = realm::ruleset_of(&db).map_err(|e| Error::Invalid(e.to_string()))?;
|
||||
|
||||
// Explicit local-id -> ruleset invariant:
|
||||
// local_id ruleset == RealmAccess.mode == Db.realm() == RealmInfo.ruleset
|
||||
if let Some((_base, rs)) = local_id.split_once(':') {
|
||||
let expected_ruleset: crate::portable::Ruleset = rs
|
||||
.parse()
|
||||
.map_err(|_| Error::Invalid(format!("Unknown ruleset in local_id: {rs}")))?;
|
||||
if ruleset != expected_ruleset {
|
||||
return Err(Error::Invalid(format!(
|
||||
"Ruleset of realm DB ({ruleset:?}) does not match local_id {local_id}"
|
||||
)));
|
||||
}
|
||||
if access.mode.map(|m| m.name()) != Some(expected_ruleset.as_str()) {
|
||||
return Err(Error::Invalid(format!(
|
||||
"RealmAccess mode ({:?}) does not match local_id {local_id}",
|
||||
access.mode
|
||||
)));
|
||||
}
|
||||
if db.realm().name() != expected_ruleset.as_str() {
|
||||
return Err(Error::Invalid(format!(
|
||||
"Db realm ({:?}) does not match local_id {local_id}",
|
||||
db.realm()
|
||||
)));
|
||||
}
|
||||
}
|
||||
|
||||
Ok(RealmInfo {
|
||||
automatic: cfg.as_ref().is_none_or(|c| !c.existing_only),
|
||||
route: cfg.and_then(|c| c.route),
|
||||
ruleset,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -203,6 +303,7 @@ 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
|
||||
@@ -211,6 +312,7 @@ impl RealmBackend for LocalBackend {
|
||||
.map_err(|e| unavailable("export", e))?;
|
||||
Ok(ClaimExport {
|
||||
character_id: bundle.character_id.as_uuid(),
|
||||
ruleset: bundle.ruleset,
|
||||
payload: bundle.payload,
|
||||
sha256: bundle.content_hash,
|
||||
collections: bundle.collections,
|
||||
@@ -223,6 +325,7 @@ 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))?;
|
||||
@@ -237,10 +340,807 @@ 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))
|
||||
.map_err(|e| unavailable("portable engine", e))?
|
||||
.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>() {
|
||||
return Ok(p);
|
||||
}
|
||||
}
|
||||
let access = self.access(local_id)?;
|
||||
let mode = if let Some(m) = access.mode {
|
||||
m
|
||||
} else if let Some((_base, _rs)) = local_id.split_once(':') {
|
||||
return Err(Error::Invalid(format!(
|
||||
"Unresolved mode for ruleset suffix in {local_id}"
|
||||
)));
|
||||
} else {
|
||||
// Legacy unsuffixed CoA realm ONLY
|
||||
crate::realms::Mode::Coa
|
||||
};
|
||||
if let Some(ref root) = access.root {
|
||||
crate::realms::world_port_for_mode(root, mode)
|
||||
} else {
|
||||
Err(Error::Invalid(format!(
|
||||
"No server installation root for {local_id} to resolve world port"
|
||||
)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
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();
|
||||
let settings = dir.path().join("Settings");
|
||||
fs::create_dir_all(&settings).unwrap();
|
||||
fs::write(settings.join("registry.json"), "{}").unwrap();
|
||||
|
||||
let desc_dir = dir.path().join("descriptors");
|
||||
fs::create_dir_all(&desc_dir).unwrap();
|
||||
|
||||
let portable_dir = dir.path().join("portable");
|
||||
let rt = PortableRuntime::start(&portable_dir, Box::new(Vec::new), None).unwrap();
|
||||
let backend = LocalBackend::new(Arc::new(rt), &settings, &desc_dir, Arc::new(Vec::new));
|
||||
|
||||
// Unknown realm id must return Err, never Ok(RealmInfo { ruleset: Ruleset::Coa, .. })
|
||||
assert!(backend.info("srv-unknown").is_err());
|
||||
assert!(backend.info("srv-unknown:wildcard").is_err());
|
||||
assert!(backend.info("srv-unknown:reborn").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn world_port_for_mode_distinguishes_simultaneous_realms() {
|
||||
let dir = tempdir().unwrap();
|
||||
let root = dir.path().join("srv");
|
||||
fs::create_dir_all(root.join("Settings")).unwrap();
|
||||
fs::write(root.join("Settings/repack.json"), r#"{"worldPort": 8085}"#).unwrap();
|
||||
fs::write(
|
||||
root.join("Settings/realm-profile.json"),
|
||||
r#"{"active": "coa", "wildcard_created": true, "simultaneous": true, "secondary_world_port": 8086}"#,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
crate::realms::world_port_for_mode(&root, crate::realms::Mode::Coa).unwrap(),
|
||||
8085
|
||||
);
|
||||
assert_eq!(
|
||||
crate::realms::world_port_for_mode(&root, crate::realms::Mode::Wildcard).unwrap(),
|
||||
8086
|
||||
);
|
||||
|
||||
let desc_dir = dir.path().join("descriptors");
|
||||
let portable_dir = dir.path().join("portable");
|
||||
let rt = PortableRuntime::start(&portable_dir, Box::new(Vec::new), None).unwrap();
|
||||
let root_clone = root.clone();
|
||||
let backend = LocalBackend::new(
|
||||
Arc::new(rt),
|
||||
root.join("Settings"),
|
||||
&desc_dir,
|
||||
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);
|
||||
|
||||
// When simultaneous is false and active is CoA:
|
||||
fs::write(
|
||||
root.join("Settings/realm-profile.json"),
|
||||
r#"{"active": "coa", "wildcard_created": true, "simultaneous": false}"#,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
// CoA succeeds with 8085
|
||||
assert_eq!(backend.world_port("srv-test1:coa").unwrap(), 8085);
|
||||
// Wildcard must FAIL CLOSED, never return 8085
|
||||
let err_wc_mode =
|
||||
crate::realms::world_port_for_mode(&root, crate::realms::Mode::Wildcard).unwrap_err();
|
||||
assert!(
|
||||
err_wc_mode.to_string().contains("not active"),
|
||||
"Expected not active error, got: {err_wc_mode}"
|
||||
);
|
||||
assert!(backend.world_port("srv-test1:wildcard").is_err());
|
||||
|
||||
// Reborn must FAIL CLOSED
|
||||
let err_reb_mode =
|
||||
crate::realms::world_port_for_mode(&root, crate::realms::Mode::Reborn).unwrap_err();
|
||||
assert!(
|
||||
err_reb_mode.to_string().contains("not active"),
|
||||
"Expected not active error, got: {err_reb_mode}"
|
||||
);
|
||||
assert!(backend.world_port("srv-test1:reborn").is_err());
|
||||
|
||||
// When active is Reborn:
|
||||
fs::write(
|
||||
root.join("Settings/realm-profile.json"),
|
||||
r#"{"active": "reborn", "wildcard_created": true, "reborn_created": true, "simultaneous": false}"#,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
// Reborn succeeds with primary world port 8085
|
||||
assert_eq!(backend.world_port("srv-test1:reborn").unwrap(), 8085);
|
||||
// CoA must FAIL CLOSED when Reborn is active
|
||||
assert!(backend.world_port("srv-test1:coa").is_err());
|
||||
// Wildcard must FAIL CLOSED when Reborn is active
|
||||
assert!(backend.world_port("srv-test1:wildcard").is_err());
|
||||
|
||||
// Malformed and unknown suffixes must fail closed
|
||||
assert!(backend.access("srv-test1:unknown").is_err());
|
||||
assert!(backend.access("srv-test1:garbage").is_err());
|
||||
assert!(backend.access("srv-test1:coa:extra").is_err());
|
||||
assert!(backend.world_port("srv-test1:unknown").is_err());
|
||||
assert!(backend.world_port("srv-test1:garbage").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn world_port_lookup_failure_causes_direct_and_relay_to_fail_closed() {
|
||||
let dir = tempdir().unwrap();
|
||||
let root = dir.path().join("srv");
|
||||
fs::create_dir_all(root.join("Settings")).unwrap();
|
||||
fs::write(root.join("Settings/repack.json"), r#"{"worldPort": 8085}"#).unwrap();
|
||||
// Server only has active CoA, simultaneous is off
|
||||
fs::write(
|
||||
root.join("Settings/realm-profile.json"),
|
||||
r#"{"active": "coa", "wildcard_created": false, "simultaneous": false}"#,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let desc_dir = dir.path().join("descriptors");
|
||||
let portable_dir = dir.path().join("portable");
|
||||
let rt = PortableRuntime::start(&portable_dir, Box::new(Vec::new), None).unwrap();
|
||||
let root_clone = root.clone();
|
||||
let backend = Arc::new(LocalBackend::new(
|
||||
Arc::new(rt),
|
||||
root.join("Settings"),
|
||||
&desc_dir,
|
||||
Arc::new(move || vec![("test1".to_string(), root_clone.clone())]),
|
||||
));
|
||||
|
||||
let store = Arc::new(std::sync::Mutex::new(
|
||||
crate::control::store::ControlStore::open_in_memory().unwrap(),
|
||||
));
|
||||
let service = Arc::new(crate::control::service::HostService::new(
|
||||
"srv-test1:wildcard",
|
||||
coa_registry_proto::sign::RealmId::new(),
|
||||
store,
|
||||
backend,
|
||||
));
|
||||
|
||||
// 1. HostService::local_world_port fails closed
|
||||
assert!(service.local_world_port().is_err());
|
||||
|
||||
// 2. Direct route manager cannot find a direct route because world port resolution failed
|
||||
let mut direct_mgr =
|
||||
crate::control::direct_route::DirectRouteManager::start(None, service.clone());
|
||||
assert!(!direct_mgr.is_direct_ready());
|
||||
assert!(service.direct_route().is_none());
|
||||
direct_mgr.shutdown();
|
||||
|
||||
// 3. When relay link has no world port resolved, AllocateRelay refuses
|
||||
let mut session = crate::control::service::Session::default();
|
||||
let player = uuid::Uuid::now_v7();
|
||||
let resp = service.handle(
|
||||
&mut session,
|
||||
&player,
|
||||
"KEY",
|
||||
coa_control_proto::app::Request::AllocateRelay { player_id: player },
|
||||
);
|
||||
assert!(matches!(
|
||||
resp,
|
||||
coa_control_proto::app::Response::Error {
|
||||
code: coa_control_proto::app::AppError::NoAccount
|
||||
| coa_control_proto::app::AppError::RelayUnavailable,
|
||||
..
|
||||
}
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -33,8 +33,13 @@ impl DirectIngress {
|
||||
local_auth_port: u16,
|
||||
local_world_port: u16,
|
||||
) -> Result<Self> {
|
||||
let auth_host = if auth_bind_port == 0 {
|
||||
"127.0.0.1"
|
||||
} else {
|
||||
"0.0.0.0"
|
||||
};
|
||||
let auth_listener =
|
||||
TcpListener::bind(format!("0.0.0.0:{auth_bind_port}")).map_err(|e| {
|
||||
TcpListener::bind(format!("{auth_host}:{auth_bind_port}")).map_err(|e| {
|
||||
Error::Invalid(format!(
|
||||
"Cannot bind direct auth listener on port {auth_bind_port}: {e}"
|
||||
))
|
||||
@@ -47,8 +52,13 @@ impl DirectIngress {
|
||||
.map_err(|e| Error::Invalid(e.to_string()))?
|
||||
.port();
|
||||
|
||||
let world_host = if world_bind_port == 0 {
|
||||
"127.0.0.1"
|
||||
} else {
|
||||
"0.0.0.0"
|
||||
};
|
||||
let world_listener =
|
||||
TcpListener::bind(format!("0.0.0.0:{world_bind_port}")).map_err(|e| {
|
||||
TcpListener::bind(format!("{world_host}:{world_bind_port}")).map_err(|e| {
|
||||
Error::Invalid(format!(
|
||||
"Cannot bind direct world listener on port {world_bind_port}: {e}"
|
||||
))
|
||||
@@ -114,7 +124,11 @@ impl DirectIngress {
|
||||
std::thread::Builder::new()
|
||||
.name("direct-world-worker".into())
|
||||
.spawn(move || {
|
||||
let _ = handle_world_client(client_stream, local_world_port);
|
||||
if let Err(e) =
|
||||
handle_world_client(client_stream, local_world_port)
|
||||
{
|
||||
eprintln!("handle_world_client error: {e}");
|
||||
}
|
||||
})
|
||||
.ok();
|
||||
}
|
||||
@@ -174,8 +188,21 @@ fn handle_auth_client(
|
||||
local_auth_port: u16,
|
||||
world_target: Arc<std::sync::RwLock<String>>,
|
||||
) -> Result<()> {
|
||||
let mut server = TcpStream::connect(format!("127.0.0.1:{local_auth_port}"))
|
||||
.map_err(|e| Error::Invalid(format!("Cannot connect to local authserver: {e}")))?;
|
||||
let mut server = None;
|
||||
for _ in 0..5 {
|
||||
match TcpStream::connect(format!("127.0.0.1:{local_auth_port}")) {
|
||||
Ok(s) => {
|
||||
server = Some(s);
|
||||
break;
|
||||
}
|
||||
Err(_) => std::thread::sleep(Duration::from_millis(20)),
|
||||
}
|
||||
}
|
||||
let mut server = server.ok_or_else(|| {
|
||||
Error::Invalid(format!(
|
||||
"Cannot connect to local authserver: {local_auth_port}"
|
||||
))
|
||||
})?;
|
||||
|
||||
let _ = client.set_read_timeout(Some(Duration::from_millis(500)));
|
||||
let _ = server.set_read_timeout(Some(Duration::from_millis(500)));
|
||||
@@ -213,7 +240,7 @@ fn handle_auth_client(
|
||||
}
|
||||
done_c.store(true, Ordering::Relaxed);
|
||||
if let Some(s) = server_shutdown {
|
||||
let _ = s.shutdown(std::net::Shutdown::Both);
|
||||
let _ = s.shutdown(std::net::Shutdown::Write);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -261,8 +288,21 @@ fn handle_auth_client(
|
||||
}
|
||||
|
||||
fn handle_world_client(mut client: TcpStream, local_world_port: u16) -> Result<()> {
|
||||
let mut server = TcpStream::connect(format!("127.0.0.1:{local_world_port}"))
|
||||
.map_err(|e| Error::Invalid(format!("Cannot connect to local worldserver: {e}")))?;
|
||||
let mut server = None;
|
||||
for _ in 0..5 {
|
||||
match TcpStream::connect(format!("127.0.0.1:{local_world_port}")) {
|
||||
Ok(s) => {
|
||||
server = Some(s);
|
||||
break;
|
||||
}
|
||||
Err(_) => std::thread::sleep(Duration::from_millis(20)),
|
||||
}
|
||||
}
|
||||
let mut server = server.ok_or_else(|| {
|
||||
Error::Invalid(format!(
|
||||
"Cannot connect to local worldserver: {local_world_port}"
|
||||
))
|
||||
})?;
|
||||
|
||||
let _ = client.set_nonblocking(false);
|
||||
let _ = server.set_nonblocking(false);
|
||||
@@ -278,11 +318,11 @@ fn handle_world_client(mut client: TcpStream, local_world_port: u16) -> Result<(
|
||||
|
||||
let t_c2s = std::thread::spawn(move || {
|
||||
let _ = std::io::copy(&mut client_read, &mut server_write);
|
||||
let _ = server_write.shutdown(std::net::Shutdown::Both);
|
||||
let _ = server_write.shutdown(std::net::Shutdown::Write);
|
||||
});
|
||||
|
||||
let _ = std::io::copy(&mut server, &mut client);
|
||||
let _ = client.shutdown(std::net::Shutdown::Both);
|
||||
let _ = client.shutdown(std::net::Shutdown::Write);
|
||||
|
||||
let _ = t_c2s.join();
|
||||
Ok(())
|
||||
@@ -320,6 +360,7 @@ mod tests {
|
||||
let n = stream.read(&mut buf).unwrap();
|
||||
assert_eq!(&buf[..n], b"WORLD_PING");
|
||||
stream.write_all(b"WORLD_PONG").unwrap();
|
||||
stream.flush().unwrap();
|
||||
let _ = stream.shutdown(std::net::Shutdown::Write);
|
||||
});
|
||||
|
||||
@@ -337,25 +378,27 @@ mod tests {
|
||||
let mut buf = [0u8; 16];
|
||||
let _ = stream.read(&mut buf).unwrap();
|
||||
|
||||
let mut fake_realm_list = vec![
|
||||
0x10, // Opcode CMD_REALM_LIST
|
||||
0x00, 0x00, // Size placeholder
|
||||
0x00, 0x00, 0x00, 0x00, // Unused
|
||||
0x01, 0x00, // Realm count: 1
|
||||
0x01, 0x00, 0x00, 0x00, // Icon
|
||||
0x00, // Lock
|
||||
0x00, // Flags
|
||||
];
|
||||
fake_realm_list.extend_from_slice(b"RealmOne\0");
|
||||
fake_realm_list.extend_from_slice(b"127.0.0.1:8085\0"); // original target
|
||||
fake_realm_list.extend_from_slice(&[0x00, 0x00, 0x00, 0x00]); // Population
|
||||
fake_realm_list.extend_from_slice(&[0x01]); // Num characters
|
||||
fake_realm_list.extend_from_slice(&[0x01]); // Timezone
|
||||
fake_realm_list.extend_from_slice(&[0x00]); // Realm ID
|
||||
fake_realm_list.extend_from_slice(&[0x02, 0x00]); // Footer
|
||||
let name_bytes = b"RealmOne\0";
|
||||
let addr_bytes = b"127.0.0.1:8085\0";
|
||||
let body_len = 4 + 2 + 3 + name_bytes.len() + addr_bytes.len() + 4 + 1 + 1 + 1 + 2;
|
||||
|
||||
let body_len = (fake_realm_list.len() - 3) as u16;
|
||||
fake_realm_list[1..3].copy_from_slice(&body_len.to_le_bytes());
|
||||
let mut fake_realm_list = Vec::new();
|
||||
fake_realm_list.push(0x10); // Opcode
|
||||
fake_realm_list.extend_from_slice(&(body_len as u16).to_le_bytes()); // Length
|
||||
fake_realm_list.extend_from_slice(&0u32.to_le_bytes()); // Unused
|
||||
fake_realm_list.extend_from_slice(&1u16.to_le_bytes()); // Realm count = 1
|
||||
|
||||
// Realm info:
|
||||
fake_realm_list.extend_from_slice(&[1, 0, 0]); // type, lock, flag
|
||||
fake_realm_list.extend_from_slice(name_bytes);
|
||||
fake_realm_list.extend_from_slice(addr_bytes);
|
||||
fake_realm_list.extend_from_slice(&[0, 0, 0, 0]); // pop
|
||||
fake_realm_list.extend_from_slice(&[0]); // chars
|
||||
fake_realm_list.extend_from_slice(&[1]); // timezone
|
||||
fake_realm_list.extend_from_slice(&[1]); // realm id
|
||||
|
||||
// Footer:
|
||||
fake_realm_list.extend_from_slice(&[0x10, 0x00]);
|
||||
|
||||
stream.write_all(&fake_realm_list).unwrap();
|
||||
let _ = stream.shutdown(std::net::Shutdown::Write);
|
||||
@@ -386,7 +429,7 @@ mod tests {
|
||||
let mock_world_port = mock_world.local_addr().unwrap().port();
|
||||
|
||||
// DirectIngress binds to ephemeral ports (0, 0), so actual ingress port != 8085
|
||||
let ingress = DirectIngress::start(
|
||||
let mut ingress = DirectIngress::start(
|
||||
0,
|
||||
0,
|
||||
"198.51.100.1".to_string(),
|
||||
@@ -415,25 +458,27 @@ mod tests {
|
||||
let mut buf = [0u8; 16];
|
||||
let _ = stream.read(&mut buf).unwrap();
|
||||
|
||||
let mut fake_realm_list = vec![
|
||||
0x10, // Opcode CMD_REALM_LIST
|
||||
0x00, 0x00, // Size placeholder
|
||||
0x00, 0x00, 0x00, 0x00, // Unused
|
||||
0x01, 0x00, // Realm count: 1
|
||||
0x01, 0x00, 0x00, 0x00, // Icon
|
||||
0x00, // Lock
|
||||
0x00, // Flags
|
||||
];
|
||||
fake_realm_list.extend_from_slice(b"RealmOne\0");
|
||||
fake_realm_list.extend_from_slice(b"127.0.0.1:8085\0");
|
||||
fake_realm_list.extend_from_slice(&[0x00, 0x00, 0x00, 0x00]);
|
||||
fake_realm_list.extend_from_slice(&[0x01]);
|
||||
fake_realm_list.extend_from_slice(&[0x01]);
|
||||
fake_realm_list.extend_from_slice(&[0x00]);
|
||||
fake_realm_list.extend_from_slice(&[0x02, 0x00]);
|
||||
let name_bytes = b"RealmOne\0";
|
||||
let addr_bytes = b"127.0.0.1:8085\0";
|
||||
let body_len = 4 + 2 + 3 + name_bytes.len() + addr_bytes.len() + 4 + 1 + 1 + 1 + 2;
|
||||
|
||||
let body_len = (fake_realm_list.len() - 3) as u16;
|
||||
fake_realm_list[1..3].copy_from_slice(&body_len.to_le_bytes());
|
||||
let mut fake_realm_list = Vec::new();
|
||||
fake_realm_list.push(0x10); // Opcode
|
||||
fake_realm_list.extend_from_slice(&(body_len as u16).to_le_bytes()); // Length
|
||||
fake_realm_list.extend_from_slice(&0u32.to_le_bytes()); // Unused
|
||||
fake_realm_list.extend_from_slice(&1u16.to_le_bytes()); // Realm count = 1
|
||||
|
||||
// Realm info:
|
||||
fake_realm_list.extend_from_slice(&[1, 0, 0]); // type, lock, flag
|
||||
fake_realm_list.extend_from_slice(name_bytes);
|
||||
fake_realm_list.extend_from_slice(addr_bytes);
|
||||
fake_realm_list.extend_from_slice(&[0, 0, 0, 0]); // pop
|
||||
fake_realm_list.extend_from_slice(&[0]); // chars
|
||||
fake_realm_list.extend_from_slice(&[1]); // timezone
|
||||
fake_realm_list.extend_from_slice(&[1]); // realm id
|
||||
|
||||
// Footer:
|
||||
fake_realm_list.extend_from_slice(&[0x10, 0x00]);
|
||||
|
||||
stream.write_all(&fake_realm_list).unwrap();
|
||||
let _ = stream.shutdown(std::net::Shutdown::Write);
|
||||
@@ -462,5 +507,84 @@ mod tests {
|
||||
|
||||
drop(client_auth);
|
||||
t_auth.join().unwrap();
|
||||
ingress.stop();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_direct_ingress_wildcard_port_rewrites_to_mapped_port_and_never_advertises_coa_8085() {
|
||||
let ext_wildcard_port = 48086;
|
||||
|
||||
let mock_auth = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let mock_auth_port = mock_auth.local_addr().unwrap().port();
|
||||
|
||||
let mock_world = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let mock_world_port = mock_world.local_addr().unwrap().port();
|
||||
|
||||
// DirectIngress configured for Wildcard (local_world = mock_world_port, ext_world = 48086)
|
||||
let mut ingress = DirectIngress::start(
|
||||
0,
|
||||
0,
|
||||
"198.51.100.1".to_string(),
|
||||
ext_wildcard_port,
|
||||
mock_auth_port,
|
||||
mock_world_port,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
// Verify Auth rewrite rewrites to external port 48086 and never mentions 8085 or 8086
|
||||
let t_auth = std::thread::spawn(move || {
|
||||
let (mut stream, _) = mock_auth.accept().unwrap();
|
||||
let mut buf = [0u8; 16];
|
||||
let _ = stream.read(&mut buf).unwrap();
|
||||
|
||||
let name_bytes = b"Wildcard\0";
|
||||
let addr_bytes = b"127.0.0.1:8086\0";
|
||||
let body_len = 4 + 2 + 3 + name_bytes.len() + addr_bytes.len() + 4 + 1 + 1 + 1 + 2;
|
||||
|
||||
let mut fake_realm_list = Vec::new();
|
||||
fake_realm_list.push(0x10); // Opcode
|
||||
fake_realm_list.extend_from_slice(&(body_len as u16).to_le_bytes()); // Length
|
||||
fake_realm_list.extend_from_slice(&0u32.to_le_bytes()); // Unused
|
||||
fake_realm_list.extend_from_slice(&1u16.to_le_bytes()); // Realm count = 1
|
||||
|
||||
// Realm info:
|
||||
fake_realm_list.extend_from_slice(&[1, 0, 0]); // type, lock, flag
|
||||
fake_realm_list.extend_from_slice(name_bytes);
|
||||
fake_realm_list.extend_from_slice(addr_bytes);
|
||||
fake_realm_list.extend_from_slice(&[0, 0, 0, 0]); // pop
|
||||
fake_realm_list.extend_from_slice(&[0]); // chars
|
||||
fake_realm_list.extend_from_slice(&[1]); // timezone
|
||||
fake_realm_list.extend_from_slice(&[1]); // realm id
|
||||
|
||||
// Footer:
|
||||
fake_realm_list.extend_from_slice(&[0x10, 0x00]);
|
||||
|
||||
stream.write_all(&fake_realm_list).unwrap();
|
||||
let _ = stream.shutdown(std::net::Shutdown::Write);
|
||||
});
|
||||
|
||||
let mut client_auth =
|
||||
TcpStream::connect(format!("127.0.0.1:{}", ingress.auth_port())).unwrap();
|
||||
client_auth.write_all(b"AUTH_HELLO").unwrap();
|
||||
let mut auth_buf = [0u8; 512];
|
||||
let an = client_auth.read(&mut auth_buf).unwrap();
|
||||
let payload = String::from_utf8_lossy(&auth_buf[..an]);
|
||||
|
||||
assert!(
|
||||
payload.contains("198.51.100.1:48086"),
|
||||
"Expected rewritten realm list to contain external port 48086, got: {payload}"
|
||||
);
|
||||
assert!(
|
||||
!payload.contains("8085"),
|
||||
"DirectIngress for Wildcard must never advertise CoA port 8085"
|
||||
);
|
||||
assert!(
|
||||
!payload.contains(":8086"),
|
||||
"DirectIngress for Wildcard must rewrite internal port 8086 to external 48086"
|
||||
);
|
||||
|
||||
drop(client_auth);
|
||||
t_auth.join().unwrap();
|
||||
ingress.stop();
|
||||
}
|
||||
}
|
||||
@@ -303,11 +303,40 @@ fn attempt_route_discovery(
|
||||
let local_auth = std::env::var("COA_OVERRIDE_LOCAL_AUTH_PORT")
|
||||
.ok()
|
||||
.and_then(|p| p.parse().ok())
|
||||
.unwrap_or(coa_control_proto::relay::LOCAL_AUTH_PORT);
|
||||
let local_world = std::env::var("COA_OVERRIDE_LOCAL_WORLD_PORT")
|
||||
.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;
|
||||
}
|
||||
};
|
||||
let local_world = match std::env::var("COA_OVERRIDE_LOCAL_WORLD_PORT")
|
||||
.ok()
|
||||
.and_then(|p| p.parse().ok())
|
||||
.unwrap_or(coa_control_proto::relay::LOCAL_WORLD_PORT);
|
||||
{
|
||||
Some(p) => p,
|
||||
None => match service.local_world_port() {
|
||||
Ok(p) => p,
|
||||
Err(e) => {
|
||||
set_status(
|
||||
status,
|
||||
RouteStatus::RelayOnly {
|
||||
reason: format!("Cannot resolve local world port: {e}"),
|
||||
},
|
||||
);
|
||||
service.set_direct_route(None);
|
||||
return;
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
let desired_auth_port: u16 = std::env::var("COA_DIRECT_AUTH_PORT")
|
||||
.ok()
|
||||
@@ -316,7 +345,7 @@ fn attempt_route_discovery(
|
||||
let desired_world_port: u16 = std::env::var("COA_DIRECT_WORLD_PORT")
|
||||
.ok()
|
||||
.and_then(|p| p.parse().ok())
|
||||
.unwrap_or(8085);
|
||||
.unwrap_or(local_world);
|
||||
|
||||
let ingress = match DirectIngress::start(
|
||||
desired_auth_port,
|
||||
|
||||
@@ -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 { nonce, .. } => nonce,
|
||||
Frame::Challenge { protocol, nonce } if protocol == coord::COORDINATOR_PROTOCOL_VERSION => nonce,
|
||||
_ => return Err(LinkError::Protocol("a challenge was expected".into())),
|
||||
};
|
||||
transport::send_text(
|
||||
|
||||
@@ -24,6 +24,7 @@ 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 {
|
||||
@@ -35,6 +36,7 @@ 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>>,
|
||||
@@ -83,7 +85,7 @@ impl HostControl {
|
||||
running.retain(|id, r| {
|
||||
wanted
|
||||
.get(id)
|
||||
.is_some_and(|(realm, url, _, _)| *realm == r.realm_id && *url == r.url)
|
||||
.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)
|
||||
});
|
||||
for (local_id, (realm_id, url, base, key)) in wanted {
|
||||
if running.contains_key(&local_id) {
|
||||
@@ -95,18 +97,29 @@ impl HostControl {
|
||||
store.clone(),
|
||||
backend.clone(),
|
||||
));
|
||||
let relay_link =
|
||||
crate::control::transport::relay_url(&base, "/relay/v1/host").map(
|
||||
|r_url| {
|
||||
let rl = crate::control::relay_link::RelayLink::start(
|
||||
r_url,
|
||||
realm_id,
|
||||
key.clone(),
|
||||
);
|
||||
service.set_relay(rl.clone());
|
||||
rl
|
||||
},
|
||||
);
|
||||
let ports = service.local_auth_port().ok().zip(service.local_world_port().ok());
|
||||
let relay_link = match ports {
|
||||
Some((auth_port, 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(
|
||||
r_url,
|
||||
realm_id,
|
||||
key.clone(),
|
||||
auth_port,
|
||||
Some(world_port),
|
||||
);
|
||||
service.set_relay(rl.clone());
|
||||
rl
|
||||
},
|
||||
)
|
||||
}
|
||||
None => {
|
||||
tracing::warn!(%local_id, "relay is waiting for valid local auth and world ports");
|
||||
None
|
||||
}
|
||||
};
|
||||
let direct_route =
|
||||
Some(crate::control::direct_route::DirectRouteManager::start(
|
||||
Some(base.clone()),
|
||||
@@ -119,6 +132,7 @@ impl HostControl {
|
||||
Running {
|
||||
realm_id,
|
||||
url,
|
||||
ports,
|
||||
link,
|
||||
relay_link,
|
||||
direct_route,
|
||||
@@ -135,6 +149,7 @@ 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()),
|
||||
},
|
||||
)
|
||||
})
|
||||
|
||||
@@ -20,6 +20,8 @@ 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 {
|
||||
@@ -115,6 +117,7 @@ pub struct AccountOutcome {
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Claimed {
|
||||
pub character_id: Uuid,
|
||||
pub ruleset: String,
|
||||
pub payload: Vec<u8>,
|
||||
pub sha256: [u8; 32],
|
||||
pub collections: BTreeMap<String, Vec<u32>>,
|
||||
@@ -347,13 +350,14 @@ impl PlayerControl {
|
||||
|
||||
pub fn claim(&self, ch: &mut PlayerChannel, token: u32) -> R<Claimed> {
|
||||
let r = ch.request(&Request::Claim { token })?;
|
||||
let (character_id, sha256, payload, collections) = expect(r, |r| match r {
|
||||
let (character_id, ruleset, sha256, payload, collections) = expect(r, |r| match r {
|
||||
Response::Claimed {
|
||||
character_id,
|
||||
ruleset,
|
||||
sha256,
|
||||
payload,
|
||||
collections,
|
||||
} => Ok((character_id, sha256, payload, collections)),
|
||||
} => Ok((character_id, ruleset, sha256, payload, collections)),
|
||||
other => Err(other),
|
||||
})?;
|
||||
let payload = base64::engine::general_purpose::STANDARD
|
||||
@@ -373,6 +377,7 @@ impl PlayerControl {
|
||||
})?;
|
||||
Ok(Claimed {
|
||||
character_id,
|
||||
ruleset,
|
||||
payload,
|
||||
sha256: hash,
|
||||
collections,
|
||||
@@ -409,24 +414,39 @@ impl PlayerControl {
|
||||
}
|
||||
|
||||
/// Transfer a portable character to a remote realm over the verified control channel (Phase 12.1).
|
||||
pub fn transfer_character(
|
||||
fn transfer_with_id(
|
||||
&self,
|
||||
ch: &mut PlayerChannel,
|
||||
transfer_id: Uuid,
|
||||
owned_session: bool,
|
||||
character_id: Uuid,
|
||||
ruleset: &str,
|
||||
canonical_revision: u64,
|
||||
payload: &[u8],
|
||||
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 = Request::TransferOffer {
|
||||
transfer_id,
|
||||
character_id,
|
||||
canonical_revision,
|
||||
content_hash: content_hash_str.clone(),
|
||||
total_size: payload.len(),
|
||||
collections,
|
||||
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 r = ch.request(&offer)?;
|
||||
let mut offset = match r {
|
||||
@@ -451,7 +471,21 @@ impl PlayerControl {
|
||||
notes,
|
||||
});
|
||||
}
|
||||
Response::Error { code, message } => return Err(ControlFail::App { code, message }),
|
||||
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 });
|
||||
}
|
||||
_ => {
|
||||
return Err(ControlFail::Link(LinkError::Protocol(
|
||||
"unexpected response to transfer offer".into(),
|
||||
|
||||
@@ -0,0 +1,290 @@
|
||||
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));
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,9 @@ 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,
|
||||
@@ -35,7 +38,11 @@ impl PlayerChannel {
|
||||
Duration::from_millis(500),
|
||||
)?;
|
||||
let nonce = match transport::next_frame(&mut ws, STEP)? {
|
||||
Frame::Challenge { nonce, .. } => nonce,
|
||||
Frame::Challenge { protocol, nonce }
|
||||
if protocol == coord::COORDINATOR_PROTOCOL_VERSION =>
|
||||
{
|
||||
nonce
|
||||
}
|
||||
_ => return Err(LinkError::Protocol("a challenge was expected".into())),
|
||||
};
|
||||
transport::send_text(
|
||||
@@ -67,7 +74,14 @@ impl PlayerChannel {
|
||||
{
|
||||
transport::send_binary(&mut ws, f)?;
|
||||
}
|
||||
Ok(PlayerChannel { ws, channel, conn })
|
||||
Ok(PlayerChannel {
|
||||
ws,
|
||||
channel,
|
||||
conn,
|
||||
realm_id: *realm,
|
||||
realm_key: *realm_key,
|
||||
coordinator: coordinator.into(),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn connection(&self) -> u32 {
|
||||
|
||||
@@ -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 strictly to 127.0.0.1:3724 (Auth) and 127.0.0.1:8085 (World).
|
||||
//! opening local TCP connections only to the installed realm's configured loopback Auth and World ports.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::io::{Read, Write};
|
||||
@@ -71,6 +71,31 @@ impl RelayProvider for RelayLink {
|
||||
|
||||
impl RelayLink {
|
||||
pub fn start(url: String, realm_id: RealmId, key: SigningKey) -> Arc<Self> {
|
||||
Self::start_with_ports(url, realm_id, key, None)
|
||||
}
|
||||
|
||||
pub fn start_with_ports(
|
||||
url: String,
|
||||
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()));
|
||||
let (alloc_tx, alloc_rx) = channel();
|
||||
@@ -79,7 +104,18 @@ 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))
|
||||
.spawn(move || {
|
||||
run(
|
||||
&url,
|
||||
realm_id,
|
||||
&key,
|
||||
alloc_rx,
|
||||
&s,
|
||||
&st,
|
||||
local_auth_port,
|
||||
local_world_port,
|
||||
)
|
||||
})
|
||||
.ok();
|
||||
|
||||
Arc::new(RelayLink {
|
||||
@@ -127,11 +163,25 @@ 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);
|
||||
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");
|
||||
}
|
||||
set_status(status, |s| {
|
||||
s.connected = false;
|
||||
s.active_streams = 0;
|
||||
@@ -163,6 +213,15 @@ 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(
|
||||
@@ -176,6 +235,8 @@ 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)?;
|
||||
|
||||
@@ -243,6 +304,7 @@ 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
|
||||
@@ -263,10 +325,14 @@ fn session(
|
||||
}
|
||||
|
||||
// Keepalive
|
||||
if last_pong.elapsed() > Duration::from_secs(90) {
|
||||
return Err(LinkError::Timeout);
|
||||
}
|
||||
if last_ping.elapsed() > Duration::from_secs(30) {
|
||||
let _ = ws.send(Message::Text(
|
||||
ws.send(Message::Text(
|
||||
serde_json::to_string(&TunnelMsg::Ping).unwrap().into(),
|
||||
));
|
||||
))
|
||||
.map_err(|error| LinkError::Io(error.to_string()))?;
|
||||
last_ping = Instant::now();
|
||||
}
|
||||
|
||||
@@ -305,8 +371,21 @@ fn session(
|
||||
TunnelMsg::Connect {
|
||||
stream_id, target, ..
|
||||
} => {
|
||||
// Strictly predefined local targets: Auth (3724) or World (8085)
|
||||
let local_port = target.local_port();
|
||||
// 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::World => match local_world_port {
|
||||
Some(p) => p,
|
||||
None => {
|
||||
eprintln!("RelayLink cannot connect to World: local_world_port was not provided (fail-closed)");
|
||||
let _ = ws_out_tx.send(TunnelMsg::ConnectErr {
|
||||
stream_id,
|
||||
error: "World port unresolved".into(),
|
||||
});
|
||||
continue;
|
||||
}
|
||||
},
|
||||
};
|
||||
match TcpStream::connect(("127.0.0.1", local_port)) {
|
||||
Ok(tcp) => {
|
||||
let (stream_tx, stream_rx) = channel::<TunnelMsg>();
|
||||
@@ -314,7 +393,13 @@ 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 });
|
||||
streams.insert(
|
||||
stream_id,
|
||||
StreamWorker {
|
||||
tx: stream_tx,
|
||||
reset_on_drop: true,
|
||||
},
|
||||
);
|
||||
|
||||
// Reply ConnectOk
|
||||
let ok_msg = TunnelMsg::ConnectOk { stream_id };
|
||||
@@ -340,7 +425,8 @@ fn session(
|
||||
}
|
||||
}
|
||||
TunnelMsg::Close { stream_id } => {
|
||||
if let Some(w) = streams.remove(&stream_id) {
|
||||
if let Some(mut w) = streams.remove(&stream_id) {
|
||||
w.reset_on_drop = false;
|
||||
let _ = w.tx.send(TunnelMsg::Close { stream_id });
|
||||
}
|
||||
set_status(status, |s| s.active_streams = streams.len());
|
||||
@@ -351,7 +437,9 @@ fn session(
|
||||
}
|
||||
set_status(status, |s| s.active_streams = streams.len());
|
||||
}
|
||||
TunnelMsg::Pong => {}
|
||||
TunnelMsg::Pong => {
|
||||
last_pong = Instant::now();
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
@@ -433,3 +521,109 @@ 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:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -20,12 +20,27 @@ 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.
|
||||
pub automatic: bool,
|
||||
/// An address a player's game client can reach right now, when the owner has stated one. Not a relay and not discovery.
|
||||
pub route: Option<String>,
|
||||
pub ruleset: crate::portable::model::Ruleset,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
@@ -55,6 +70,7 @@ pub struct CharInfo {
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct ClaimExport {
|
||||
pub character_id: Uuid,
|
||||
pub ruleset: crate::portable::Ruleset,
|
||||
pub payload: Vec<u8>,
|
||||
pub sha256: [u8; 32],
|
||||
pub collections: BTreeMap<String, Vec<u32>>,
|
||||
@@ -62,6 +78,7 @@ pub struct ClaimExport {
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct RemoteImportParams {
|
||||
pub session_id: Uuid,
|
||||
pub character_id: Uuid,
|
||||
pub revision: u64,
|
||||
pub payload: Vec<u8>,
|
||||
@@ -87,6 +104,30 @@ 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>>;
|
||||
@@ -118,6 +159,11 @@ pub trait RealmBackend: Send + Sync {
|
||||
local_id: &str,
|
||||
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>;
|
||||
}
|
||||
|
||||
/// State of one channel.
|
||||
@@ -144,7 +190,7 @@ impl Session {
|
||||
}
|
||||
|
||||
const MAX_REQUESTS_PER_SESSION: u32 = 60;
|
||||
const MAX_TRANSFER_CHUNKS_PER_SESSION: u32 = 128;
|
||||
const MAX_TRANSFER_CHUNKS_PER_SESSION: u32 = 2048;
|
||||
const LINK_FAILURES: usize = 5;
|
||||
const LINK_WINDOW: Duration = Duration::from_secs(600);
|
||||
|
||||
@@ -177,6 +223,8 @@ 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.",
|
||||
@@ -218,6 +266,14 @@ 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)
|
||||
}
|
||||
|
||||
/// The player's public key is the one recorded for this player id when there is a record; `None` when the player is new here.
|
||||
pub fn key_matches(&self, player: &Uuid, public_key: &str) -> bool {
|
||||
match self
|
||||
@@ -238,7 +294,12 @@ impl HostService {
|
||||
public_key: &str,
|
||||
request: Request,
|
||||
) -> Response {
|
||||
if matches!(request, Request::TransferChunk { .. }) {
|
||||
if matches!(
|
||||
request,
|
||||
Request::TransferChunk { .. }
|
||||
| Request::SessionRead { .. }
|
||||
| Request::SessionAck { .. }
|
||||
) {
|
||||
session.transfer_chunks += 1;
|
||||
if session.transfer_chunks > MAX_TRANSFER_CHUNKS_PER_SESSION {
|
||||
return err(
|
||||
@@ -303,6 +364,7 @@ impl HostService {
|
||||
Request::TransferOffer {
|
||||
transfer_id,
|
||||
character_id,
|
||||
ruleset,
|
||||
canonical_revision,
|
||||
content_hash,
|
||||
total_size,
|
||||
@@ -311,10 +373,31 @@ impl HostService {
|
||||
player,
|
||||
transfer_id,
|
||||
character_id,
|
||||
ruleset,
|
||||
canonical_revision,
|
||||
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,
|
||||
@@ -327,6 +410,32 @@ 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)
|
||||
}
|
||||
@@ -691,6 +800,7 @@ impl HostService {
|
||||
use base64::Engine;
|
||||
Response::Claimed {
|
||||
character_id: exported.character_id,
|
||||
ruleset: exported.ruleset.as_str().to_string(),
|
||||
sha256: hex::encode(exported.sha256),
|
||||
payload: base64::engine::general_purpose::STANDARD.encode(&exported.payload),
|
||||
collections: exported.collections,
|
||||
@@ -726,10 +836,12 @@ impl HostService {
|
||||
player: &Uuid,
|
||||
transfer_id: Uuid,
|
||||
character_id: Uuid,
|
||||
ruleset: String,
|
||||
canonical_revision: u64,
|
||||
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.");
|
||||
@@ -741,6 +853,30 @@ impl HostService {
|
||||
);
|
||||
};
|
||||
|
||||
// 0. Strict ruleset isolation: target realm ruleset must match offer ruleset
|
||||
let info = match self.backend.info(&self.local_id) {
|
||||
Ok(i) => i,
|
||||
Err(e) => return unavailable("reading realm info", &e),
|
||||
};
|
||||
let offer_ruleset = match crate::portable::model::Ruleset::parse(&ruleset) {
|
||||
Ok(r) => r,
|
||||
Err(_) => return err(AppError::Incompatible, "Invalid ruleset in transfer offer."),
|
||||
};
|
||||
if offer_ruleset != info.ruleset {
|
||||
return err(
|
||||
AppError::Incompatible,
|
||||
"Character ruleset does not match this realm.",
|
||||
);
|
||||
}
|
||||
for kind in collections.keys() {
|
||||
if !crate::portable::session::protocol::carried_kind_for(kind, offer_ruleset) {
|
||||
return err(
|
||||
AppError::Incompatible,
|
||||
"Collection kind does not belong to this ruleset.",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// 1. Ownership check: another player cannot overwrite a character claimed here
|
||||
if let Ok(Some(claim)) = self
|
||||
.store
|
||||
@@ -756,6 +892,41 @@ 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 => {
|
||||
@@ -783,30 +954,6 @@ 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
|
||||
@@ -834,6 +981,7 @@ impl HostService {
|
||||
realm_local_id: self.local_id.clone(),
|
||||
transfer_id,
|
||||
character_id,
|
||||
ruleset: offer_ruleset.as_str().to_string(),
|
||||
player_id: *player,
|
||||
revision: canonical_revision,
|
||||
content_hash,
|
||||
@@ -1008,23 +1156,61 @@ impl HostService {
|
||||
Err(e) => return unavailable("reading transfer file", &Error::Invalid(e.to_string())),
|
||||
};
|
||||
|
||||
use sha2::{Digest, Sha256};
|
||||
let hash = hex::encode(Sha256::digest(&payload));
|
||||
if hash != t.content_hash {
|
||||
let _ = std::fs::remove_file(&path);
|
||||
return err(AppError::Invalid, "Content hash mismatch.");
|
||||
}
|
||||
|
||||
let mut hash_bytes = [0u8; 32];
|
||||
if hex::decode_to_slice(&t.content_hash, &mut hash_bytes).is_err() {
|
||||
let _ = std::fs::remove_file(&path);
|
||||
return err(AppError::Invalid, "Invalid content hash format.");
|
||||
}
|
||||
|
||||
let decoded = match crate::portable::snapshot::decode(&payload, Some(&hash_bytes)) {
|
||||
Ok(d) => d,
|
||||
Err(e) => {
|
||||
let _ = std::fs::remove_file(&path);
|
||||
return err(AppError::Invalid, &format!("Corrupt snapshot: {e}"));
|
||||
}
|
||||
};
|
||||
let transfer_ruleset: crate::portable::Ruleset = match t.ruleset.parse() {
|
||||
Ok(r) => r,
|
||||
Err(_) => {
|
||||
let _ = std::fs::remove_file(&path);
|
||||
return err(AppError::Incompatible, "Invalid transfer ruleset.");
|
||||
}
|
||||
};
|
||||
if decoded.character_id.as_uuid() != t.character_id {
|
||||
let _ = std::fs::remove_file(&path);
|
||||
return err(
|
||||
AppError::Invalid,
|
||||
"Snapshot character id does not match TransferOffer.",
|
||||
);
|
||||
}
|
||||
if decoded.ruleset != transfer_ruleset {
|
||||
let _ = std::fs::remove_file(&path);
|
||||
return err(
|
||||
AppError::Incompatible,
|
||||
"Snapshot ruleset does not match TransferOffer.",
|
||||
);
|
||||
}
|
||||
let info = match self.backend.info(&self.local_id) {
|
||||
Ok(i) => i,
|
||||
Err(e) => {
|
||||
let _ = std::fs::remove_file(&path);
|
||||
return unavailable("reading realm info", &e);
|
||||
}
|
||||
};
|
||||
if transfer_ruleset != info.ruleset {
|
||||
let _ = std::fs::remove_file(&path);
|
||||
return err(
|
||||
AppError::Incompatible,
|
||||
"Transfer ruleset does not match target realm ruleset.",
|
||||
);
|
||||
}
|
||||
|
||||
let Some(m) = self.mapping(player) else {
|
||||
return err(AppError::NoAccount, "Player has no account on this realm.");
|
||||
};
|
||||
|
||||
let params = RemoteImportParams {
|
||||
session_id: t.transfer_id,
|
||||
character_id: t.character_id,
|
||||
revision: t.revision,
|
||||
payload,
|
||||
@@ -1083,6 +1269,7 @@ impl HostService {
|
||||
#[cfg(any(test, feature = "testkit"))]
|
||||
pub mod fake {
|
||||
use super::*;
|
||||
use crate::portable::Ruleset;
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct FakeRealm {
|
||||
@@ -1095,6 +1282,7 @@ pub mod fake {
|
||||
pub seen_passwords: Mutex<Vec<String>>,
|
||||
pub imported: Mutex<HashMap<Uuid, (u32, Uuid)>>,
|
||||
pub incompatible: Mutex<std::collections::HashSet<Uuid>>,
|
||||
pub world_port: Mutex<Option<Result<u16>>>,
|
||||
}
|
||||
|
||||
impl FakeRealm {
|
||||
@@ -1141,6 +1329,7 @@ pub mod fake {
|
||||
impl RealmBackend for FakeRealm {
|
||||
fn info(&self, _: &str) -> Result<RealmInfo> {
|
||||
Ok(RealmInfo {
|
||||
ruleset: Ruleset::Coa,
|
||||
automatic: *self.automatic.lock().unwrap(),
|
||||
route: self.route.lock().unwrap().clone(),
|
||||
})
|
||||
@@ -1245,6 +1434,7 @@ pub mod fake {
|
||||
.or_insert_with(Uuid::now_v7);
|
||||
Ok(ClaimExport {
|
||||
character_id: id,
|
||||
ruleset: crate::portable::Ruleset::Coa,
|
||||
payload: format!("payload-{guid}").into_bytes(),
|
||||
sha256: [7; 32],
|
||||
collections: BTreeMap::from([("coa:appearance".to_string(), vec![1, 2, 3])]),
|
||||
@@ -1284,6 +1474,16 @@ pub mod fake {
|
||||
notes: vec![],
|
||||
})
|
||||
}
|
||||
fn world_port(&self, _: &str) -> Result<u16> {
|
||||
if let Some(res) = self.world_port.lock().unwrap().as_ref() {
|
||||
match res {
|
||||
Ok(p) => Ok(*p),
|
||||
Err(e) => Err(Error::Invalid(e.to_string())),
|
||||
}
|
||||
} else {
|
||||
Ok(8085)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1424,7 +1624,7 @@ mod tests {
|
||||
&Uuid::now_v7(),
|
||||
"K",
|
||||
Request::Hello {
|
||||
protocol: 1,
|
||||
protocol: coa_control_proto::CONTROL_PROTOCOL_VERSION,
|
||||
client: "t".into(),
|
||||
},
|
||||
)
|
||||
@@ -1655,6 +1855,7 @@ mod tests {
|
||||
);
|
||||
let Response::Claimed {
|
||||
character_id,
|
||||
ruleset,
|
||||
sha256,
|
||||
payload,
|
||||
collections,
|
||||
@@ -1662,6 +1863,7 @@ mod tests {
|
||||
else {
|
||||
panic!()
|
||||
};
|
||||
assert_eq!(ruleset, "coa");
|
||||
assert_eq!(sha256, hex::encode([7u8; 32]));
|
||||
assert!(!payload.is_empty() && collections["coa:appearance"] == vec![1, 2, 3]);
|
||||
// asking again returns the same character
|
||||
@@ -1857,6 +2059,14 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
fn test_snapshot(cid: Uuid, ruleset: crate::portable::Ruleset) -> (Vec<u8>, String) {
|
||||
let mut model = crate::portable::fixtures::geared_level_eighty();
|
||||
model.character_id = crate::portable::CharacterId::from_uuid(cid).unwrap();
|
||||
model.ruleset = ruleset;
|
||||
let encoded = crate::portable::snapshot::encode(&model).unwrap();
|
||||
(encoded.payload, hex::encode(encoded.content_hash))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remote_transfer_lifecycle_empty_realm_import_and_ack() {
|
||||
let (realm, s, p, _acc) = claimed_setup();
|
||||
@@ -1864,12 +2074,11 @@ mod tests {
|
||||
let cid = Uuid::now_v7();
|
||||
let tid = Uuid::now_v7();
|
||||
|
||||
let payload = b"portable_character_snapshot_payload_test_data".to_vec();
|
||||
use sha2::{Digest, Sha256};
|
||||
let hash = hex::encode(Sha256::digest(&payload));
|
||||
let (payload, hash) = test_snapshot(cid, crate::portable::Ruleset::Coa);
|
||||
|
||||
// 1. Offer
|
||||
let offer = Request::TransferOffer {
|
||||
ruleset: "coa".into(),
|
||||
transfer_id: tid,
|
||||
character_id: cid,
|
||||
canonical_revision: 1,
|
||||
@@ -1943,6 +2152,7 @@ mod tests {
|
||||
realm.incompatible.lock().unwrap().insert(cid);
|
||||
|
||||
let offer = Request::TransferOffer {
|
||||
ruleset: "coa".into(),
|
||||
transfer_id: tid,
|
||||
character_id: cid,
|
||||
canonical_revision: 1,
|
||||
@@ -1973,15 +2183,12 @@ mod tests {
|
||||
let cid = Uuid::now_v7();
|
||||
let tid = Uuid::now_v7();
|
||||
|
||||
let chunk1 = b"first_chunk_of_payload_";
|
||||
let chunk2 = b"second_chunk_of_payload";
|
||||
let mut full = chunk1.to_vec();
|
||||
full.extend_from_slice(chunk2);
|
||||
|
||||
use sha2::{Digest, Sha256};
|
||||
let hash = hex::encode(Sha256::digest(&full));
|
||||
let (full, hash) = test_snapshot(cid, crate::portable::Ruleset::Coa);
|
||||
let mid = full.len() / 2;
|
||||
let (chunk1, chunk2) = full.split_at(mid);
|
||||
|
||||
let offer = Request::TransferOffer {
|
||||
ruleset: "coa".into(),
|
||||
transfer_id: tid,
|
||||
character_id: cid,
|
||||
canonical_revision: 1,
|
||||
@@ -2071,11 +2278,10 @@ mod tests {
|
||||
let cid = Uuid::now_v7();
|
||||
let tid = Uuid::now_v7();
|
||||
|
||||
let payload = b"idempotency_test_payload".to_vec();
|
||||
use sha2::{Digest, Sha256};
|
||||
let hash = hex::encode(Sha256::digest(&payload));
|
||||
let (payload, hash) = test_snapshot(cid, crate::portable::Ruleset::Coa);
|
||||
|
||||
let offer = Request::TransferOffer {
|
||||
ruleset: "coa".into(),
|
||||
transfer_id: tid,
|
||||
character_id: cid,
|
||||
canonical_revision: 1,
|
||||
@@ -2138,6 +2344,7 @@ mod tests {
|
||||
// Client starts a new transfer for the exact same committed revision: discovers committed state
|
||||
let tid2 = Uuid::now_v7();
|
||||
let offer2 = Request::TransferOffer {
|
||||
ruleset: "coa".into(),
|
||||
transfer_id: tid2,
|
||||
character_id: cid,
|
||||
canonical_revision: 1,
|
||||
@@ -2163,17 +2370,92 @@ 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();
|
||||
let cid = Uuid::now_v7();
|
||||
let tid = Uuid::now_v7();
|
||||
|
||||
let payload = b"player_1_character_data".to_vec();
|
||||
use sha2::{Digest, Sha256};
|
||||
let hash = hex::encode(Sha256::digest(&payload));
|
||||
let (payload, hash) = test_snapshot(cid, crate::portable::Ruleset::Coa);
|
||||
|
||||
let offer = Request::TransferOffer {
|
||||
ruleset: "coa".into(),
|
||||
transfer_id: tid,
|
||||
character_id: cid,
|
||||
canonical_revision: 1,
|
||||
@@ -2240,6 +2522,7 @@ mod tests {
|
||||
|
||||
let tid_impostor = Uuid::now_v7();
|
||||
let impostor_offer = Request::TransferOffer {
|
||||
ruleset: "coa".into(),
|
||||
transfer_id: tid_impostor,
|
||||
character_id: cid,
|
||||
canonical_revision: 2,
|
||||
@@ -2267,9 +2550,7 @@ mod tests {
|
||||
let cid = Uuid::now_v7();
|
||||
let tid1 = Uuid::now_v7();
|
||||
|
||||
let payload1 = b"character_revision_1_data".to_vec();
|
||||
use sha2::{Digest, Sha256};
|
||||
let hash1 = hex::encode(Sha256::digest(&payload1));
|
||||
let (payload1, hash1) = test_snapshot(cid, crate::portable::Ruleset::Coa);
|
||||
|
||||
// Rev 1
|
||||
s.handle(
|
||||
@@ -2277,6 +2558,7 @@ mod tests {
|
||||
&p,
|
||||
"K",
|
||||
Request::TransferOffer {
|
||||
ruleset: "coa".into(),
|
||||
transfer_id: tid1,
|
||||
character_id: cid,
|
||||
canonical_revision: 1,
|
||||
@@ -2321,13 +2603,18 @@ mod tests {
|
||||
|
||||
// Rev 2
|
||||
let tid2 = Uuid::now_v7();
|
||||
let payload2 = b"character_revision_2_newer_data".to_vec();
|
||||
let hash2 = hex::encode(Sha256::digest(&payload2));
|
||||
let mut model2 = crate::portable::fixtures::geared_level_eighty();
|
||||
model2.character_id = crate::portable::CharacterId::from_uuid(cid).unwrap();
|
||||
model2.progression.money += 500;
|
||||
let enc2 = crate::portable::snapshot::encode(&model2).unwrap();
|
||||
let (payload2, hash2) = (enc2.payload, hex::encode(enc2.content_hash));
|
||||
|
||||
let r = s.handle(
|
||||
&mut session,
|
||||
&p,
|
||||
"K",
|
||||
Request::TransferOffer {
|
||||
ruleset: "coa".into(),
|
||||
transfer_id: tid2,
|
||||
character_id: cid,
|
||||
canonical_revision: 2,
|
||||
@@ -2377,4 +2664,190 @@ mod tests {
|
||||
"update, not duplicate import"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cross_ruleset_transfer_offers_are_rejected_before_mutation() {
|
||||
let (realm, s, p, _acc) = claimed_setup();
|
||||
let mut session = Session::default();
|
||||
let cid = Uuid::now_v7();
|
||||
let tid = Uuid::now_v7();
|
||||
|
||||
// 1. Host is CoA, offer is Wildcard -> Rejected
|
||||
let wc_offer = Request::TransferOffer {
|
||||
ruleset: "wildcard".into(),
|
||||
transfer_id: tid,
|
||||
character_id: cid,
|
||||
canonical_revision: 1,
|
||||
content_hash: "a".repeat(64),
|
||||
total_size: 100,
|
||||
collections: BTreeMap::new(),
|
||||
};
|
||||
let r = s.handle(&mut session, &p, "K", wc_offer);
|
||||
assert!(matches!(
|
||||
r,
|
||||
Response::Error {
|
||||
code: AppError::Incompatible,
|
||||
..
|
||||
}
|
||||
));
|
||||
|
||||
// 2. Host is CoA, offer is Reborn -> Rejected
|
||||
let rb_offer = Request::TransferOffer {
|
||||
ruleset: "reborn".into(),
|
||||
transfer_id: tid,
|
||||
character_id: cid,
|
||||
canonical_revision: 1,
|
||||
content_hash: "a".repeat(64),
|
||||
total_size: 100,
|
||||
collections: BTreeMap::new(),
|
||||
};
|
||||
let r = s.handle(&mut session, &p, "K", rb_offer);
|
||||
assert!(matches!(
|
||||
r,
|
||||
Response::Error {
|
||||
code: AppError::Incompatible,
|
||||
..
|
||||
}
|
||||
));
|
||||
|
||||
// 3. Collection kinds for another ruleset -> Rejected
|
||||
let foreign_coll_offer = Request::TransferOffer {
|
||||
ruleset: "coa".into(),
|
||||
transfer_id: tid,
|
||||
character_id: cid,
|
||||
canonical_revision: 1,
|
||||
content_hash: "a".repeat(64),
|
||||
total_size: 100,
|
||||
collections: BTreeMap::from([("wildcard:appearance".into(), vec![1, 2, 3])]),
|
||||
};
|
||||
let r = s.handle(&mut session, &p, "K", foreign_coll_offer);
|
||||
assert!(matches!(
|
||||
r,
|
||||
Response::Error {
|
||||
code: AppError::Incompatible,
|
||||
..
|
||||
}
|
||||
));
|
||||
|
||||
// Ensure 0 DB imports happened
|
||||
assert!(realm.imported.lock().unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tampered_payload_at_commit_aborts_with_zero_mutation() {
|
||||
let (realm, s, p, _acc) = claimed_setup();
|
||||
let mut session = Session::default();
|
||||
let cid = Uuid::now_v7();
|
||||
let tid = Uuid::now_v7();
|
||||
|
||||
// 1. Offer announces CoA
|
||||
let (payload_coa, hash_coa) = test_snapshot(cid, crate::portable::Ruleset::Coa);
|
||||
let offer = Request::TransferOffer {
|
||||
ruleset: "coa".into(),
|
||||
transfer_id: tid,
|
||||
character_id: cid,
|
||||
canonical_revision: 1,
|
||||
content_hash: hash_coa,
|
||||
total_size: payload_coa.len(),
|
||||
collections: BTreeMap::new(),
|
||||
};
|
||||
s.handle(&mut session, &p, "K", offer);
|
||||
|
||||
// Attacker creates a Wildcard snapshot with the same CID, but uploads it under the CoA offer
|
||||
let (payload_wc, hash_wc) = test_snapshot(cid, crate::portable::Ruleset::Wildcard);
|
||||
|
||||
// Uploading chunks of payload_wc will mismatch the offered hash
|
||||
use base64::Engine;
|
||||
let data = base64::engine::general_purpose::STANDARD.encode(&payload_wc);
|
||||
s.handle(
|
||||
&mut session,
|
||||
&p,
|
||||
"K",
|
||||
Request::TransferChunk {
|
||||
transfer_id: tid,
|
||||
offset: 0,
|
||||
data,
|
||||
},
|
||||
);
|
||||
let commit = Request::TransferCommit { transfer_id: tid };
|
||||
let r = s.handle(&mut session, &p, "K", commit);
|
||||
assert!(matches!(
|
||||
r,
|
||||
Response::Error {
|
||||
code: AppError::Invalid,
|
||||
..
|
||||
}
|
||||
));
|
||||
assert!(realm.imported.lock().unwrap().is_empty());
|
||||
|
||||
// 2. What if attacker offered hash_wc matching payload_wc, but offer.ruleset is "coa"?
|
||||
let tid2 = Uuid::now_v7();
|
||||
let offer2 = Request::TransferOffer {
|
||||
ruleset: "coa".into(),
|
||||
transfer_id: tid2,
|
||||
character_id: cid,
|
||||
canonical_revision: 1,
|
||||
content_hash: hash_wc,
|
||||
total_size: payload_wc.len(),
|
||||
collections: BTreeMap::new(),
|
||||
};
|
||||
s.handle(&mut session, &p, "K", offer2);
|
||||
let data2 = base64::engine::general_purpose::STANDARD.encode(&payload_wc);
|
||||
s.handle(
|
||||
&mut session,
|
||||
&p,
|
||||
"K",
|
||||
Request::TransferChunk {
|
||||
transfer_id: tid2,
|
||||
offset: 0,
|
||||
data: data2,
|
||||
},
|
||||
);
|
||||
let commit2 = Request::TransferCommit { transfer_id: tid2 };
|
||||
let r2 = s.handle(&mut session, &p, "K", commit2);
|
||||
assert!(matches!(
|
||||
r2,
|
||||
Response::Error {
|
||||
code: AppError::Incompatible,
|
||||
..
|
||||
}
|
||||
));
|
||||
assert!(realm.imported.lock().unwrap().is_empty());
|
||||
|
||||
// 3. What if snapshot contains a different character_id than offer?
|
||||
let tid3 = Uuid::now_v7();
|
||||
let other_cid = Uuid::now_v7();
|
||||
let (payload_other, hash_other) = test_snapshot(other_cid, crate::portable::Ruleset::Coa);
|
||||
let offer3 = Request::TransferOffer {
|
||||
ruleset: "coa".into(),
|
||||
transfer_id: tid3,
|
||||
character_id: cid, // offered cid
|
||||
canonical_revision: 1,
|
||||
content_hash: hash_other,
|
||||
total_size: payload_other.len(),
|
||||
collections: BTreeMap::new(),
|
||||
};
|
||||
s.handle(&mut session, &p, "K", offer3);
|
||||
let data3 = base64::engine::general_purpose::STANDARD.encode(&payload_other);
|
||||
s.handle(
|
||||
&mut session,
|
||||
&p,
|
||||
"K",
|
||||
Request::TransferChunk {
|
||||
transfer_id: tid3,
|
||||
offset: 0,
|
||||
data: data3,
|
||||
},
|
||||
);
|
||||
let commit3 = Request::TransferCommit { transfer_id: tid3 };
|
||||
let r3 = s.handle(&mut session, &p, "K", commit3);
|
||||
assert!(matches!(
|
||||
r3,
|
||||
Response::Error {
|
||||
code: AppError::Invalid,
|
||||
..
|
||||
}
|
||||
));
|
||||
assert!(realm.imported.lock().unwrap().is_empty());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
//! 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),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -56,6 +56,7 @@ CREATE TABLE IF NOT EXISTS host_transfer(
|
||||
realm_local_id TEXT NOT NULL,
|
||||
transfer_id TEXT NOT NULL PRIMARY KEY,
|
||||
character_id TEXT NOT NULL,
|
||||
ruleset TEXT NOT NULL DEFAULT 'coa',
|
||||
player_id TEXT NOT NULL,
|
||||
revision INTEGER NOT NULL,
|
||||
content_hash TEXT NOT NULL,
|
||||
@@ -71,6 +72,13 @@ 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 {
|
||||
@@ -155,6 +163,7 @@ pub struct HostTransfer {
|
||||
pub realm_local_id: String,
|
||||
pub transfer_id: Uuid,
|
||||
pub character_id: Uuid,
|
||||
pub ruleset: String,
|
||||
pub player_id: Uuid,
|
||||
pub revision: u64,
|
||||
pub content_hash: String,
|
||||
@@ -175,6 +184,15 @@ 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,
|
||||
}
|
||||
@@ -184,6 +202,66 @@ 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)?;
|
||||
@@ -199,6 +277,10 @@ impl ControlStore {
|
||||
.map_err(db)?;
|
||||
let _ = conn.pragma_update(None, "journal_mode", "WAL");
|
||||
conn.execute_batch(SCHEMA).map_err(db)?;
|
||||
let _ = conn.execute(
|
||||
"ALTER TABLE host_transfer ADD COLUMN ruleset TEXT NOT NULL DEFAULT 'coa'",
|
||||
[],
|
||||
);
|
||||
Ok(Self { conn })
|
||||
}
|
||||
|
||||
@@ -307,7 +389,7 @@ impl ControlStore {
|
||||
pub fn host_transfer(&self, realm: &str, transfer_id: &Uuid) -> Result<Option<HostTransfer>> {
|
||||
self.conn
|
||||
.query_row(
|
||||
"SELECT realm_local_id, transfer_id, character_id, player_id, revision, content_hash, total_size, received_size, state, local_guid, session_id, projected_level, notes, collections FROM host_transfer WHERE realm_local_id = ?1 AND transfer_id = ?2",
|
||||
"SELECT realm_local_id, transfer_id, character_id, player_id, revision, content_hash, total_size, received_size, state, local_guid, session_id, projected_level, notes, collections, ruleset FROM host_transfer WHERE realm_local_id = ?1 AND transfer_id = ?2",
|
||||
params![realm, transfer_id.to_string()],
|
||||
row_transfer,
|
||||
)
|
||||
@@ -323,7 +405,7 @@ impl ControlStore {
|
||||
) -> Result<Option<HostTransfer>> {
|
||||
self.conn
|
||||
.query_row(
|
||||
"SELECT realm_local_id, transfer_id, character_id, player_id, revision, content_hash, total_size, received_size, state, local_guid, session_id, projected_level, notes, collections FROM host_transfer WHERE realm_local_id = ?1 AND character_id = ?2 ORDER BY updated_at DESC LIMIT 1",
|
||||
"SELECT realm_local_id, transfer_id, character_id, player_id, revision, content_hash, total_size, received_size, state, local_guid, session_id, projected_level, notes, collections, ruleset FROM host_transfer WHERE realm_local_id = ?1 AND character_id = ?2 ORDER BY updated_at DESC LIMIT 1",
|
||||
params![realm, character_id.to_string()],
|
||||
row_transfer,
|
||||
)
|
||||
@@ -337,8 +419,8 @@ impl ControlStore {
|
||||
let coll_json = serde_json::to_string(&t.collections).unwrap_or_default();
|
||||
self.conn
|
||||
.execute(
|
||||
"INSERT INTO host_transfer(realm_local_id, transfer_id, character_id, player_id, revision, content_hash, total_size, received_size, state, local_guid, session_id, projected_level, notes, collections, created_at, updated_at)
|
||||
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16)
|
||||
"INSERT INTO host_transfer(realm_local_id, transfer_id, character_id, ruleset, player_id, revision, content_hash, total_size, received_size, state, local_guid, session_id, projected_level, notes, collections, created_at, updated_at)
|
||||
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16, ?17)
|
||||
ON CONFLICT(transfer_id) DO UPDATE SET
|
||||
received_size = excluded.received_size,
|
||||
state = excluded.state,
|
||||
@@ -347,11 +429,13 @@ impl ControlStore {
|
||||
projected_level = excluded.projected_level,
|
||||
notes = excluded.notes,
|
||||
collections = excluded.collections,
|
||||
ruleset = excluded.ruleset,
|
||||
updated_at = excluded.updated_at",
|
||||
params![
|
||||
t.realm_local_id,
|
||||
t.transfer_id.to_string(),
|
||||
t.character_id.to_string(),
|
||||
t.ruleset,
|
||||
t.player_id.to_string(),
|
||||
t.revision as i64,
|
||||
t.content_hash,
|
||||
@@ -540,11 +624,13 @@ fn row_transfer(r: &rusqlite::Row<'_>) -> rusqlite::Result<Result<HostTransfer>>
|
||||
let collections = coll_str
|
||||
.and_then(|s| serde_json::from_str::<BTreeMap<String, Vec<u32>>>(&s).ok())
|
||||
.unwrap_or_default();
|
||||
let ruleset: String = r.get(14).unwrap_or_else(|_| "coa".to_string());
|
||||
Ok((|| {
|
||||
Ok(HostTransfer {
|
||||
realm_local_id,
|
||||
transfer_id: uuid(tid)?,
|
||||
character_id: uuid(cid)?,
|
||||
ruleset,
|
||||
player_id: uuid(pid)?,
|
||||
revision: revision as u64,
|
||||
content_hash,
|
||||
@@ -564,6 +650,43 @@ 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();
|
||||
@@ -677,6 +800,7 @@ mod tests {
|
||||
realm_local_id: "live".into(),
|
||||
transfer_id: t,
|
||||
character_id: c,
|
||||
ruleset: "coa".into(),
|
||||
player_id: p,
|
||||
revision: 3,
|
||||
content_hash: "a".repeat(64),
|
||||
|
||||
@@ -14,12 +14,14 @@ use crate::download::Cancel;
|
||||
use crate::error::{Error, Result};
|
||||
use crate::fsx;
|
||||
|
||||
pub const CLIENT_VERSION: &str = "1.8.3";
|
||||
pub const CLIENT_VERSION: &str = "1.9.2";
|
||||
pub const MANIFEST_FILENAME: &str = "custom_races_patch_manifest.txt";
|
||||
pub const ARCHIVES: &[(&str, &str)] = &[
|
||||
("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"),
|
||||
("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"),
|
||||
];
|
||||
|
||||
pub const RACE_MPQS: &[&str] = &[
|
||||
@@ -53,9 +55,15 @@ 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",
|
||||
@@ -186,6 +194,10 @@ 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")
|
||||
};
|
||||
@@ -200,16 +212,10 @@ 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 if let Some(name) = line.strip_prefix("ADDON:") {
|
||||
Some(format!("Interface/AddOns/{name}"))
|
||||
} else {
|
||||
None
|
||||
line.strip_prefix("ADDON:")
|
||||
.map(|name| format!("Interface/AddOns/{name}"))
|
||||
};
|
||||
if let Some(path) = path {
|
||||
fsx::safe_join(client, &path)?;
|
||||
@@ -331,6 +337,26 @@ struct PatchTransaction<'a> {
|
||||
entries: Vec<SavedFile>,
|
||||
finished: bool,
|
||||
}
|
||||
|
||||
// A shared AddOns directory can resolve onto another volume. Publish a complete,
|
||||
// synced copy beside the destination before deleting the source, so the journal
|
||||
// always retains recoverable bytes even if copying or publishing fails.
|
||||
fn move_patch_file(source: &Path, target: &Path) -> io::Result<()> {
|
||||
match fs::rename(source, target) {
|
||||
Ok(()) => return Ok(()),
|
||||
Err(error) if error.kind() == io::ErrorKind::CrossesDevices => {}
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
let parent = target
|
||||
.parent()
|
||||
.ok_or_else(|| io::Error::other("Patch target has no parent"))?;
|
||||
let temporary = tempfile::NamedTempFile::new_in(parent)?;
|
||||
fs::copy(source, temporary.path())?;
|
||||
temporary.as_file().sync_all()?;
|
||||
temporary.persist(target).map_err(|error| error.error)?;
|
||||
fs::remove_file(source)
|
||||
}
|
||||
|
||||
impl<'a> PatchTransaction<'a> {
|
||||
fn new(root: &'a Path) -> Result<Self> {
|
||||
recover_patch_transaction(root)?;
|
||||
@@ -362,9 +388,10 @@ impl<'a> PatchTransaction<'a> {
|
||||
&self.entries,
|
||||
)?;
|
||||
if path.is_file() {
|
||||
fs::rename(
|
||||
move_patch_file(
|
||||
path,
|
||||
self.root
|
||||
&self
|
||||
.root
|
||||
.join(".coa-races-transaction")
|
||||
.join(index.to_string()),
|
||||
)?;
|
||||
@@ -401,8 +428,9 @@ impl<'a> PatchTransaction<'a> {
|
||||
&self.entries,
|
||||
)?;
|
||||
fs::create_dir_all(target.parent().unwrap())?;
|
||||
fs::rename(
|
||||
self.root
|
||||
move_patch_file(
|
||||
&self
|
||||
.root
|
||||
.join(".coa-races-transaction")
|
||||
.join(index.to_string()),
|
||||
target,
|
||||
@@ -442,7 +470,7 @@ fn recover_patch_transaction(root: &Path) -> Result<()> {
|
||||
if let Some(target) = &entry.moved_to {
|
||||
let target = fsx::safe_join(root, target)?;
|
||||
if !saved.is_file() && target.is_file() {
|
||||
fs::rename(target, &saved)?;
|
||||
move_patch_file(&target, &saved)?;
|
||||
}
|
||||
// Persist recovery progress before restoring the source, making retries safe.
|
||||
entries[index].moved_to = None;
|
||||
@@ -453,7 +481,7 @@ fn recover_patch_transaction(root: &Path) -> Result<()> {
|
||||
if path.is_file() {
|
||||
fs::remove_file(&path)?;
|
||||
}
|
||||
fs::rename(saved, path)?;
|
||||
move_patch_file(&saved, &path)?;
|
||||
} else if !entry.existed && path.is_file() {
|
||||
fs::remove_file(path)?;
|
||||
}
|
||||
@@ -603,16 +631,37 @@ 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.8.3-Client-1.zip" => {
|
||||
"CoA-Custom-1.9.2-Client-1.zip" => {
|
||||
"a9dd51ed2d90fb048d549602f40f5429d56e2df0df5606a38781b358fa369568"
|
||||
}
|
||||
"CoA-Custom-1.8.3-Client-2.zip" => {
|
||||
"CoA-Custom-1.9.2-Client-2.zip" => {
|
||||
"ab084a55509ccbcc2977a06dd0c01fa879973a1892baaacaeb3ff52f3dfc750e"
|
||||
}
|
||||
"CoA-Custom-1.8.3-Client-3.zip" => {
|
||||
"270c7b306624bf9e5c3fe577e3bd058601221df223dd9e449ff7c25de70b9461"
|
||||
"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"
|
||||
}
|
||||
_ => return Err(Error::Invalid("Unknown custom races archive.".into())),
|
||||
};
|
||||
@@ -846,22 +895,8 @@ pub fn install_client_patches(
|
||||
let mut out = File::create(&dest)?;
|
||||
io::copy(&mut zfile, &mut out)?;
|
||||
installed_roots.push(relative);
|
||||
} 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);
|
||||
}
|
||||
} else if let Some(relative) = zname_norm.split("files/client_root/").nth(1) {
|
||||
installed_roots.push(stage_root_asset(staging.path(), relative, &mut zfile)?);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -971,12 +1006,137 @@ pub fn install_client_patches(
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[cfg(windows)]
|
||||
fn exercise_linked_addons(shared: &Path) {
|
||||
let client = tempfile::tempdir().unwrap();
|
||||
let root = client.path();
|
||||
fs::create_dir(root.join("Interface")).unwrap();
|
||||
let link = root.join("Interface/AddOns");
|
||||
let output = std::process::Command::new("cmd")
|
||||
.args(["/C", "mklink", "/J"])
|
||||
.arg(link.to_string_lossy().replace('/', "\\"))
|
||||
.arg(shared.to_string_lossy().replace('/', "\\"))
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(output.status.success(), "{output:?}");
|
||||
let name = "Interface/AddOns/CoAHideArmor/CoAHideArmor.lua";
|
||||
let active = root.join(name);
|
||||
fs::create_dir_all(active.parent().unwrap()).unwrap();
|
||||
fs::write(shared.join("unrelated.lua"), b"user addon").unwrap();
|
||||
let staged = root.join("staged.lua");
|
||||
fs::write(&staged, b"custom").unwrap();
|
||||
let mut tx = PatchTransaction::new(root).unwrap();
|
||||
tx.copy(&staged, &active).unwrap();
|
||||
tx.finish().unwrap();
|
||||
record_files(root, &[name]);
|
||||
set_client_patch_enabled(root, false).unwrap();
|
||||
assert!(!active.exists());
|
||||
assert_eq!(fs::read(suffix(&active, "disabled")).unwrap(), b"custom");
|
||||
set_client_patch_enabled(root, true).unwrap();
|
||||
assert_eq!(fs::read(&active).unwrap(), b"custom");
|
||||
// Simulate process termination after a move, then recover twice.
|
||||
let mut tx = PatchTransaction::new(root).unwrap();
|
||||
tx.move_file(&active, &suffix(&active, "disabled")).unwrap();
|
||||
std::mem::forget(tx);
|
||||
recover_patch_transaction(root).unwrap();
|
||||
recover_patch_transaction(root).unwrap();
|
||||
assert_eq!(fs::read(&active).unwrap(), b"custom");
|
||||
assert!(!suffix(&active, "disabled").exists());
|
||||
// Replacement installation must preserve the old bytes on failure.
|
||||
{
|
||||
let mut tx = PatchTransaction::new(root).unwrap();
|
||||
fs::write(&staged, b"replacement").unwrap();
|
||||
tx.copy(&staged, &active).unwrap();
|
||||
}
|
||||
assert_eq!(fs::read(&active).unwrap(), b"custom");
|
||||
uninstall_client_patches(root).unwrap();
|
||||
assert!(!active.exists());
|
||||
assert_eq!(
|
||||
fs::read(shared.join("unrelated.lua")).unwrap(),
|
||||
b"user addon"
|
||||
);
|
||||
assert!(fs::symlink_metadata(&link)
|
||||
.unwrap()
|
||||
.file_type()
|
||||
.is_symlink());
|
||||
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() {
|
||||
let shared = tempfile::tempdir().unwrap();
|
||||
exercise_linked_addons(shared.path());
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(windows)]
|
||||
#[ignore = "Set COA_TEST_OTHER_VOLUME to a writable directory on another volume"]
|
||||
fn shared_addons_on_another_volume_supports_install_switch_and_rollback() {
|
||||
let base = std::env::var_os("COA_TEST_OTHER_VOLUME").expect("COA_TEST_OTHER_VOLUME");
|
||||
let shared = tempfile::tempdir_in(base).unwrap();
|
||||
exercise_linked_addons(shared.path());
|
||||
}
|
||||
|
||||
fn record_files(root: &Path, names: &[&str]) {
|
||||
let mut manifest = format!("# CoA Custom {CLIENT_VERSION}\n");
|
||||
for name in names {
|
||||
let (kind, base) = name
|
||||
.strip_prefix("Data/")
|
||||
.map_or(("ROOT", *name), |base| ("MPQ", base));
|
||||
let (kind, base) = if let Some(base) = name.strip_prefix("Interface/AddOns/") {
|
||||
("ADDON", base)
|
||||
} else {
|
||||
name.strip_prefix("Data/")
|
||||
.map_or(("ROOT", *name), |base| ("MPQ", base))
|
||||
};
|
||||
manifest.push_str(&format!(
|
||||
"{kind}:{base}\nSHA256:{}:{name}\n",
|
||||
fsx::sha256_file(&root.join(name)).unwrap()
|
||||
|
||||
@@ -1,5 +1,20 @@
|
||||
{
|
||||
"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",
|
||||
@@ -22,28 +37,48 @@
|
||||
"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-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": "e4ce9d8b363eb609d0d6d92627eb53454fa2e03e4dbc1795b3573a22b7d009c8",
|
||||
"Data/patch-ZZZD.MPQ": "ca893cf8129f6fd442a63f0697a8ddea88546e3ce71bde713be2cc832b892bc9",
|
||||
"Data/patch-ZZZE.MPQ": "2e245ee0fe3b913087eed399062fda5843d98b04afac38024f7c64ac3bf43e18",
|
||||
"Data/patch-ZZZF.MPQ": "40eac695cfcafb598b8376f3b9a61ecc037e4d445b87279cfe387a91edad32c3",
|
||||
"Data/patch-ZZZZ.MPQ": "860c990db3b4185fdc36e1a001d3ca3507a68253a4506793a115f86eb0892a15",
|
||||
"EsteriaAppearance.bin": "90d9cfaeaf6de10f014f1d1610ea10453ec9b240255759aea99513cac488a3ec",
|
||||
"EsteriaAppearance.dll": "196a82f24dd287653e2b2fc4d12bfc796f8ee3f6687ca8308905a5ab528a51a9",
|
||||
"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",
|
||||
@@ -51,18 +86,26 @@
|
||||
"EsteriaSaberonTextures.bin": "1ba9133a75dad291d98a068b2dcde01f31a897a1764cd7f3e2c316c288a8f605",
|
||||
"EsteriaSethrak.bin": "bd14857a8c11fdf8027128763293701586b2102f9a6539d33a727014789fd606",
|
||||
"EsteriaSethrakTextures.bin": "d2b2cf58087a391f00198008fe871edd400ddf28d54a3a05674df74c5198528a",
|
||||
"EsteriaSlime.bin": "491e942ceb6abda83c0249afebae7c9c43af3897b35e45fa33d6f9177ecbc177",
|
||||
"EsteriaSlimeTextures.bin": "837774377ca055e6a5c79c1a4cfd8151e7c1f7ce2c16990b00fd445281137433",
|
||||
"EsteriaTarasek.bin": "f718444d5ec36f7aff018883486ae1981151fe6e01f5b7781d68d74e9fadfa47",
|
||||
"EsteriaTarasekTextures.bin": "1ba9133a75dad291d98a068b2dcde01f31a897a1764cd7f3e2c316c288a8f605",
|
||||
"EsteriaThinHuman.bin": "75794d192ea0c228b3da7bf7d0bdff1119f79d3f9bfef6650cd5e1a2b5d106eb",
|
||||
"EsteriaThinHumanTextures.bin": "02aeb4c05893d06125b8b58fdb7c2a56fe3d66a7d094706a44b43cb503d1731e",
|
||||
"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/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",
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
{
|
||||
"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"
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
{
|
||||
"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"
|
||||
}
|
||||
+195
-19
@@ -5,9 +5,10 @@
|
||||
|
||||
use std::fmt;
|
||||
use std::fs::File;
|
||||
use std::io::{BufReader, BufWriter, Read, Write};
|
||||
use std::io::{BufReader, BufWriter, Read, Seek, SeekFrom, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Stdio};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use serde::Deserialize;
|
||||
|
||||
@@ -48,6 +49,7 @@ 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)]
|
||||
@@ -67,6 +69,42 @@ 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"),
|
||||
@@ -75,11 +113,23 @@ pub const SCHEMAS: [(&str, &str); 3] = [
|
||||
];
|
||||
|
||||
pub fn schema_of(kind: &str) -> Result<&'static str> {
|
||||
if kind == "playerbots" { return Ok("acore_playerbots"); }
|
||||
if let Some(kind) = kind.strip_prefix("wildcard-") { return crate::realms::Mode::Wildcard.schema(kind); }
|
||||
if let Some(kind) = kind.strip_prefix("reborn-") { return crate::realms::Mode::Reborn.schema(kind); }
|
||||
if let Some(kind) = kind.strip_prefix("coa-") { return crate::realms::Mode::Coa.schema(kind); }
|
||||
SCHEMAS.iter().find(|(k, _)| *k == kind).map(|(_, s)| *s).ok_or_else(|| Error::Invalid(format!("unknown database {kind}")))
|
||||
if kind == "playerbots" {
|
||||
return Ok("acore_playerbots");
|
||||
}
|
||||
if let Some(kind) = kind.strip_prefix("wildcard-") {
|
||||
return crate::realms::Mode::Wildcard.schema(kind);
|
||||
}
|
||||
if let Some(kind) = kind.strip_prefix("reborn-") {
|
||||
return crate::realms::Mode::Reborn.schema(kind);
|
||||
}
|
||||
if let Some(kind) = kind.strip_prefix("coa-") {
|
||||
return crate::realms::Mode::Coa.schema(kind);
|
||||
}
|
||||
SCHEMAS
|
||||
.iter()
|
||||
.find(|(k, _)| *k == kind)
|
||||
.map(|(_, s)| *s)
|
||||
.ok_or_else(|| Error::Invalid(format!("unknown database {kind}")))
|
||||
}
|
||||
|
||||
fn ident_ok(name: &str) -> bool {
|
||||
@@ -123,6 +173,7 @@ impl Db {
|
||||
password: Secret(password),
|
||||
realm: crate::realms::state(root)?.active,
|
||||
container: None,
|
||||
read_deadline: None,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -143,6 +194,7 @@ impl Db {
|
||||
password: Secret(password),
|
||||
realm: crate::realms::state(root)?.active,
|
||||
container: Some(container),
|
||||
read_deadline: None,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -162,6 +214,7 @@ impl Db {
|
||||
password: Secret(password.to_string()),
|
||||
realm,
|
||||
container: None,
|
||||
read_deadline: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -280,7 +333,13 @@ impl Db {
|
||||
pub fn ping(&self) -> bool {
|
||||
let mut c = self.command("mysqladmin.exe");
|
||||
c.arg("ping").arg("--connect-timeout=3");
|
||||
c.output().map(|o| o.status.success()).unwrap_or(false)
|
||||
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
|
||||
}
|
||||
|
||||
/// Run SQL text (statement(s) supplied on stdin) and return the raw output.
|
||||
@@ -291,6 +350,13 @@ 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
|
||||
@@ -357,9 +423,11 @@ impl Db {
|
||||
|
||||
pub fn recovery_objects(&self, schema: &str) -> Result<Vec<serde_json::Value>> {
|
||||
let schema = self.realm_schema(schema);
|
||||
if !ident_ok(schema) { return Err(Error::Invalid("bad schema name".into())); }
|
||||
if !ident_ok(schema) {
|
||||
return Err(Error::Invalid("bad schema name".into()));
|
||||
}
|
||||
let sql = format!("SELECT routine_type,HEX(routine_name) FROM information_schema.routines WHERE routine_schema='{schema}' UNION ALL SELECT 'TRIGGER',HEX(trigger_name) FROM information_schema.triggers WHERE trigger_schema='{schema}' UNION ALL SELECT 'VIEW',HEX(table_name) FROM information_schema.views WHERE table_schema='{schema}' ORDER BY 1,2;");
|
||||
parse_recovery_objects(&schema, &self.query(&sql)?)
|
||||
parse_recovery_objects(schema, &self.query(&sql)?)
|
||||
}
|
||||
|
||||
/// Consistent dump of one schema, zstd-compressed to `out`. Returns (compressed bytes, sha256 of the file).
|
||||
@@ -469,15 +537,23 @@ impl Db {
|
||||
}
|
||||
|
||||
fn parse_recovery_objects(schema: &str, text: &str) -> Result<Vec<serde_json::Value>> {
|
||||
text.lines().filter(|line| !line.is_empty()).map(|line| {
|
||||
let (kind, name) = line.split_once('\t').ok_or_else(|| Error::Invalid("unexpected database object reply".into()))?;
|
||||
if !matches!(kind, "PROCEDURE" | "FUNCTION" | "TRIGGER" | "VIEW") {
|
||||
return Err(Error::Invalid("unexpected database object type".into()));
|
||||
}
|
||||
let name = hex::decode(name).ok().and_then(|bytes| String::from_utf8(bytes).ok())
|
||||
.filter(|name| !name.is_empty()).ok_or_else(|| Error::Invalid("unexpected database object name".into()))?;
|
||||
Ok(serde_json::json!({ "database": schema, "kind": kind, "name": name }))
|
||||
}).collect()
|
||||
text.lines()
|
||||
.filter(|line| !line.is_empty())
|
||||
.map(|line| {
|
||||
let (kind, name) = line
|
||||
.split_once('\t')
|
||||
.ok_or_else(|| Error::Invalid("unexpected database object reply".into()))?;
|
||||
if !matches!(kind, "PROCEDURE" | "FUNCTION" | "TRIGGER" | "VIEW") {
|
||||
return Err(Error::Invalid("unexpected database object type".into()));
|
||||
}
|
||||
let name = hex::decode(name)
|
||||
.ok()
|
||||
.and_then(|bytes| String::from_utf8(bytes).ok())
|
||||
.filter(|name| !name.is_empty())
|
||||
.ok_or_else(|| Error::Invalid("unexpected database object name".into()))?;
|
||||
Ok(serde_json::json!({ "database": schema, "kind": kind, "name": name }))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Name of the service account the Manager uses for the server console (RA). Accounts are stored upper-case.
|
||||
@@ -582,12 +658,112 @@ 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;
|
||||
let sql = "SELECT * FROM `acore_characters`.characters WHERE name='acore_world'; -- acore_world\nSELECT * FROM acore_world.items; SELECT * FROM acore_world_wildcard.items;";
|
||||
assert_eq!(super::route_sql(sql, Mode::Reborn), "SELECT * FROM `acore_characters_reborn`.characters WHERE name='acore_world'; -- acore_world\nSELECT * FROM acore_world_reborn.items; SELECT * FROM acore_world_wildcard.items;");
|
||||
assert_eq!(super::schema_of("reborn-characters").unwrap(), "acore_characters_reborn");
|
||||
assert_eq!(
|
||||
super::schema_of("reborn-characters").unwrap(),
|
||||
"acore_characters_reborn"
|
||||
);
|
||||
assert_eq!(super::schema_of("reborn-auth").unwrap(), "acore_auth");
|
||||
}
|
||||
use super::*;
|
||||
|
||||
@@ -96,6 +96,9 @@ pub fn run(root: &Path, meta: &InstallMeta) -> Report {
|
||||
if let Some(second) = &o.secondary_world {
|
||||
services.push(("Second world", second));
|
||||
}
|
||||
if let Some(reborn) = &o.reborn_world {
|
||||
services.push(("Warcraft Reborn world", reborn));
|
||||
}
|
||||
for (title, s) in services {
|
||||
let (lvl, text) = match (s.state, &s.conflict) {
|
||||
(ServiceState::Running, _) => (Level::Ok, "Running".to_string()),
|
||||
@@ -639,6 +642,7 @@ fn processes_report(root: &Path, ports: &layout::Ports) -> String {
|
||||
Some(&o.auth),
|
||||
Some(&o.world),
|
||||
o.secondary_world.as_ref(),
|
||||
o.reborn_world.as_ref(),
|
||||
]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
@@ -1045,7 +1049,12 @@ real error
|
||||
fn stop_diagnostics_survive_while_portable_pins_remain_hidden() {
|
||||
let ordinary = "MySQL is still stopping; wait before copying the repack.";
|
||||
assert_eq!(redact(ordinary), ordinary);
|
||||
for secret in ["PIN: 123456", "pin=123456", "transfer_pin=123456", "PIN123456"] {
|
||||
for secret in [
|
||||
"PIN: 123456",
|
||||
"pin=123456",
|
||||
"transfer_pin=123456",
|
||||
"PIN123456",
|
||||
] {
|
||||
let output = redact(&format!("{ordinary}\n{secret}"));
|
||||
assert!(output.contains(ordinary));
|
||||
assert!(!output.contains("123456"));
|
||||
|
||||
@@ -758,6 +758,7 @@ pub fn observe_with(d: &dyn Docker, root: &Path, ports: &Ports) -> Observed {
|
||||
auth: unknown("auth", ports.auth),
|
||||
world: unknown("world", ports.world),
|
||||
secondary_world: None,
|
||||
reborn_world: None,
|
||||
};
|
||||
};
|
||||
let n = cfg.names();
|
||||
@@ -767,6 +768,7 @@ pub fn observe_with(d: &dyn Docker, root: &Path, ports: &Ports) -> Observed {
|
||||
auth: unknown("auth", ports.auth),
|
||||
world: unknown("world", ports.world),
|
||||
secondary_world: None,
|
||||
reborn_world: None,
|
||||
};
|
||||
};
|
||||
let ip = connect_ip(&cfg);
|
||||
@@ -795,6 +797,7 @@ pub fn observe_with(d: &dyn Docker, root: &Path, ports: &Ports) -> Observed {
|
||||
listening(state.get(&n.world), ports.world),
|
||||
),
|
||||
secondary_world: None,
|
||||
reborn_world: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1249,12 +1252,27 @@ mod tests {
|
||||
"db;3306;acore;apppw;acore_characters"
|
||||
);
|
||||
let wild = database_env(&s, true, crate::realms::Mode::Wildcard);
|
||||
assert_eq!(get(&wild, "AC_WORLD_DATABASE_INFO").unwrap(), "db;3306;acore;apppw;acore_world_wildcard");
|
||||
assert_eq!(get(&wild, "AC_CHARACTER_DATABASE_INFO").unwrap(), "db;3306;acore;apppw;acore_characters_wildcard");
|
||||
assert_eq!(
|
||||
get(&wild, "AC_WORLD_DATABASE_INFO").unwrap(),
|
||||
"db;3306;acore;apppw;acore_world_wildcard"
|
||||
);
|
||||
assert_eq!(
|
||||
get(&wild, "AC_CHARACTER_DATABASE_INFO").unwrap(),
|
||||
"db;3306;acore;apppw;acore_characters_wildcard"
|
||||
);
|
||||
let reborn = database_env(&s, true, crate::realms::Mode::Reborn);
|
||||
assert_eq!(get(&reborn, "AC_WORLD_DATABASE_INFO").unwrap(), "db;3306;acore;apppw;acore_world_reborn");
|
||||
assert_eq!(get(&reborn, "AC_CHARACTER_DATABASE_INFO").unwrap(), "db;3306;acore;apppw;acore_characters_reborn");
|
||||
assert_eq!(get(&reborn, "AC_LOGIN_DATABASE_INFO").unwrap(), "db;3306;acore;apppw;acore_auth");
|
||||
assert_eq!(
|
||||
get(&reborn, "AC_WORLD_DATABASE_INFO").unwrap(),
|
||||
"db;3306;acore;apppw;acore_world_reborn"
|
||||
);
|
||||
assert_eq!(
|
||||
get(&reborn, "AC_CHARACTER_DATABASE_INFO").unwrap(),
|
||||
"db;3306;acore;apppw;acore_characters_reborn"
|
||||
);
|
||||
assert_eq!(
|
||||
get(&reborn, "AC_LOGIN_DATABASE_INFO").unwrap(),
|
||||
"db;3306;acore;apppw;acore_auth"
|
||||
);
|
||||
// Accounts are shared by both realms; the auth server never sees the others.
|
||||
assert_eq!(
|
||||
get(&wild, "AC_LOGIN_DATABASE_INFO").unwrap(),
|
||||
|
||||
@@ -12,16 +12,28 @@ pub fn database_log(root: &Path, filter: Option<&str>, max_lines: usize) -> Resu
|
||||
database_log_with(&SystemDocker, root, filter, max_lines)
|
||||
}
|
||||
|
||||
pub fn database_log_with(d: &dyn Docker, root: &Path, filter: Option<&str>, max_lines: usize) -> Result<Vec<Line>> {
|
||||
pub fn database_log_with(
|
||||
d: &dyn Docker,
|
||||
root: &Path,
|
||||
filter: Option<&str>,
|
||||
max_lines: usize,
|
||||
) -> Result<Vec<Line>> {
|
||||
let name = Config::load(root)?.names().db;
|
||||
// Ask for more than wanted: the filter may drop most of them.
|
||||
let tail = (max_lines * 4).clamp(200, 8000).to_string();
|
||||
let out = d.run(&Call::new(&["logs", "--tail", &tail, &name], Duration::from_secs(20)))?;
|
||||
let out = d.run(&Call::new(
|
||||
&["logs", "--tail", &tail, &name],
|
||||
Duration::from_secs(20),
|
||||
))?;
|
||||
if !out.ok() {
|
||||
return Err(Error::Invalid("This log does not exist yet.".into()));
|
||||
}
|
||||
// MySQL writes to the error stream.
|
||||
Ok(crate::console::lines_from_text(&format!("{}\n{}", out.stderr, out.stdout), filter, max_lines))
|
||||
Ok(crate::console::lines_from_text(
|
||||
&format!("{}\n{}", out.stderr, out.stdout),
|
||||
filter,
|
||||
max_lines,
|
||||
))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -58,7 +70,9 @@ mod tests {
|
||||
assert_eq!(fake.calls.borrow()[0][..2], ["logs", "--tail"]);
|
||||
assert_eq!(fake.calls.borrow()[0].last().unwrap(), "coa-t1-db");
|
||||
assert_eq!(lines.len(), 3);
|
||||
assert!(lines.iter().any(|l| l.text.contains("boom") && l.level == crate::console::Level::Error));
|
||||
assert!(lines
|
||||
.iter()
|
||||
.any(|l| l.text.contains("boom") && l.level == crate::console::Level::Error));
|
||||
let only = database_log_with(&fake, &root, Some("slow"), 100).unwrap();
|
||||
assert_eq!(only.len(), 1);
|
||||
}
|
||||
@@ -66,7 +80,17 @@ mod tests {
|
||||
#[test]
|
||||
fn a_database_that_never_ran_has_no_log_yet() {
|
||||
let (_d, root) = root();
|
||||
let fake = Fake { out: Output { code: Some(1), stdout: String::new(), stderr: "Error: No such container: coa-t1-db".into() }, calls: Default::default() };
|
||||
assert!(database_log_with(&fake, &root, None, 10).unwrap_err().to_string().contains("does not exist yet"));
|
||||
let fake = Fake {
|
||||
out: Output {
|
||||
code: Some(1),
|
||||
stdout: String::new(),
|
||||
stderr: "Error: No such container: coa-t1-db".into(),
|
||||
},
|
||||
calls: Default::default(),
|
||||
};
|
||||
assert!(database_log_with(&fake, &root, None, 10)
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("does not exist yet"));
|
||||
}
|
||||
}
|
||||
@@ -18,7 +18,10 @@ use crate::net::Exposure;
|
||||
use crate::process::{ServiceState, ServiceStatus};
|
||||
|
||||
fn is_open(cfg: &Config) -> bool {
|
||||
cfg.bind_address.parse::<IpAddr>().map(|ip| !ip.is_loopback()).unwrap_or(false)
|
||||
cfg.bind_address
|
||||
.parse::<IpAddr>()
|
||||
.map(|ip| !ip.is_loopback())
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
/// Whether the login and world servers are published beyond this computer.
|
||||
@@ -46,7 +49,11 @@ pub fn set_open(root: &Path, meta: &Path, open: bool) -> Result<bool> {
|
||||
if let Ok(bytes) = fs::read(&coa_conf) {
|
||||
let mut conf = ConfFile::parse_bytes(&bytes)?;
|
||||
if conf.get("CoA.AllowRemoteClients").map(str::trim) != Some("1") {
|
||||
conf.set("CoA.AllowRemoteClients", "1", &["Set by CoA Server Manager together with the friends mode"]);
|
||||
conf.set(
|
||||
"CoA.AllowRemoteClients",
|
||||
"1",
|
||||
&["Set by CoA Server Manager together with the friends mode"],
|
||||
);
|
||||
originals.push((coa_conf.clone(), bytes));
|
||||
coa_edit = Some(conf.to_text());
|
||||
}
|
||||
@@ -55,7 +62,16 @@ pub fn set_open(root: &Path, meta: &Path, open: bool) -> Result<bool> {
|
||||
if !changed && coa_edit.is_none() {
|
||||
return Ok(false);
|
||||
}
|
||||
take_snapshot(meta, Scope::Server, if open { "before opening the servers to friends" } else { "before closing the servers to friends" }, &originals)?;
|
||||
take_snapshot(
|
||||
meta,
|
||||
Scope::Server,
|
||||
if open {
|
||||
"before opening the servers to friends"
|
||||
} else {
|
||||
"before closing the servers to friends"
|
||||
},
|
||||
&originals,
|
||||
)?;
|
||||
if changed {
|
||||
fsx::atomic_write_json(&root.join(MARKER), &cfg)?;
|
||||
}
|
||||
@@ -73,10 +89,30 @@ pub fn exposure(root: &Path, ports: &Ports) -> Vec<Exposure> {
|
||||
let observed = crate::process::observe(root, ports);
|
||||
let up = |s: &ServiceStatus| matches!(s.state, ServiceState::Running | ServiceState::Starting);
|
||||
vec![
|
||||
Exposure { port: ports.mysql, what: "database", listening: up(&observed.mysql), reachable_from_network: false },
|
||||
Exposure { port: ports.ra, what: "server console", listening: up(&observed.world), reachable_from_network: false },
|
||||
Exposure { port: ports.auth, what: "login server", listening: up(&observed.auth), reachable_from_network: open && up(&observed.auth) },
|
||||
Exposure { port: ports.world, what: "game world", listening: up(&observed.world), reachable_from_network: open && up(&observed.world) },
|
||||
Exposure {
|
||||
port: ports.mysql,
|
||||
what: "database",
|
||||
listening: up(&observed.mysql),
|
||||
reachable_from_network: false,
|
||||
},
|
||||
Exposure {
|
||||
port: ports.ra,
|
||||
what: "server console",
|
||||
listening: up(&observed.world),
|
||||
reachable_from_network: false,
|
||||
},
|
||||
Exposure {
|
||||
port: ports.auth,
|
||||
what: "login server",
|
||||
listening: up(&observed.auth),
|
||||
reachable_from_network: open && up(&observed.auth),
|
||||
},
|
||||
Exposure {
|
||||
port: ports.world,
|
||||
what: "game world",
|
||||
listening: up(&observed.world),
|
||||
reachable_from_network: open && up(&observed.world),
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
@@ -91,9 +127,15 @@ mod tests {
|
||||
fs::create_dir_all(root.join("Settings")).unwrap();
|
||||
fs::create_dir_all(root.join("Core/configs/modules")).unwrap();
|
||||
fs::create_dir_all(&meta).unwrap();
|
||||
let extra = bind.map(|b| format!(r#","bindAddress":"{b}""#)).unwrap_or_default();
|
||||
let extra = bind
|
||||
.map(|b| format!(r#","bindAddress":"{b}""#))
|
||||
.unwrap_or_default();
|
||||
fs::write(root.join(MARKER), format!(r#"{{"project":"t1"{extra}}}"#)).unwrap();
|
||||
fs::write(root.join("Core/configs/modules/coa.conf"), "CoA.Enable = 1\n").unwrap();
|
||||
fs::write(
|
||||
root.join("Core/configs/modules/coa.conf"),
|
||||
"CoA.Enable = 1\n",
|
||||
)
|
||||
.unwrap();
|
||||
(d, root, meta)
|
||||
}
|
||||
|
||||
@@ -104,8 +146,15 @@ mod tests {
|
||||
assert!(set_open(&root, &meta, true).unwrap(), "a restart is needed");
|
||||
assert!(bind_is_open(&root));
|
||||
assert_eq!(Config::load(&root).unwrap().bind_address, "0.0.0.0");
|
||||
assert!(fs::read_to_string(root.join("Core/configs/modules/coa.conf")).unwrap().contains("CoA.AllowRemoteClients = 1"));
|
||||
assert!(!set_open(&root, &meta, true).unwrap(), "nothing left to change");
|
||||
assert!(
|
||||
fs::read_to_string(root.join("Core/configs/modules/coa.conf"))
|
||||
.unwrap()
|
||||
.contains("CoA.AllowRemoteClients = 1")
|
||||
);
|
||||
assert!(
|
||||
!set_open(&root, &meta, true).unwrap(),
|
||||
"nothing left to change"
|
||||
);
|
||||
assert!(set_open(&root, &meta, false).unwrap());
|
||||
assert!(!bind_is_open(&root));
|
||||
assert_eq!(Config::load(&root).unwrap().bind_address, "127.0.0.1");
|
||||
@@ -114,7 +163,11 @@ mod tests {
|
||||
#[test]
|
||||
fn enabling_remote_client_protocol_requires_restart_even_when_ports_are_open() {
|
||||
let (_d, root, meta) = server(Some("0.0.0.0"));
|
||||
fs::write(root.join("Core/configs/modules/coa.conf"), "CoA.Enable = 1\nCoA.AllowRemoteClients = 0\n").unwrap();
|
||||
fs::write(
|
||||
root.join("Core/configs/modules/coa.conf"),
|
||||
"CoA.Enable = 1\nCoA.AllowRemoteClients = 0\n",
|
||||
)
|
||||
.unwrap();
|
||||
assert!(set_open(&root, &meta, true).unwrap());
|
||||
assert_eq!(Config::load(&root).unwrap().bind_address, "0.0.0.0");
|
||||
assert!(!set_open(&root, &meta, true).unwrap());
|
||||
@@ -123,7 +176,10 @@ mod tests {
|
||||
#[test]
|
||||
fn an_address_chosen_by_hand_is_kept_when_opening_and_other_settings_survive() {
|
||||
let (_d, root, meta) = server(Some("192.168.1.20"));
|
||||
assert!(bind_is_open(&root), "any address but the loopback is the network");
|
||||
assert!(
|
||||
bind_is_open(&root),
|
||||
"any address but the loopback is the network"
|
||||
);
|
||||
set_open(&root, &meta, true).unwrap();
|
||||
let cfg = Config::load(&root).unwrap();
|
||||
assert_eq!(cfg.bind_address, "192.168.1.20");
|
||||
@@ -142,7 +198,9 @@ mod tests {
|
||||
let (_d, root, _meta) = server(Some("0.0.0.0"));
|
||||
let rows = exposure(&root, &Ports::default());
|
||||
let by = |what: &str| rows.iter().find(|e| e.what == what).unwrap();
|
||||
assert!(!by("database").reachable_from_network && !by("server console").reachable_from_network);
|
||||
assert!(
|
||||
!by("database").reachable_from_network && !by("server console").reachable_from_network
|
||||
);
|
||||
// Nothing runs in this test (docker is not asked to start anything), so nothing is reachable yet.
|
||||
assert!(rows.iter().all(|e| !e.reachable_from_network));
|
||||
}
|
||||
|
||||
@@ -254,7 +254,7 @@ fn run_inner(root: &Path, verb: Verb, validating_update: bool) -> Result<DriverO
|
||||
let observed = crate::process::observe(&root, &crate::layout::read_ports(&root));
|
||||
for service in [&observed.mysql, &observed.auth, &observed.world]
|
||||
.into_iter()
|
||||
.chain(observed.secondary_world.iter())
|
||||
.chain(observed.extra_worlds())
|
||||
{
|
||||
if let Some(conflict) = &service.conflict {
|
||||
output.push_str(&format!(
|
||||
|
||||
@@ -88,23 +88,27 @@ fn run_elevated(commands: &[String]) -> Result<()> {
|
||||
|
||||
/// Make sure both rules exist (adds only the missing ones) and confirm afterwards.
|
||||
pub fn ensure_rules(ports: &Ports) -> Result<Status> {
|
||||
ensure_rules_with_secondary(ports, None)
|
||||
ensure_rules_with_extra(ports, &[])
|
||||
}
|
||||
|
||||
pub fn ensure_rules_with_secondary(ports: &Ports, secondary: Option<u16>) -> Result<Status> {
|
||||
/// As `ensure_rules`, plus one rule for the world port of each extra realm that runs next to the main one.
|
||||
pub fn ensure_rules_with_extra(ports: &Ports, extra: &[u16]) -> Result<Status> {
|
||||
let have = status();
|
||||
let mut cmds = plan(ports, &have);
|
||||
let second_name = secondary.map(|port| format!("CoA Server Manager - Second World {port}"));
|
||||
if let (Some(port), Some(name)) = (secondary, &second_name) {
|
||||
let extra_names: Vec<String> = extra
|
||||
.iter()
|
||||
.map(|port| format!("CoA Server Manager - Second World {port}"))
|
||||
.collect();
|
||||
for (port, name) in extra.iter().zip(&extra_names) {
|
||||
if !rule_exists(name) {
|
||||
cmds.push(add_cmd(name, port));
|
||||
cmds.push(add_cmd(name, *port));
|
||||
}
|
||||
}
|
||||
if !cmds.is_empty() {
|
||||
run_elevated(&cmds)?;
|
||||
}
|
||||
let now = status();
|
||||
if now.auth && now.world && second_name.as_ref().is_none_or(|name| rule_exists(name)) {
|
||||
if now.auth && now.world && extra_names.iter().all(|name| rule_exists(name)) {
|
||||
Ok(now)
|
||||
} else {
|
||||
Err(Error::Invalid(
|
||||
|
||||
@@ -163,20 +163,64 @@ 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).
|
||||
pub fn apply_realm_address(root: &Path, host: &str) -> Result<()> {
|
||||
fn realm_address_sql(
|
||||
host: &str,
|
||||
local: Option<(std::net::Ipv4Addr, std::net::Ipv4Addr)>,
|
||||
where_realms: &str,
|
||||
) -> Result<String> {
|
||||
if !host_ok(host) {
|
||||
return Err(Error::Invalid("That address is not valid.".into()));
|
||||
}
|
||||
let db = Db::from_repack(root, Account::Admin)?;
|
||||
let realm = crate::realms::state(root)?.active.realm_id();
|
||||
let where_realms = if crate::realms::state(root)?.simultaneous {
|
||||
"id IN (1,2)".into()
|
||||
} else {
|
||||
format!("id={realm}")
|
||||
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,
|
||||
};
|
||||
db.query(&format!(
|
||||
"UPDATE acore_auth.realmlist SET address='{host}' WHERE {where_realms};"
|
||||
))?;
|
||||
let db = Db::from_repack(root, Account::Admin)?;
|
||||
let state = crate::realms::state(root)?;
|
||||
let mut ids = vec![state.active];
|
||||
ids.extend(state.extra_modes());
|
||||
let where_realms = format!(
|
||||
"id IN ({})",
|
||||
ids.iter()
|
||||
.map(|m| m.realm_id().to_string())
|
||||
.collect::<Vec<_>>()
|
||||
.join(",")
|
||||
);
|
||||
db.query(&realm_address_sql(host, local, &where_realms)?)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -194,9 +238,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(host)) => apply_realm_address(root, &host),
|
||||
(_, Some(_)) => apply_realm_address(root, &s),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -390,6 +434,25 @@ 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();
|
||||
|
||||
@@ -36,7 +36,12 @@ fn key(path: &Path) -> Vec<String> {
|
||||
return format!("{}:", char::from(drive).to_ascii_lowercase());
|
||||
}
|
||||
Prefix::UNC(server, share) | Prefix::VerbatimUNC(server, share) => {
|
||||
return format!("\\\\{}\\{}", server.to_string_lossy(), share.to_string_lossy()).to_lowercase();
|
||||
return format!(
|
||||
"\\\\{}\\{}",
|
||||
server.to_string_lossy(),
|
||||
share.to_string_lossy()
|
||||
)
|
||||
.to_lowercase();
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
@@ -337,12 +342,30 @@ mod tests {
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn containment_matches_verbatim_drive_and_unc_prefixes() {
|
||||
assert!(starts_with_ci(Path::new(r"\\?\C:\server\Extras\file.sql"), Path::new(r"C:\server")));
|
||||
assert!(starts_with_ci(Path::new(r"C:\server\Extras\file.sql"), Path::new(r"\\?\c:\server")));
|
||||
assert!(starts_with_ci(Path::new(r"\\?\UNC\host\share\server\file.sql"), Path::new(r"\\host\share\server")));
|
||||
assert!(!starts_with_ci(Path::new(r"\\?\D:\server\file.sql"), Path::new(r"C:\server")));
|
||||
assert!(!starts_with_ci(Path::new(r"\\?\C:\server-other\file.sql"), Path::new(r"C:\server")));
|
||||
assert!(!starts_with_ci(Path::new(r"\\?\UNC\host\other\server\file.sql"), Path::new(r"\\host\share\server")));
|
||||
assert!(starts_with_ci(
|
||||
Path::new(r"\\?\C:\server\Extras\file.sql"),
|
||||
Path::new(r"C:\server")
|
||||
));
|
||||
assert!(starts_with_ci(
|
||||
Path::new(r"C:\server\Extras\file.sql"),
|
||||
Path::new(r"\\?\c:\server")
|
||||
));
|
||||
assert!(starts_with_ci(
|
||||
Path::new(r"\\?\UNC\host\share\server\file.sql"),
|
||||
Path::new(r"\\host\share\server")
|
||||
));
|
||||
assert!(!starts_with_ci(
|
||||
Path::new(r"\\?\D:\server\file.sql"),
|
||||
Path::new(r"C:\server")
|
||||
));
|
||||
assert!(!starts_with_ci(
|
||||
Path::new(r"\\?\C:\server-other\file.sql"),
|
||||
Path::new(r"C:\server")
|
||||
));
|
||||
assert!(!starts_with_ci(
|
||||
Path::new(r"\\?\UNC\host\other\server\file.sql"),
|
||||
Path::new(r"\\host\share\server")
|
||||
));
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
|
||||
@@ -165,21 +165,38 @@ impl Manifest {
|
||||
}
|
||||
if let Some(c) = &self.compatibility {
|
||||
if parse_version(&self.min_manager_version).is_none_or(|v| v < (0, 6, 13)) {
|
||||
return bad("Release compatibility matrices require Manager 0.6.13 or newer".into());
|
||||
return bad(
|
||||
"Release compatibility matrices require Manager 0.6.13 or newer".into(),
|
||||
);
|
||||
}
|
||||
if c.schema != 1 || !matches!(c.platform.as_str(), "windows-x86_64" | "linux-x86_64")
|
||||
|| !is_commit(&c.core_commit) || self.core.commit.as_deref() != Some(&c.core_commit)
|
||||
|| c.module_commits.is_empty() || c.module_commits.values().any(|sha| !is_commit(sha))
|
||||
|| self.bots.as_ref().and_then(|r| r.commit.as_ref()).is_some_and(|sha| c.module_commits.get("bots") != Some(sha))
|
||||
if c.schema != 1
|
||||
|| !matches!(c.platform.as_str(), "windows-x86_64" | "linux-x86_64")
|
||||
|| !is_commit(&c.core_commit)
|
||||
|| self.core.commit.as_deref() != Some(&c.core_commit)
|
||||
|| c.module_commits.is_empty()
|
||||
|| c.module_commits.values().any(|sha| !is_commit(sha))
|
||||
|| self
|
||||
.bots
|
||||
.as_ref()
|
||||
.and_then(|r| r.commit.as_ref())
|
||||
.is_some_and(|sha| c.module_commits.get("bots") != Some(sha))
|
||||
|| parse_version(&c.client_patch_version).is_none()
|
||||
|| c.source_versions.is_empty() || c.source_versions.iter().any(|v| parse_version(v).is_none())
|
||||
|| c.source_versions.iter().collect::<HashSet<_>>().len() != c.source_versions.len() {
|
||||
|| c.source_versions.is_empty()
|
||||
|| c.source_versions.iter().any(|v| parse_version(v).is_none())
|
||||
|| c.source_versions.iter().collect::<HashSet<_>>().len() != c.source_versions.len()
|
||||
{
|
||||
return bad("Invalid release compatibility matrix".into());
|
||||
}
|
||||
if !c.source_databases.is_empty() && (c.source_databases.len() != c.source_versions.len()
|
||||
|| c.source_versions.iter().any(|v| !c.source_databases.contains_key(v))
|
||||
|| c.source_databases.values().any(|s| !is_sha256(&s.manifest_sha256)
|
||||
|| s.schema_sha256.as_ref().is_some_and(|sha| !is_sha256(sha)))) {
|
||||
if !c.source_databases.is_empty()
|
||||
&& (c.source_databases.len() != c.source_versions.len()
|
||||
|| c.source_versions
|
||||
.iter()
|
||||
.any(|v| !c.source_databases.contains_key(v))
|
||||
|| c.source_databases.values().any(|s| {
|
||||
!is_sha256(&s.manifest_sha256)
|
||||
|| s.schema_sha256.as_ref().is_some_and(|sha| !is_sha256(sha))
|
||||
}))
|
||||
{
|
||||
return bad("Invalid source database compatibility".into());
|
||||
}
|
||||
}
|
||||
@@ -308,9 +325,15 @@ mod tests {
|
||||
fn compatibility_matrix_binds_core_and_requires_tested_sources() {
|
||||
let mut m = Manifest::parse(sample("").as_bytes()).unwrap();
|
||||
m.min_manager_version = "0.6.13".into();
|
||||
m.compatibility = Some(Compatibility { schema: 1, platform: "windows-x86_64".into(),
|
||||
core_commit: "a".repeat(40), module_commits: [("squid".into(), "b".repeat(40))].into(),
|
||||
source_databases: Default::default(), client_patch_version: "1.5.1".into(), source_versions: vec!["0.261010.32".into()] });
|
||||
m.compatibility = Some(Compatibility {
|
||||
schema: 1,
|
||||
platform: "windows-x86_64".into(),
|
||||
core_commit: "a".repeat(40),
|
||||
module_commits: [("squid".into(), "b".repeat(40))].into(),
|
||||
source_databases: Default::default(),
|
||||
client_patch_version: "1.5.1".into(),
|
||||
source_versions: vec!["0.261010.32".into()],
|
||||
});
|
||||
m.validate().unwrap();
|
||||
m.compatibility.as_mut().unwrap().core_commit = "c".repeat(40);
|
||||
assert!(m.validate().is_err());
|
||||
@@ -323,14 +346,30 @@ mod tests {
|
||||
fn compatibility_cannot_claim_a_different_packaged_bot_revision() {
|
||||
let mut m = Manifest::parse(sample("").as_bytes()).unwrap();
|
||||
m.min_manager_version = "0.6.13".into();
|
||||
m.bots = Some(Revision { commit: Some("b".repeat(40)) });
|
||||
m.compatibility = Some(Compatibility { schema: 1, platform: "windows-x86_64".into(),
|
||||
core_commit: "a".repeat(40), module_commits: [("bots".into(), "c".repeat(40))].into(),
|
||||
source_databases: Default::default(), client_patch_version: "1.5.1".into(), source_versions: vec!["0.2.0".into()] });
|
||||
m.bots = Some(Revision {
|
||||
commit: Some("b".repeat(40)),
|
||||
});
|
||||
m.compatibility = Some(Compatibility {
|
||||
schema: 1,
|
||||
platform: "windows-x86_64".into(),
|
||||
core_commit: "a".repeat(40),
|
||||
module_commits: [("bots".into(), "c".repeat(40))].into(),
|
||||
source_databases: Default::default(),
|
||||
client_patch_version: "1.5.1".into(),
|
||||
source_versions: vec!["0.2.0".into()],
|
||||
});
|
||||
assert!(m.validate().is_err());
|
||||
m.compatibility.as_mut().unwrap().module_commits.insert("bots".into(), "b".repeat(40));
|
||||
m.compatibility
|
||||
.as_mut()
|
||||
.unwrap()
|
||||
.module_commits
|
||||
.insert("bots".into(), "b".repeat(40));
|
||||
m.validate().unwrap();
|
||||
m.compatibility.as_mut().unwrap().source_versions.push("0.2.0".into());
|
||||
m.compatibility
|
||||
.as_mut()
|
||||
.unwrap()
|
||||
.source_versions
|
||||
.push("0.2.0".into());
|
||||
assert!(m.validate().is_err());
|
||||
}
|
||||
|
||||
@@ -338,12 +377,30 @@ mod tests {
|
||||
fn source_database_contracts_must_cover_the_exact_upgrade_versions() {
|
||||
let mut m = Manifest::parse(sample("").as_bytes()).unwrap();
|
||||
m.min_manager_version = "0.6.13".into();
|
||||
m.compatibility = Some(Compatibility { schema: 1, platform: "windows-x86_64".into(),
|
||||
core_commit: "a".repeat(40), module_commits: [("squid".into(), "b".repeat(40))].into(),
|
||||
client_patch_version: "1.5.1".into(), source_versions: vec!["0.2.0".into()],
|
||||
source_databases: [("0.2.0".into(), SourceDatabase { manifest_sha256: "a".repeat(64), schema_sha256: None })].into() });
|
||||
m.compatibility = Some(Compatibility {
|
||||
schema: 1,
|
||||
platform: "windows-x86_64".into(),
|
||||
core_commit: "a".repeat(40),
|
||||
module_commits: [("squid".into(), "b".repeat(40))].into(),
|
||||
client_patch_version: "1.5.1".into(),
|
||||
source_versions: vec!["0.2.0".into()],
|
||||
source_databases: [(
|
||||
"0.2.0".into(),
|
||||
SourceDatabase {
|
||||
manifest_sha256: "a".repeat(64),
|
||||
schema_sha256: None,
|
||||
},
|
||||
)]
|
||||
.into(),
|
||||
});
|
||||
m.validate().unwrap();
|
||||
m.compatibility.as_mut().unwrap().source_databases.get_mut("0.2.0").unwrap().schema_sha256 = Some("bad".into());
|
||||
m.compatibility
|
||||
.as_mut()
|
||||
.unwrap()
|
||||
.source_databases
|
||||
.get_mut("0.2.0")
|
||||
.unwrap()
|
||||
.schema_sha256 = Some("bad".into());
|
||||
assert!(m.validate().is_err());
|
||||
let c = m.compatibility.as_mut().unwrap();
|
||||
c.source_databases.get_mut("0.2.0").unwrap().schema_sha256 = None;
|
||||
|
||||
@@ -101,8 +101,19 @@ impl Store for Db {
|
||||
let connection = self.clone().for_realm(crate::realms::Mode::Coa);
|
||||
let world = self.realm_schema("acore_world");
|
||||
let characters = self.realm_schema("acore_characters");
|
||||
let others: Vec<_> = [crate::realms::Mode::Coa, crate::realms::Mode::Wildcard, crate::realms::Mode::Reborn].into_iter().filter(|m| *m != self.realm()).map(|m| m.schema("world").unwrap()).collect();
|
||||
let schemas: std::collections::BTreeSet<_> = [world, characters, AUTH_LEDGER_SCHEMA].into_iter().chain(others.iter().copied()).collect();
|
||||
let others: Vec<_> = [
|
||||
crate::realms::Mode::Coa,
|
||||
crate::realms::Mode::Wildcard,
|
||||
crate::realms::Mode::Reborn,
|
||||
]
|
||||
.into_iter()
|
||||
.filter(|m| *m != self.realm())
|
||||
.map(|m| m.schema("world").unwrap())
|
||||
.collect();
|
||||
let schemas: std::collections::BTreeSet<_> = [world, characters, AUTH_LEDGER_SCHEMA]
|
||||
.into_iter()
|
||||
.chain(others.iter().copied())
|
||||
.collect();
|
||||
let catalog = connection.query(&format!("SELECT table_schema,table_name FROM information_schema.tables WHERE table_schema IN ('{}') AND table_name IN ('updates','{LEDGER_TABLE}') AND table_type='BASE TABLE';", schemas.into_iter().collect::<Vec<_>>().join("','")))?;
|
||||
let available: std::collections::BTreeSet<_> = catalog
|
||||
.lines()
|
||||
@@ -120,7 +131,16 @@ impl Store for Db {
|
||||
queries.push(format!("SELECT 'core','{kind}',{},REPEAT('0',64),'applied',1,'' FROM `{schema}`.`updates` WHERE BINARY RIGHT(name,4)='.sql'",text("LEFT(name,CHAR_LENGTH(name)-4)")));
|
||||
}
|
||||
}
|
||||
for (origin, schema, filter) in [("local",world,""), ("shared",AUTH_LEDGER_SCHEMA,"")].into_iter().chain(others.iter().map(|schema| ("other", *schema, " WHERE `db` IN ('auth','coa-auth','wildcard-auth','reborn-auth')"))) {
|
||||
for (origin, schema, filter) in [("local", world, ""), ("shared", AUTH_LEDGER_SCHEMA, "")]
|
||||
.into_iter()
|
||||
.chain(others.iter().map(|schema| {
|
||||
(
|
||||
"other",
|
||||
*schema,
|
||||
" WHERE `db` IN ('auth','coa-auth','wildcard-auth','reborn-auth')",
|
||||
)
|
||||
}))
|
||||
{
|
||||
if available.contains(&(schema, LEDGER_TABLE)) {
|
||||
queries.push(format!("SELECT '{origin}',{},{},{},{},`baseline`,{} FROM `{schema}`.`{LEDGER_TABLE}`{filter}",text("`db`"),text("`id`"),text("`sha256`"),text("`status`"),text("COALESCE(HEX(`error`),'')")));
|
||||
}
|
||||
|
||||
@@ -173,7 +173,9 @@ 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 wildcard = crate::realms::state(root).map(|s| s.active != crate::realms::Mode::Coa).unwrap_or(true);
|
||||
let wildcard = crate::realms::state(root)
|
||||
.map(|s| s.active != crate::realms::Mode::Coa)
|
||||
.unwrap_or(true);
|
||||
cat.iter()
|
||||
.cloned()
|
||||
.map(|e| {
|
||||
@@ -522,6 +524,18 @@ 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())
|
||||
@@ -532,10 +546,17 @@ fn save_settings_in(
|
||||
));
|
||||
}
|
||||
}
|
||||
if id == "content-scaling" && key.starts_with("CoAContentScaling.Difficulty.Health.") && key.ends_with("Multiplier") {
|
||||
let multiplier = value.parse::<f32>().map_err(|_| Error::Invalid("Health multipliers must be a number from 0.1 to 10.".into()))?;
|
||||
if id == "content-scaling"
|
||||
&& key.starts_with("CoAContentScaling.Difficulty.Health.")
|
||||
&& key.ends_with("Multiplier")
|
||||
{
|
||||
let multiplier = value.parse::<f32>().map_err(|_| {
|
||||
Error::Invalid("Health multipliers must be a number from 0.1 to 10.".into())
|
||||
})?;
|
||||
if !multiplier.is_finite() || !(0.1..=10.0).contains(&multiplier) {
|
||||
return Err(Error::Invalid("Health multipliers must be a number from 0.1 to 10.".into()));
|
||||
return Err(Error::Invalid(
|
||||
"Health multipliers must be a number from 0.1 to 10.".into(),
|
||||
));
|
||||
}
|
||||
}
|
||||
if id == "content-scaling" && key == "CoAContentScaling.World.Leech.Percent" {
|
||||
@@ -611,6 +632,53 @@ 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(),
|
||||
@@ -802,8 +870,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!(
|
||||
e.description.contains_key("en") && e.description.len() == 5,
|
||||
"{} has all five descriptions",
|
||||
["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.id
|
||||
);
|
||||
assert!(
|
||||
@@ -1202,17 +1270,33 @@ mod tests {
|
||||
for key in keys {
|
||||
let changes = |v: &str| BTreeMap::from([(key.to_string(), v.to_string())]);
|
||||
for bad in ["NaN", "inf", "0", "0.09", "10.01", "-1", "abc", ""] {
|
||||
assert!(save_settings_in(&cat, &root, &meta, "content-scaling", &changes(bad)).is_err(), "{key} {bad}");
|
||||
assert!(
|
||||
save_settings_in(&cat, &root, &meta, "content-scaling", &changes(bad)).is_err(),
|
||||
"{key} {bad}"
|
||||
);
|
||||
}
|
||||
for good in ["0.1", "0.4", "1", "2.5", "10"] {
|
||||
assert_eq!(save_settings_in(&cat, &root, &meta, "content-scaling", &changes(good)).unwrap(), [key]);
|
||||
assert_eq!(settings_in(&cat, &root, "content-scaling").unwrap().iter().find(|s| s.key == key).unwrap().value, good);
|
||||
assert_eq!(
|
||||
save_settings_in(&cat, &root, &meta, "content-scaling", &changes(good))
|
||||
.unwrap(),
|
||||
[key]
|
||||
);
|
||||
assert_eq!(
|
||||
settings_in(&cat, &root, "content-scaling")
|
||||
.unwrap()
|
||||
.iter()
|
||||
.find(|s| s.key == key)
|
||||
.unwrap()
|
||||
.value,
|
||||
good
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_older_file_name_is_used_when_the_current_one_is_missing_and_a_part_that_cannot_be_switched_stays_on() {
|
||||
fn an_older_file_name_is_used_when_the_current_one_is_missing_and_a_part_that_cannot_be_switched_stays_on(
|
||||
) {
|
||||
let d = tempfile::tempdir().unwrap();
|
||||
let (root, meta) = server(d.path());
|
||||
fs::write(
|
||||
|
||||
@@ -12,12 +12,66 @@ use std::{
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
|
||||
pub fn root(main: &Path) -> PathBuf {
|
||||
main.join(".realms/secondary")
|
||||
/// A world that runs next to the primary one. Each has its own folder, configs, logs and ports; auth and MySQL stay shared.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Tree {
|
||||
/// Wildcard next to Conquest of Azeroth (or Conquest of Azeroth next to Wildcard when Wildcard is the primary).
|
||||
Second,
|
||||
/// Warcraft Reborn next to Conquest of Azeroth.
|
||||
Reborn,
|
||||
}
|
||||
|
||||
pub fn is_running(main: &Path) -> bool {
|
||||
let second = root(main);
|
||||
impl Tree {
|
||||
pub const ALL: [Tree; 2] = [Tree::Second, Tree::Reborn];
|
||||
|
||||
fn dir(self) -> &'static str {
|
||||
match self {
|
||||
Tree::Second => ".realms/secondary",
|
||||
Tree::Reborn => ".realms/reborn",
|
||||
}
|
||||
}
|
||||
|
||||
fn label(self) -> &'static str {
|
||||
match self {
|
||||
Tree::Second => "second realm",
|
||||
Tree::Reborn => "Warcraft Reborn realm",
|
||||
}
|
||||
}
|
||||
|
||||
fn mode(self, active: Mode) -> Mode {
|
||||
match self {
|
||||
Tree::Second if active == Mode::Coa => Mode::Wildcard,
|
||||
Tree::Second => Mode::Coa,
|
||||
Tree::Reborn => Mode::Reborn,
|
||||
}
|
||||
}
|
||||
|
||||
fn enabled(self, s: &RealmState) -> bool {
|
||||
match self {
|
||||
Tree::Second => s.simultaneous,
|
||||
Tree::Reborn => s.with_reborn,
|
||||
}
|
||||
}
|
||||
|
||||
fn ports(self, s: &RealmState) -> (Option<u16>, Option<u16>) {
|
||||
match self {
|
||||
Tree::Second => (s.secondary_world_port, s.secondary_ra_port),
|
||||
Tree::Reborn => (s.reborn_world_port, s.reborn_ra_port),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn tree_root(main: &Path, tree: Tree) -> PathBuf {
|
||||
main.join(tree.dir())
|
||||
}
|
||||
|
||||
/// The folder of the second realm (Wildcard next to Conquest of Azeroth).
|
||||
pub fn root(main: &Path) -> PathBuf {
|
||||
tree_root(main, Tree::Second)
|
||||
}
|
||||
|
||||
pub fn tree_running(main: &Path, tree: Tree) -> bool {
|
||||
let second = tree_root(main, tree);
|
||||
if !second.exists() {
|
||||
return false;
|
||||
}
|
||||
@@ -28,6 +82,26 @@ pub fn is_running(main: &Path) -> 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))
|
||||
}
|
||||
|
||||
fn copy_tree(from: &Path, to: &Path) -> Result<()> {
|
||||
fs::create_dir_all(to)?;
|
||||
for entry in fs::read_dir(from)? {
|
||||
@@ -55,15 +129,53 @@ fn copy_tree(from: &Path, to: &Path) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Start Wildcard together with Conquest of Azeroth.
|
||||
pub fn set_enabled(main: &Path, enabled: bool) -> Result<realms::View> {
|
||||
set_tree(main, Tree::Second, enabled)
|
||||
}
|
||||
|
||||
/// Start Warcraft Reborn together with Conquest of Azeroth.
|
||||
pub fn set_reborn_enabled(main: &Path, enabled: bool) -> Result<realms::View> {
|
||||
set_tree(main, Tree::Reborn, enabled)
|
||||
}
|
||||
|
||||
fn set_tree(main: &Path, tree: Tree, enabled: bool) -> Result<realms::View> {
|
||||
if enabled && !cfg!(windows) {
|
||||
return Err(Error::Invalid(
|
||||
"Simultaneous realms currently require Windows.".into(),
|
||||
));
|
||||
}
|
||||
if enabled {
|
||||
if realms::state(main)?.active == Mode::Reborn { return Err(Error::Invalid("Simultaneous startup supports CoA and Wildcard. Select one of these realms first.".into())); }
|
||||
if !realms::view(main)?.supported { return Err(Error::Invalid("Update the server to a build with Wildcard support first.".into())); }
|
||||
let active = realms::state(main)?.active;
|
||||
let view = realms::view(main)?;
|
||||
match tree {
|
||||
Tree::Second => {
|
||||
if active == Mode::Reborn {
|
||||
return Err(Error::Invalid(
|
||||
"Wildcard starts together with Conquest of Azeroth. Select Conquest of Azeroth first."
|
||||
.into(),
|
||||
));
|
||||
}
|
||||
if !view.supported {
|
||||
return Err(Error::Invalid(
|
||||
"Update the server to a build with Wildcard support first.".into(),
|
||||
));
|
||||
}
|
||||
}
|
||||
Tree::Reborn => {
|
||||
if active != Mode::Coa {
|
||||
return Err(Error::Invalid(
|
||||
"Warcraft Reborn starts together with Conquest of Azeroth. Select Conquest of Azeroth first."
|
||||
.into(),
|
||||
));
|
||||
}
|
||||
if !view.reborn_supported {
|
||||
return Err(Error::Invalid(
|
||||
"Update the server to a build with Warcraft Reborn support first.".into(),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
secondary_launcher(&fs::read_to_string(main.join("Scripts/manage.py"))?)?;
|
||||
}
|
||||
let status = process::observe(main, &crate::layout::read_ports(main));
|
||||
@@ -72,20 +184,21 @@ pub fn set_enabled(main: &Path, enabled: bool) -> Result<realms::View> {
|
||||
|| is_running(main)
|
||||
{
|
||||
return Err(Error::Invalid(
|
||||
"Stop both realms before changing simultaneous startup.".into(),
|
||||
"Stop all realms before changing which realms start together.".into(),
|
||||
));
|
||||
}
|
||||
let original = realms::state(main)?.active;
|
||||
if enabled && !realms::state(main)?.wildcard_created {
|
||||
realms::select(main, Mode::Wildcard)?;
|
||||
if original != Mode::Wildcard {
|
||||
realms::select(main, original)?;
|
||||
}
|
||||
if enabled {
|
||||
realms::ensure_created(main, tree.mode(realms::state(main)?.active))?;
|
||||
}
|
||||
let mut s = realms::state(main)?;
|
||||
if enabled {
|
||||
let p = crate::layout::read_ports(main);
|
||||
let mut reserved = vec![p.mysql, p.auth, p.world, p.ra];
|
||||
// Ports already saved for any other extra world stay reserved, so two worlds never get the same one.
|
||||
for other in Tree::ALL.into_iter().filter(|t| *t != tree) {
|
||||
let (world, ra) = other.ports(&s);
|
||||
reserved.extend(world.into_iter().chain(ra));
|
||||
}
|
||||
let mut choose = |saved: Option<u16>, near: u16| -> Result<u16> {
|
||||
if let Some(port) = saved.filter(|p| *p > 0 && !reserved.contains(p)) {
|
||||
reserved.push(port);
|
||||
@@ -95,31 +208,41 @@ pub fn set_enabled(main: &Path, enabled: bool) -> Result<realms::View> {
|
||||
.find(|p| {
|
||||
!reserved.contains(p) && std::net::TcpListener::bind(("127.0.0.1", *p)).is_ok()
|
||||
})
|
||||
.ok_or_else(|| Error::Invalid("No free port for the second realm.".into()))?;
|
||||
.ok_or_else(|| Error::Invalid(format!("No free port for the {}.", tree.label())))?;
|
||||
reserved.push(port);
|
||||
Ok(port)
|
||||
};
|
||||
s.secondary_world_port = Some(choose(s.secondary_world_port, p.world)?);
|
||||
s.secondary_ra_port = Some(choose(s.secondary_ra_port, p.ra)?);
|
||||
let (world, ra) = tree.ports(&s);
|
||||
let (world, ra) = (choose(world, p.world)?, choose(ra, p.ra)?);
|
||||
match tree {
|
||||
Tree::Second => {
|
||||
s.secondary_world_port = Some(world);
|
||||
s.secondary_ra_port = Some(ra);
|
||||
}
|
||||
Tree::Reborn => {
|
||||
s.reborn_world_port = Some(world);
|
||||
s.reborn_ra_port = Some(ra);
|
||||
}
|
||||
}
|
||||
}
|
||||
match tree {
|
||||
Tree::Second => s.simultaneous = enabled,
|
||||
Tree::Reborn => s.with_reborn = enabled,
|
||||
}
|
||||
s.simultaneous = enabled;
|
||||
fsx::atomic_write_json(&main.join("Settings/realm-profile.json"), &s)?;
|
||||
realms::view(main)
|
||||
}
|
||||
|
||||
fn prepare(main: &Path) -> Result<PathBuf> {
|
||||
if is_running(main) {
|
||||
return Err(Error::Invalid(
|
||||
"The second realm is still running; stop it before preparing its files.".into(),
|
||||
));
|
||||
fn prepare(main: &Path, tree: Tree) -> Result<PathBuf> {
|
||||
if tree_running(main, tree) {
|
||||
return Err(Error::Invalid(format!(
|
||||
"The {} is still running; stop it before preparing its files.",
|
||||
tree.label()
|
||||
)));
|
||||
}
|
||||
let s = realms::state(main)?;
|
||||
let mode = if s.active == Mode::Coa {
|
||||
Mode::Wildcard
|
||||
} else {
|
||||
Mode::Coa
|
||||
};
|
||||
let second = fsx::ensure_within(main, &root(main))?;
|
||||
let mode = tree.mode(s.active);
|
||||
let second = fsx::ensure_within(main, &tree_root(main, tree))?;
|
||||
for folder in ["Runtime", "BugReport", "mysql/bin"] {
|
||||
copy_tree(
|
||||
&main.join(folder),
|
||||
@@ -205,13 +328,12 @@ fn prepare(main: &Path) -> Result<PathBuf> {
|
||||
)?;
|
||||
}
|
||||
let mut cfg: serde_json::Value = fsx::read_json(&main.join("Settings/repack.json"))?;
|
||||
cfg["worldPort"] = s
|
||||
.secondary_world_port
|
||||
.ok_or_else(|| Error::Invalid("Second realm world port is missing.".into()))?
|
||||
let (world_port, ra_port) = tree.ports(&s);
|
||||
cfg["worldPort"] = world_port
|
||||
.ok_or_else(|| Error::Invalid(format!("The {} world port is missing.", tree.label())))?
|
||||
.into();
|
||||
cfg["raPort"] = s
|
||||
.secondary_ra_port
|
||||
.ok_or_else(|| Error::Invalid("Second realm console port is missing.".into()))?
|
||||
cfg["raPort"] = ra_port
|
||||
.ok_or_else(|| Error::Invalid(format!("The {} console port is missing.", tree.label())))?
|
||||
.into();
|
||||
fsx::atomic_write_json(&second.join("Settings/repack.json"), &cfg)?;
|
||||
fsx::atomic_write(
|
||||
@@ -223,6 +345,7 @@ fn prepare(main: &Path) -> Result<PathBuf> {
|
||||
&RealmState {
|
||||
active: mode,
|
||||
wildcard_created: true,
|
||||
reborn_created: true,
|
||||
..Default::default()
|
||||
},
|
||||
)?;
|
||||
@@ -247,12 +370,9 @@ fn secondary_launcher(source: &str) -> Result<String> {
|
||||
))
|
||||
}
|
||||
|
||||
pub fn start(main: &Path) -> Result<()> {
|
||||
if !realms::state(main)?.simultaneous {
|
||||
return Ok(());
|
||||
}
|
||||
if is_running(main) {
|
||||
let second = root(main);
|
||||
fn start_tree(main: &Path, tree: Tree) -> Result<()> {
|
||||
if tree_running(main, tree) {
|
||||
let second = tree_root(main, tree);
|
||||
if process::observe(&second, &crate::layout::read_ports(&second))
|
||||
.world
|
||||
.state
|
||||
@@ -260,35 +380,50 @@ pub fn start(main: &Path) -> Result<()> {
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
return Err(Error::Invalid(
|
||||
"The second realm is still starting or stopping.".into(),
|
||||
));
|
||||
return Err(Error::Invalid(format!(
|
||||
"The {} is still starting or stopping.",
|
||||
tree.label()
|
||||
)));
|
||||
}
|
||||
let second = prepare(main)?;
|
||||
let second = prepare(main, tree)?;
|
||||
let out = driver::run(&second, Verb::StartWorld)?;
|
||||
if !out.ok {
|
||||
return Err(Error::Invalid(format!(
|
||||
"The second realm did not start: {}",
|
||||
"The {} did not start: {}",
|
||||
tree.label(),
|
||||
out.output
|
||||
)));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn stop(main: &Path) -> Result<()> {
|
||||
let second = root(main);
|
||||
/// Start every extra world that is switched on.
|
||||
pub fn start(main: &Path) -> Result<()> {
|
||||
let s = realms::state(main)?;
|
||||
for tree in Tree::ALL.into_iter().filter(|t| t.enabled(&s)) {
|
||||
start_tree(main, tree)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn stop_tree(main: &Path, tree: Tree) -> Result<()> {
|
||||
let second = tree_root(main, tree);
|
||||
if !second.join("Scripts/manage.py").exists() {
|
||||
if is_running(main) {
|
||||
return Err(Error::Invalid("The running second realm's launcher is missing. The shared database was left running.".into()));
|
||||
if tree_running(main, tree) {
|
||||
return Err(Error::Invalid(format!(
|
||||
"The running {}'s launcher is missing. The shared database was left running.",
|
||||
tree.label()
|
||||
)));
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
// Its state has no auth/MySQL records: the shared database remains up until the primary world stops.
|
||||
if is_running(main) {
|
||||
if tree_running(main, tree) {
|
||||
let out = driver::run(&second, Verb::StopAll)?;
|
||||
if !out.ok || is_running(main) {
|
||||
if !out.ok || tree_running(main, tree) {
|
||||
return Err(Error::Invalid(format!(
|
||||
"The second realm could not stop; the database was left running: {}",
|
||||
"The {} could not stop; the database was left running: {}",
|
||||
tree.label(),
|
||||
out.output
|
||||
)));
|
||||
}
|
||||
@@ -296,9 +431,76 @@ pub fn stop(main: &Path) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Stop every extra world; one that fails does not keep the others running.
|
||||
pub fn stop(main: &Path) -> Result<()> {
|
||||
let mut first = None;
|
||||
for tree in Tree::ALL {
|
||||
if let Err(e) = stop_tree(main, tree) {
|
||||
first.get_or_insert(e);
|
||||
}
|
||||
}
|
||||
first.map_or(Ok(()), Err)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn every_extra_world_has_its_own_folder_realm_and_ports() {
|
||||
let mut s = RealmState::default();
|
||||
assert_eq!(Tree::Second.mode(Mode::Coa), Mode::Wildcard);
|
||||
assert_eq!(Tree::Second.mode(Mode::Wildcard), Mode::Coa);
|
||||
assert_eq!(Tree::Reborn.mode(Mode::Coa), Mode::Reborn);
|
||||
assert_ne!(Tree::Second.dir(), Tree::Reborn.dir());
|
||||
s.secondary_world_port = Some(8086);
|
||||
s.reborn_world_port = Some(8087);
|
||||
assert_eq!(Tree::Second.ports(&s).0, Some(8086));
|
||||
assert_eq!(Tree::Reborn.ports(&s).0, Some(8087));
|
||||
assert!(!Tree::Second.enabled(&s) && !Tree::Reborn.enabled(&s));
|
||||
s.with_reborn = true;
|
||||
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();
|
||||
fsx::atomic_write(
|
||||
&t.path().join("Core/worldserver.exe"),
|
||||
b"Warcraft Reborn class spells are unavailable",
|
||||
)
|
||||
.unwrap();
|
||||
fsx::atomic_write(
|
||||
&t.path().join("Settings/realm-profile.json"),
|
||||
br#"{"active":"wildcard","wildcard_created":true}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let err = set_reborn_enabled(t.path(), true).unwrap_err().to_string();
|
||||
assert!(err.contains("Select Conquest of Azeroth first"), "{err}");
|
||||
assert!(!realms::state(t.path()).unwrap().with_reborn);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn secondary_never_starts_the_shared_database() {
|
||||
let patched = secondary_launcher("def start_world(config, offset):\r\n start_mysql(config)\r\n wait_ready('world', 8086)\r\n").unwrap();
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -51,24 +51,38 @@ fn parse_counts(out: &str) -> Result<Population> {
|
||||
|
||||
/// Read-only query with the game's own database account. Requires the database to be running.
|
||||
pub fn query(root: &Path) -> Result<Population> {
|
||||
let prefix = bot_account_prefix(root).to_uppercase();
|
||||
let db = Db::from_repack(root, Account::App)?;
|
||||
query_with(&db, &prefix)
|
||||
query_with(
|
||||
&db,
|
||||
&bot_account_prefix(root),
|
||||
&crate::accounts::squid_bot_prefix(root),
|
||||
)
|
||||
}
|
||||
|
||||
/// The same counts through any database handle (a realm known by its descriptor); `prefix` is the bot accounts' name prefix, upper case.
|
||||
pub fn query_with(db: &Db, prefix: &str) -> Result<Population> {
|
||||
if prefix.is_empty() || !prefix.chars().all(|c| c.is_ascii_alphanumeric()) {
|
||||
fn counts_sql(prefix: &str, squid_prefix: &str) -> Result<String> {
|
||||
if [prefix, squid_prefix]
|
||||
.iter()
|
||||
.any(|prefix| prefix.is_empty() || !prefix.chars().all(|c| c.is_ascii_alphanumeric()))
|
||||
{
|
||||
return Err(Error::Invalid(
|
||||
"the bot account prefix is not a plain name".into(),
|
||||
));
|
||||
}
|
||||
let sql = format!(
|
||||
let prefix = prefix.to_ascii_uppercase();
|
||||
let squid_prefix = squid_prefix.to_ascii_uppercase();
|
||||
// OR counts each character once even when the two configured prefixes overlap.
|
||||
let bots =
|
||||
format!("(UPPER(a.username) LIKE '{prefix}%' OR UPPER(a.username) LIKE '{squid_prefix}%')");
|
||||
Ok(format!(
|
||||
"SELECT (SELECT COUNT(*) FROM acore_characters.characters WHERE online=1), \
|
||||
(SELECT COUNT(*) FROM acore_characters.characters c JOIN acore_auth.account a ON a.id=c.account WHERE c.online=1 AND UPPER(a.username) LIKE '{prefix}%'), \
|
||||
(SELECT COUNT(*) FROM acore_characters.characters c JOIN acore_auth.account a ON a.id=c.account WHERE UPPER(a.username) LIKE '{prefix}%');"
|
||||
);
|
||||
parse_counts(&db.query(&sql)?)
|
||||
(SELECT COUNT(*) FROM acore_characters.characters c JOIN acore_auth.account a ON a.id=c.account WHERE c.online=1 AND {bots}), \
|
||||
(SELECT COUNT(*) FROM acore_characters.characters c JOIN acore_auth.account a ON a.id=c.account WHERE {bots});"
|
||||
))
|
||||
}
|
||||
|
||||
/// Read both supported bot populations, including SQUID random bots, without changing realm data.
|
||||
pub fn query_with(db: &Db, prefix: &str, squid_prefix: &str) -> Result<Population> {
|
||||
parse_counts(&db.query(&counts_sql(prefix, squid_prefix)?)?)
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
@@ -174,6 +188,109 @@ pub fn sizes(h: &Hardware) -> Vec<SizeOption> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
// Execute the production SELECT against disposable in-memory schemas. No
|
||||
// server connection or credentials are needed for these regression cases.
|
||||
fn fixture_counts(
|
||||
prefix: &str,
|
||||
squid_prefix: &str,
|
||||
accounts: &[(&str, u32, u32)],
|
||||
) -> Population {
|
||||
let db = rusqlite::Connection::open_in_memory().unwrap();
|
||||
db.execute_batch(
|
||||
"ATTACH DATABASE ':memory:' AS acore_auth;
|
||||
ATTACH DATABASE ':memory:' AS acore_characters;
|
||||
CREATE TABLE acore_auth.account (id INTEGER PRIMARY KEY, username TEXT);
|
||||
CREATE TABLE acore_characters.characters (account INTEGER, online INTEGER);",
|
||||
)
|
||||
.unwrap();
|
||||
for (index, (name, online, offline)) in accounts.iter().enumerate() {
|
||||
db.execute(
|
||||
"INSERT INTO acore_auth.account VALUES (?1, ?2)",
|
||||
rusqlite::params![index as u32, name],
|
||||
)
|
||||
.unwrap();
|
||||
for flag in std::iter::repeat_n(1, *online as usize)
|
||||
.chain(std::iter::repeat_n(0, *offline as usize))
|
||||
{
|
||||
db.execute(
|
||||
"INSERT INTO acore_characters.characters VALUES (?1, ?2)",
|
||||
rusqlite::params![index as u32, flag],
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
let changes = db.total_changes();
|
||||
let (total, bots, all): (u32, u32, u32) = db
|
||||
.query_row(&counts_sql(prefix, squid_prefix).unwrap(), [], |row| {
|
||||
Ok((row.get(0)?, row.get(1)?, row.get(2)?))
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
db.total_changes(),
|
||||
changes,
|
||||
"population queries must only read"
|
||||
);
|
||||
parse_counts(&format!("{total}\t{bots}\t{all}")).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn random_bots_are_not_advertised_as_real_players() {
|
||||
let p = fixture_counts(
|
||||
"CoaBotHost",
|
||||
"rndbot",
|
||||
&[("RNDBOT1", 171, 1), ("CoaBotHost1", 2, 3), ("PLAYER", 2, 1)],
|
||||
);
|
||||
assert_eq!(
|
||||
(
|
||||
p.online_total,
|
||||
p.players_online,
|
||||
p.bots_online,
|
||||
p.bots_total
|
||||
),
|
||||
(175, 2, 173, 177)
|
||||
);
|
||||
let empty = fixture_counts("CoaBotHost", "rndbot", &[]);
|
||||
assert_eq!(
|
||||
(empty.online_total, empty.bots_online, empty.bots_total),
|
||||
(0, 0, 0)
|
||||
);
|
||||
let humans = fixture_counts("CoaBotHost", "rndbot", &[("PLAYER", 3, 1)]);
|
||||
assert_eq!((humans.players_online, humans.bots_online), (3, 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn population_uses_both_configured_prefixes_and_counts_overlaps_once() {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let configs = root.path().join("Core/configs/modules");
|
||||
std::fs::create_dir_all(&configs).unwrap();
|
||||
std::fs::write(
|
||||
configs.join("mod_coa_playerbots.conf"),
|
||||
"CoaBots.RandomSpawn.AccountPrefix = \"Companion\"\n",
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::write(
|
||||
configs.join("playerbots.conf"),
|
||||
"AiPlayerbot.RandomBotAccountPrefix = \"Random\"\n",
|
||||
)
|
||||
.unwrap();
|
||||
let p = fixture_counts(
|
||||
&bot_account_prefix(root.path()),
|
||||
&crate::accounts::squid_bot_prefix(root.path()),
|
||||
&[("COMPANION1", 2, 0), ("RANDOM1", 3, 1), ("PLAYER", 1, 0)],
|
||||
);
|
||||
assert_eq!((p.players_online, p.bots_online, p.bots_total), (1, 5, 6));
|
||||
let p = fixture_counts(
|
||||
"Bot",
|
||||
"BotRandom",
|
||||
&[("BOTRANDOM1", 3, 1), ("BOT1", 2, 0), ("PLAYER", 1, 0)],
|
||||
);
|
||||
assert_eq!((p.players_online, p.bots_online, p.bots_total), (1, 5, 6));
|
||||
for unsafe_prefix in ["", "x' OR 1=1 --", "bot_", "bot%"] {
|
||||
assert!(counts_sql(unsafe_prefix, "rndbot").is_err());
|
||||
assert!(counts_sql("CoaBotHost", unsafe_prefix).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
#[test]
|
||||
fn memory_is_read_from_proc_meminfo() {
|
||||
|
||||
@@ -456,8 +456,9 @@ mod tests {
|
||||
ruleset: Ruleset::Coa,
|
||||
character_formats: ContentProfile::manager_formats(),
|
||||
online_import_job_formats: jobs.to_vec(),
|
||||
session_protocol: 2,
|
||||
collection_protocol: 2,
|
||||
session_protocol: crate::portable::session::protocol::SESSION_PROTOCOL_VERSION,
|
||||
collection_protocol:
|
||||
crate::portable::session::protocol::COLLECTION_PROTOCOL_VERSION,
|
||||
features: features.iter().copied().collect(),
|
||||
collection_kinds: ["coa:appearance".to_string(), "coa:vanity".to_string()]
|
||||
.into_iter()
|
||||
|
||||
@@ -64,6 +64,11 @@ pub enum PortableError {
|
||||
RealmRead(String),
|
||||
#[error("the realm database is a {found} realm but a {expected} character was requested")]
|
||||
WrongRealm { expected: String, found: String },
|
||||
#[error("ruleset mismatch: character has {character:?}, realm expects {realm:?}")]
|
||||
RulesetMismatch {
|
||||
character: super::model::Ruleset,
|
||||
realm: super::model::Ruleset,
|
||||
},
|
||||
|
||||
#[error("character {character} is already on server {server_id}")]
|
||||
AlreadyOnRealm {
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
-- Schema 9: Multi-ruleset partitioned collections and reborn ruleset support.
|
||||
-- 1. Partition collection table by (profile_id, ruleset, kind)
|
||||
CREATE TABLE collection_new (
|
||||
profile_id TEXT NOT NULL REFERENCES profile(profile_id),
|
||||
ruleset TEXT NOT NULL CHECK (ruleset IN ('coa', 'wildcard', 'reborn')),
|
||||
kind TEXT NOT NULL,
|
||||
collection_revision INTEGER NOT NULL CHECK (collection_revision >= 1),
|
||||
collection_hash BLOB NOT NULL CHECK (length(collection_hash) = 32),
|
||||
format_version INTEGER NOT NULL,
|
||||
item_count INTEGER NOT NULL,
|
||||
updated_at TEXT NOT NULL,
|
||||
payload BLOB NOT NULL,
|
||||
PRIMARY KEY (profile_id, ruleset, kind)
|
||||
) STRICT;
|
||||
|
||||
INSERT INTO collection_new (profile_id, ruleset, kind, collection_revision, collection_hash, format_version, item_count, updated_at, payload)
|
||||
SELECT profile_id, 'coa', kind, collection_revision, collection_hash, format_version, item_count, updated_at, payload
|
||||
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);
|
||||
@@ -0,0 +1,26 @@
|
||||
-- 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);
|
||||
@@ -23,8 +23,8 @@ pub mod snapshot;
|
||||
pub mod store;
|
||||
pub mod versions;
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) mod fixtures;
|
||||
#[cfg(any(test, feature = "testkit"))]
|
||||
pub mod fixtures;
|
||||
|
||||
pub use collection::IdSet;
|
||||
pub use error::{PortableError, Result};
|
||||
|
||||
@@ -59,12 +59,13 @@ pub mod limits {
|
||||
|
||||
use limits::*;
|
||||
|
||||
/// A character belongs to exactly one ruleset for its whole life; CoA and Wildcard never mix.
|
||||
/// A character belongs to exactly one ruleset for its whole life; rulesets never mix.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum Ruleset {
|
||||
Coa,
|
||||
Wildcard,
|
||||
Reborn,
|
||||
}
|
||||
|
||||
impl Ruleset {
|
||||
@@ -72,23 +73,99 @@ impl Ruleset {
|
||||
match self {
|
||||
Ruleset::Coa => "coa",
|
||||
Ruleset::Wildcard => "wildcard",
|
||||
Ruleset::Reborn => "reborn",
|
||||
}
|
||||
}
|
||||
pub fn display_name(self) -> &'static str {
|
||||
match self {
|
||||
Ruleset::Coa => "Conquest of Azeroth",
|
||||
Ruleset::Wildcard => "Wildcard",
|
||||
Ruleset::Reborn => "Warcraft Reborn",
|
||||
}
|
||||
}
|
||||
pub fn realm_id(self) -> u32 {
|
||||
match self {
|
||||
Ruleset::Coa => 1,
|
||||
Ruleset::Wildcard => 2,
|
||||
Ruleset::Reborn => 3,
|
||||
}
|
||||
}
|
||||
pub fn schema(self, kind: &str) -> Result<&'static str> {
|
||||
let mode: crate::realms::Mode = self.into();
|
||||
mode.schema(kind)
|
||||
.map_err(|e| PortableError::Invalid(e.to_string()))
|
||||
}
|
||||
pub fn collection_namespace(self) -> &'static str {
|
||||
match self {
|
||||
Ruleset::Coa => "coa",
|
||||
Ruleset::Wildcard => "wildcard",
|
||||
Ruleset::Reborn => "reborn",
|
||||
}
|
||||
}
|
||||
pub fn parse(s: &str) -> Result<Self> {
|
||||
match s {
|
||||
"coa" => Ok(Ruleset::Coa),
|
||||
"wildcard" => Ok(Ruleset::Wildcard),
|
||||
"reborn" => Ok(Ruleset::Reborn),
|
||||
other => Err(PortableError::Invalid(format!("unknown ruleset {other:?}"))),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::str::FromStr for Ruleset {
|
||||
type Err = PortableError;
|
||||
|
||||
fn from_str(s: &str) -> Result<Self> {
|
||||
Self::parse(s)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for Ruleset {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str(self.as_str())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<crate::realms::Mode> for Ruleset {
|
||||
fn from(m: crate::realms::Mode) -> Self {
|
||||
match m {
|
||||
crate::realms::Mode::Coa => Ruleset::Coa,
|
||||
crate::realms::Mode::Wildcard => Ruleset::Wildcard,
|
||||
crate::realms::Mode::Reborn => Ruleset::Reborn,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Ruleset> for crate::realms::Mode {
|
||||
fn from(r: Ruleset) -> Self {
|
||||
match r {
|
||||
Ruleset::Coa => crate::realms::Mode::Coa,
|
||||
Ruleset::Wildcard => crate::realms::Mode::Wildcard,
|
||||
Ruleset::Reborn => crate::realms::Mode::Reborn,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<coa_registry_proto::caps::Ruleset> for Ruleset {
|
||||
fn from(r: coa_registry_proto::caps::Ruleset) -> Self {
|
||||
match r {
|
||||
coa_registry_proto::caps::Ruleset::Coa => Ruleset::Coa,
|
||||
coa_registry_proto::caps::Ruleset::Wildcard => Ruleset::Wildcard,
|
||||
coa_registry_proto::caps::Ruleset::Reborn => Ruleset::Reborn,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Ruleset> for coa_registry_proto::caps::Ruleset {
|
||||
fn from(r: Ruleset) -> Self {
|
||||
match r {
|
||||
Ruleset::Coa => coa_registry_proto::caps::Ruleset::Coa,
|
||||
Ruleset::Wildcard => coa_registry_proto::caps::Ruleset::Wildcard,
|
||||
Ruleset::Reborn => coa_registry_proto::caps::Ruleset::Reborn,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Binary data as base64 text in the serialised form.
|
||||
#[derive(Clone, PartialEq, Eq, Default)]
|
||||
pub struct Bytes(pub Vec<u8>);
|
||||
@@ -806,3 +883,21 @@ impl PortableCharacter {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn schema_mapping_never_falls_back_on_unknown_database_kind() {
|
||||
for ruleset in [Ruleset::Coa, Ruleset::Wildcard, Ruleset::Reborn] {
|
||||
assert!(ruleset.schema("auth").is_ok());
|
||||
assert!(ruleset.schema("characters").is_ok());
|
||||
assert!(ruleset.schema("world").is_ok());
|
||||
assert!(ruleset.schema("characters_extra").is_err());
|
||||
assert!(ruleset.schema("unknown").is_err());
|
||||
assert!(ruleset.schema("").is_err());
|
||||
assert!(ruleset.schema("acore_characters").is_err());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -11,7 +11,6 @@ use crate::db::Db;
|
||||
|
||||
use super::super::collection::IdSet;
|
||||
use super::super::error::{PortableError, Result};
|
||||
use super::super::model::Ruleset;
|
||||
use super::knowledge::{is_bank_vanity_item, RealmKnowledge};
|
||||
use super::plan::FAIL;
|
||||
use super::ruleset_of;
|
||||
@@ -22,8 +21,12 @@ const CHUNK: usize = 2_000;
|
||||
/// `(table, id column, columns written)` of a collection kind.
|
||||
fn layout(kind: &str) -> Result<(&'static str, &'static str, bool)> {
|
||||
match kind {
|
||||
"coa:appearance" => Ok(("account_appearance_collection", "appearance_id", true)),
|
||||
"coa:vanity" => Ok(("account_vanity_collection", "item_id", false)),
|
||||
"coa:appearance" | "wildcard:appearance" | "reborn:appearance" => {
|
||||
Ok(("account_appearance_collection", "appearance_id", true))
|
||||
}
|
||||
"coa:vanity" | "wildcard:vanity" | "reborn:vanity" => {
|
||||
Ok(("account_vanity_collection", "item_id", false))
|
||||
}
|
||||
other => Err(PortableError::Invalid(format!(
|
||||
"collection kind {other:?} is not carried"
|
||||
))),
|
||||
@@ -34,11 +37,12 @@ fn realm_error(e: crate::Error) -> PortableError {
|
||||
PortableError::RealmRead(e.to_string())
|
||||
}
|
||||
|
||||
fn coa_only(db: &Db) -> Result<()> {
|
||||
if ruleset_of(db)? != Ruleset::Coa {
|
||||
return Err(PortableError::Invalid(
|
||||
"collections are carried for CoA realms only (Wildcard transfer is disabled)".into(),
|
||||
));
|
||||
fn check_ruleset(db: &Db, kind: &str) -> Result<()> {
|
||||
let r = ruleset_of(db)?;
|
||||
if !crate::portable::session::protocol::carried_kind_for(kind, r) {
|
||||
return Err(PortableError::Invalid(format!(
|
||||
"collection kind {kind:?} does not belong to realm ruleset {r:?}"
|
||||
)));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -62,7 +66,7 @@ pub fn account_of(db: &Db, local_guid: u32) -> Result<Option<u32>> {
|
||||
|
||||
/// Count, maximum, sum and checksum of the account's rows of this kind: one cheap aggregate over the primary key.
|
||||
pub fn fingerprint(db: &Db, account: u32, kind: &str) -> Result<String> {
|
||||
coa_only(db)?;
|
||||
check_ruleset(db, kind)?;
|
||||
let (table, column, _) = layout(kind)?;
|
||||
let out = db
|
||||
.query(&format!("SELECT COUNT(*), IFNULL(MAX(`{column}`), 0), IFNULL(SUM(`{column}`), 0), IFNULL(BIT_XOR(CRC32(`{column}`)), 0) FROM acore_characters.`{table}` WHERE `account_id` = {account}"))
|
||||
@@ -82,7 +86,7 @@ pub fn fingerprint(db: &Db, account: u32, kind: &str) -> Result<String> {
|
||||
|
||||
/// The ids of the account in this realm, without the bank vanity items.
|
||||
pub fn read_set(db: &Db, account: u32, kind: &str) -> Result<IdSet> {
|
||||
coa_only(db)?;
|
||||
check_ruleset(db, kind)?;
|
||||
let (table, column, _) = layout(kind)?;
|
||||
let out = db.query(&format!("SELECT `{column}` FROM acore_characters.`{table}` WHERE `account_id` = {account} ORDER BY `{column}`")).map_err(realm_error)?;
|
||||
let mut ids = Vec::new();
|
||||
@@ -91,7 +95,9 @@ pub fn read_set(db: &Db, account: u32, kind: &str) -> Result<IdSet> {
|
||||
.trim()
|
||||
.parse()
|
||||
.map_err(|_| PortableError::CorruptSnapshot(format!("{line:?} is not an id")))?;
|
||||
if kind == "coa:vanity" && is_bank_vanity_item(id) {
|
||||
if (kind == "coa:vanity" || kind == "wildcard:vanity" || kind == "reborn:vanity")
|
||||
&& is_bank_vanity_item(id)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
ids.push(id);
|
||||
@@ -117,21 +123,21 @@ pub fn apply_set(
|
||||
canonical: &IdSet,
|
||||
knowledge: &RealmKnowledge,
|
||||
) -> Result<Applied> {
|
||||
coa_only(db)?;
|
||||
check_ruleset(db, kind)?;
|
||||
let (table, column, has_source) = layout(kind)?;
|
||||
let known = |id: u32| match kind {
|
||||
"coa:appearance" => knowledge.knows_appearance(id),
|
||||
"coa:appearance" | "wildcard:appearance" | "reborn:appearance" => {
|
||||
knowledge.knows_appearance(id)
|
||||
}
|
||||
_ => knowledge.knows_vanity(id) && !is_bank_vanity_item(id),
|
||||
};
|
||||
let held = read_set(db, account, kind)?;
|
||||
let mut applied = Applied::default();
|
||||
let mut wanted = Vec::new();
|
||||
for id in canonical
|
||||
.ids()
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|id| !(kind == "coa:vanity" && is_bank_vanity_item(*id)))
|
||||
{
|
||||
for id in canonical.ids().iter().copied().filter(|id| {
|
||||
!((kind == "coa:vanity" || kind == "wildcard:vanity" || kind == "reborn:vanity")
|
||||
&& is_bank_vanity_item(*id))
|
||||
}) {
|
||||
if !known(id) {
|
||||
applied.unknown += 1;
|
||||
} else if held.contains(id) {
|
||||
|
||||
@@ -168,9 +168,11 @@ fn account_collections_are_read_cheaply_unioned_and_written_without_duplicates_o
|
||||
let (mut store, _) = fresh_store();
|
||||
let profile = store.default_profile().unwrap();
|
||||
store
|
||||
.merge_collection(profile, APPEARANCE, &wardrobe)
|
||||
.merge_collection(profile, Ruleset::Coa, APPEARANCE, &wardrobe)
|
||||
.unwrap();
|
||||
store
|
||||
.merge_collection(profile, Ruleset::Coa, VANITY, &vanity)
|
||||
.unwrap();
|
||||
store.merge_collection(profile, VANITY, &vanity).unwrap();
|
||||
let fingerprint_a = fingerprint(&r.a, 5001, APPEARANCE).unwrap();
|
||||
assert_eq!(
|
||||
fingerprint(&r.a, 5001, APPEARANCE).unwrap(),
|
||||
@@ -331,10 +333,20 @@ fn the_result_comes_back_to_realm_a_unchanged_gameplay_and_complete_collections(
|
||||
reconcile_session(&r.b, &mut store, id, B, true, None).unwrap();
|
||||
for kind in [APPEARANCE, VANITY] {
|
||||
store
|
||||
.merge_collection(profile, kind, &read_set(&r.b, ACCOUNT, kind).unwrap())
|
||||
.merge_collection(
|
||||
profile,
|
||||
Ruleset::Coa,
|
||||
kind,
|
||||
&read_set(&r.b, ACCOUNT, kind).unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
store
|
||||
.merge_collection(profile, kind, &read_set(&r.a, 5001, kind).unwrap())
|
||||
.merge_collection(
|
||||
profile,
|
||||
Ruleset::Coa,
|
||||
kind,
|
||||
&read_set(&r.a, 5001, kind).unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
@@ -343,7 +355,10 @@ fn the_result_comes_back_to_realm_a_unchanged_gameplay_and_complete_collections(
|
||||
let updated =
|
||||
update_realm_character(&r.a, &mut store, id, "realm-a", &options(a_known.clone())).unwrap();
|
||||
assert!(updated.updated, "{updated:?}");
|
||||
let (_, canonical_wardrobe) = store.collection(profile, APPEARANCE).unwrap().unwrap();
|
||||
let (_, canonical_wardrobe) = store
|
||||
.collection(profile, Ruleset::Coa, APPEARANCE)
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let applied = apply_set(&r.a, 5001, APPEARANCE, &canonical_wardrobe, &a_known).unwrap();
|
||||
assert_eq!(applied.inserted, 1, "only 1300 is new to A");
|
||||
assert_eq!(
|
||||
|
||||
@@ -55,7 +55,7 @@ pub fn ruleset_of(db: &Db) -> Result<Ruleset> {
|
||||
match db.realm() {
|
||||
Mode::Coa => Ok(Ruleset::Coa),
|
||||
Mode::Wildcard => Ok(Ruleset::Wildcard),
|
||||
Mode::Reborn => Err(PortableError::Invalid("Portable characters are not supported on Warcraft Reborn realms yet.".into())),
|
||||
Mode::Reborn => Ok(Ruleset::Reborn),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -14,7 +14,9 @@ use super::super::extension::{
|
||||
};
|
||||
use super::super::ids::CharacterId;
|
||||
use super::super::model::PortableCharacter;
|
||||
use super::super::session::protocol::{COLLECTION_KINDS, PROTOCOL_VERSION};
|
||||
use super::super::session::protocol::{
|
||||
collection_kinds, COLLECTION_PROTOCOL_VERSION, SESSION_PROTOCOL_VERSION,
|
||||
};
|
||||
use super::super::store::Store;
|
||||
use super::import::ImportOptions;
|
||||
use super::script::SchemaProbe;
|
||||
@@ -97,13 +99,16 @@ pub fn assemble(
|
||||
online_import_job_formats: core
|
||||
.map(|c| c.portable.job_formats.clone())
|
||||
.unwrap_or_default(),
|
||||
session_protocol: PROTOCOL_VERSION,
|
||||
collection_protocol: PROTOCOL_VERSION,
|
||||
session_protocol: SESSION_PROTOCOL_VERSION,
|
||||
collection_protocol: COLLECTION_PROTOCOL_VERSION,
|
||||
features,
|
||||
collection_kinds: if probe.has("account_appearance_collection")
|
||||
&& probe.has("account_vanity_collection")
|
||||
{
|
||||
COLLECTION_KINDS.iter().map(|k| k.to_string()).collect()
|
||||
collection_kinds(ruleset_of(db)?)
|
||||
.iter()
|
||||
.map(|k| k.to_string())
|
||||
.collect()
|
||||
} else {
|
||||
Default::default()
|
||||
},
|
||||
|
||||
@@ -729,7 +729,7 @@ fn the_wildcard_ruleset_uses_its_own_namespace_and_quarantines_wildcard_state()
|
||||
let wc_db = Db::with_tools(std::path::PathBuf::new(), 1, "root", "x", Mode::Wildcard);
|
||||
let coa_db = Db::with_tools(std::path::PathBuf::new(), 1, "root", "x", Mode::Coa);
|
||||
let reborn_db = Db::with_tools(std::path::PathBuf::new(), 1, "root", "x", Mode::Reborn);
|
||||
assert!(ruleset_of(&reborn_db).is_err());
|
||||
assert_eq!(ruleset_of(&reborn_db).unwrap(), Ruleset::Reborn);
|
||||
assert_eq!(
|
||||
(ruleset_of(&wc_db).unwrap(), ruleset_of(&coa_db).unwrap()),
|
||||
(Ruleset::Wildcard, Ruleset::Coa)
|
||||
|
||||
@@ -112,6 +112,7 @@ pub struct RealmAccess {
|
||||
pub job_dir: PathBuf,
|
||||
pub data_dir: PathBuf,
|
||||
pub game_server_users: Vec<String>,
|
||||
pub mode: Option<crate::realms::Mode>,
|
||||
source: Source,
|
||||
}
|
||||
|
||||
@@ -198,6 +199,7 @@ impl RealmAccess {
|
||||
job_dir: PathBuf::from(&d.job_dir),
|
||||
data_dir: PathBuf::from(&d.data_dir),
|
||||
game_server_users: d.game_server_users.clone(),
|
||||
mode: None,
|
||||
source: Source::Descriptor(Box::new(d)),
|
||||
})
|
||||
}
|
||||
@@ -219,6 +221,7 @@ impl RealmAccess {
|
||||
job_dir: root.join("Core").join("PortableImport"),
|
||||
data_dir: root.join("Data"),
|
||||
game_server_users: default_game_users(),
|
||||
mode: None,
|
||||
source: Source::Install {
|
||||
root: root.to_path_buf(),
|
||||
},
|
||||
@@ -228,20 +231,32 @@ impl RealmAccess {
|
||||
/// The database with full rights (imports and updates of a stopped realm, reading characters).
|
||||
pub fn db(&self) -> Result<Db> {
|
||||
match &self.source {
|
||||
Source::Install { root } => Db::from_repack(root, Account::Admin),
|
||||
Source::Install { root } => {
|
||||
let mut d = Db::from_repack(root, Account::Admin)?;
|
||||
if let Some(m) = self.mode {
|
||||
d = d.for_realm(m);
|
||||
}
|
||||
Ok(d)
|
||||
}
|
||||
Source::Descriptor(d) => Ok(Db::with_tools(
|
||||
PathBuf::from(&d.mysql_bin),
|
||||
d.db_port,
|
||||
leak(&d.db_user),
|
||||
d.db_password.expose(),
|
||||
Mode::Coa,
|
||||
self.mode.unwrap_or(Mode::Coa),
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
/// 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(root),
|
||||
Source::Install { root } => Ra::connect(&self.world_folder(root)),
|
||||
Source::Descriptor(d) => Ra::connect_to(d.ra_port, &d.ra_user, d.ra_password.expose()),
|
||||
}
|
||||
}
|
||||
@@ -252,7 +267,7 @@ impl RealmAccess {
|
||||
|
||||
pub fn ports(&self) -> (Option<u16>, u16) {
|
||||
match &self.source {
|
||||
Source::Install { root } => (None, read_ports(root).ra),
|
||||
Source::Install { root } => (None, read_ports(&self.world_folder(root)).ra),
|
||||
Source::Descriptor(d) => (Some(d.db_port), d.ra_port),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -31,6 +31,8 @@ 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;
|
||||
@@ -136,6 +138,7 @@ struct Saved {
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ClaimBundle {
|
||||
pub character_id: CharacterId,
|
||||
pub ruleset: super::super::model::Ruleset,
|
||||
pub payload: Vec<u8>,
|
||||
pub content_hash: [u8; 32],
|
||||
pub collections: BTreeMap<String, Vec<u32>>,
|
||||
@@ -181,6 +184,16 @@ pub fn class_name(class: &str) -> String {
|
||||
.and_then(|n| n.parse().ok())
|
||||
.unwrap_or(0);
|
||||
match id {
|
||||
1 => "Warrior",
|
||||
2 => "Paladin",
|
||||
3 => "Hunter",
|
||||
4 => "Rogue",
|
||||
5 => "Priest",
|
||||
6 => "Death Knight",
|
||||
7 => "Shaman",
|
||||
8 => "Mage",
|
||||
9 => "Warlock",
|
||||
11 => "Druid",
|
||||
12 => "Barbarian",
|
||||
13 => "Witch Doctor",
|
||||
14 => "Felsworn",
|
||||
@@ -363,11 +376,26 @@ impl PortableService {
|
||||
pub fn reload_realms(&mut self) {
|
||||
let (descriptors, broken) = access::load_descriptors(&self.dir.join("realms"));
|
||||
self.broken_descriptors = broken;
|
||||
let mut realms: Vec<RealmAccess> = self
|
||||
.installs
|
||||
.iter()
|
||||
.map(|(id, root)| RealmAccess::from_install(id, root))
|
||||
.collect();
|
||||
let mut realms: Vec<RealmAccess> = Vec::new();
|
||||
for (id, root) in &self.installs {
|
||||
realms.push(RealmAccess::from_install(id, root));
|
||||
if let Ok(state) = crate::realms::state(root) {
|
||||
if state.wildcard_created {
|
||||
let mut wc = RealmAccess::from_install(id, root);
|
||||
wc.id = format!("srv-{id}:wildcard");
|
||||
wc.name = format!("{} — Wildcard", wc.name);
|
||||
wc.mode = Some(crate::realms::Mode::Wildcard);
|
||||
realms.push(wc);
|
||||
}
|
||||
if state.reborn_created {
|
||||
let mut rb = RealmAccess::from_install(id, root);
|
||||
rb.id = format!("srv-{id}:reborn");
|
||||
rb.name = format!("{} — Warcraft Reborn", rb.name);
|
||||
rb.mode = Some(crate::realms::Mode::Reborn);
|
||||
realms.push(rb);
|
||||
}
|
||||
}
|
||||
}
|
||||
for d in descriptors {
|
||||
match RealmAccess::from_descriptor(d) {
|
||||
Ok(a) if !realms.iter().any(|r| r.id == a.id) => realms.push(a),
|
||||
@@ -414,10 +442,10 @@ impl PortableService {
|
||||
}
|
||||
|
||||
fn access(&self, id: &str) -> Res<RealmAccess> {
|
||||
self.realms
|
||||
.iter()
|
||||
.find(|r| r.id == id)
|
||||
.cloned()
|
||||
if let Some(r) = self.realms.iter().find(|r| r.id == id) {
|
||||
return Ok(r.clone());
|
||||
}
|
||||
crate::realm_registry::advert::find_access(&self.dir.join("realms"), &self.installs, id)
|
||||
.ok_or_else(|| fail("realm_missing", "That realm is not known to this Manager."))
|
||||
}
|
||||
|
||||
@@ -703,6 +731,12 @@ 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| {
|
||||
@@ -715,9 +749,9 @@ impl PortableService {
|
||||
)
|
||||
})
|
||||
.cloned();
|
||||
let status = active
|
||||
.as_ref()
|
||||
.map(|a| a.status)
|
||||
let status = remote_active
|
||||
.then_some(PlayStatus::Syncing)
|
||||
.or_else(|| active.as_ref().map(|a| a.status))
|
||||
.or_else(|| {
|
||||
copies
|
||||
.iter()
|
||||
@@ -728,6 +762,7 @@ impl PortableService {
|
||||
characters.push(CharacterView {
|
||||
id: c.character_id.to_string(),
|
||||
name: c.name,
|
||||
ruleset: c.ruleset,
|
||||
class_name: class_name(&c.class),
|
||||
race: c.race,
|
||||
level: c.level,
|
||||
@@ -1291,6 +1326,11 @@ 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)?
|
||||
@@ -1304,6 +1344,25 @@ 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)?;
|
||||
}
|
||||
@@ -1356,6 +1415,7 @@ impl PortableService {
|
||||
.map_err(|e| fail("realm_offline", e.to_string()))?;
|
||||
let list =
|
||||
realm::inspect_characters(&db).map_err(|e| fail("realm_offline", e.to_string()))?;
|
||||
let realm_ruleset = realm::ruleset_of(&db)?;
|
||||
let mut out = Vec::new();
|
||||
for c in list {
|
||||
if self.host.find_by_local(realm_id, c.local_guid)?.is_some() {
|
||||
@@ -1364,7 +1424,7 @@ impl PortableService {
|
||||
out.push(LocalCharacterView {
|
||||
token: c.local_guid,
|
||||
name: c.name.clone(),
|
||||
class_name: class_name(&format!("coa:class:{}", c.class)),
|
||||
class_name: class_name(&format!("{}:class:{}", realm_ruleset.as_str(), c.class)),
|
||||
level: c.level,
|
||||
account: c.username.clone().unwrap_or_default(),
|
||||
eligible: c.eligible(),
|
||||
@@ -1438,18 +1498,18 @@ impl PortableService {
|
||||
let model = self.host.load_current(character_id)?;
|
||||
let encoded = super::super::snapshot::encode(&model)?;
|
||||
let mut collections = BTreeMap::new();
|
||||
if realm::ruleset_of(&db)? == super::super::model::Ruleset::Coa {
|
||||
if let Some(account) = realm::collections::account_of(&db, local_guid)? {
|
||||
for kind in ["coa:appearance", "coa:vanity"] {
|
||||
if let Ok(set) = realm::collections::read_set(&db, account, kind) {
|
||||
collections.insert(kind.to_string(), set.ids().to_vec());
|
||||
}
|
||||
let realm_ruleset = realm::ruleset_of(&db)?;
|
||||
if let Some(account) = realm::collections::account_of(&db, local_guid)? {
|
||||
for kind in super::super::session::protocol::collection_kinds(realm_ruleset) {
|
||||
if let Ok(set) = realm::collections::read_set(&db, account, kind) {
|
||||
collections.insert(kind.to_string(), set.ids().to_vec());
|
||||
}
|
||||
}
|
||||
}
|
||||
self.publish();
|
||||
Ok(ClaimBundle {
|
||||
character_id,
|
||||
ruleset: model.ruleset,
|
||||
payload: encoded.payload,
|
||||
content_hash: encoded.content_hash,
|
||||
collections,
|
||||
@@ -1473,17 +1533,25 @@ impl PortableService {
|
||||
"The character data does not belong to the character that was claimed.",
|
||||
));
|
||||
}
|
||||
let ruleset = model.ruleset;
|
||||
for kind in collections.keys() {
|
||||
if !super::super::session::protocol::carried_kind_for(kind, ruleset) {
|
||||
return Err(fail(
|
||||
"incompatible",
|
||||
format!("Foreign collection kind {kind:?} in {ruleset} claim"),
|
||||
));
|
||||
}
|
||||
}
|
||||
if self.owner.character(character_id).is_err() {
|
||||
self.owner
|
||||
.create_character_with_id(self.owner_profile, model, realm_id)?;
|
||||
}
|
||||
for (kind, ids) in collections {
|
||||
if !matches!(kind.as_str(), "coa:appearance" | "coa:vanity") {
|
||||
continue;
|
||||
if super::super::session::protocol::carried_kind_for(kind, ruleset) {
|
||||
let set = super::super::collection::IdSet::from_ids(ids.iter().copied())?;
|
||||
self.owner
|
||||
.merge_collection(self.owner_profile, ruleset, kind, &set)?;
|
||||
}
|
||||
let set = super::super::collection::IdSet::from_ids(ids.iter().copied())?;
|
||||
self.owner
|
||||
.merge_collection(self.owner_profile, kind, &set)?;
|
||||
}
|
||||
self.publish();
|
||||
self.state()
|
||||
@@ -1499,13 +1567,17 @@ impl PortableService {
|
||||
let model = self.owner.load_current(cid)?;
|
||||
let encoded = super::super::snapshot::encode(&model)?;
|
||||
let mut collections = BTreeMap::new();
|
||||
for kind in ["coa:appearance", "coa:vanity"] {
|
||||
if let Ok(Some((_, set))) = self.owner.collection(self.owner_profile, kind) {
|
||||
for kind in super::super::session::protocol::collection_kinds(model.ruleset) {
|
||||
if let Ok(Some((_, set))) =
|
||||
self.owner
|
||||
.collection(self.owner_profile, model.ruleset, kind)
|
||||
{
|
||||
collections.insert(kind.to_string(), set.ids().to_vec());
|
||||
}
|
||||
}
|
||||
Ok(ClaimBundle {
|
||||
character_id: cid,
|
||||
ruleset: model.ruleset,
|
||||
payload: encoded.payload,
|
||||
content_hash: encoded.content_hash,
|
||||
collections,
|
||||
@@ -1591,40 +1663,75 @@ impl PortableService {
|
||||
let opts = self.options(&access, &caps);
|
||||
|
||||
// Preflight compatibility check before ANY mutation
|
||||
let db_ruleset = super::super::realm::ruleset_of(&db)?;
|
||||
if model.ruleset != db_ruleset {
|
||||
return Err(fail(
|
||||
"incompatible",
|
||||
"Character ruleset does not match realm database ruleset.",
|
||||
));
|
||||
}
|
||||
let caps_ruleset: crate::portable::model::Ruleset = caps.content.ruleset;
|
||||
if model.ruleset != caps_ruleset {
|
||||
return Err(fail(
|
||||
"incompatible",
|
||||
"Character ruleset does not match realm capability ruleset.",
|
||||
));
|
||||
}
|
||||
|
||||
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.",
|
||||
));
|
||||
}
|
||||
|
||||
// Install or advance copy in host store
|
||||
self.host
|
||||
.host_install_copy(self.host_profile, &model, params.revision, "remote")?;
|
||||
|
||||
// Monotonic union of collections
|
||||
for (kind, ids) in ¶ms.collections {
|
||||
if matches!(kind.as_str(), "coa:appearance" | "coa:vanity") {
|
||||
if let Ok(set) = super::super::collection::IdSet::from_ids(ids.iter().copied()) {
|
||||
let _ = self.host.merge_collection(self.host_profile, kind, &set);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let existing_mapping = self
|
||||
.host
|
||||
.server_mappings(cid)?
|
||||
.into_iter()
|
||||
.find(|m| m.server_id == realm_id);
|
||||
|
||||
let session_id = SessionId::new();
|
||||
// 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")?;
|
||||
|
||||
// Monotonic union of collections
|
||||
for (kind, ids) in ¶ms.collections {
|
||||
if !super::super::session::protocol::carried_kind_for(kind, model.ruleset) {
|
||||
return Err(fail(
|
||||
"incompatible",
|
||||
format!(
|
||||
"Foreign collection kind {kind:?} in {} remote transfer",
|
||||
model.ruleset
|
||||
),
|
||||
));
|
||||
}
|
||||
if let Ok(set) = super::super::collection::IdSet::from_ids(ids.iter().copied()) {
|
||||
let _ = self
|
||||
.host
|
||||
.merge_collection(self.host_profile, model.ruleset, kind, &set);
|
||||
}
|
||||
}
|
||||
|
||||
let session_id = SessionId::from_uuid(params.session_id)?;
|
||||
let envelope = super::super::session::protocol::Envelope::from_encoded(
|
||||
&super::super::snapshot::encode(&model)?,
|
||||
);
|
||||
let offer = super::super::session::protocol::SessionOffer {
|
||||
protocol_version: super::super::session::protocol::PROTOCOL_VERSION,
|
||||
ruleset: model.ruleset,
|
||||
session_id,
|
||||
character_id: cid,
|
||||
server_id: realm_id.to_string(),
|
||||
|
||||
@@ -0,0 +1,345 @@
|
||||
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
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -53,6 +53,7 @@ pub struct CopyView {
|
||||
pub struct CharacterView {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub ruleset: super::super::model::Ruleset,
|
||||
pub class_name: String,
|
||||
pub race: String,
|
||||
pub level: u8,
|
||||
|
||||
@@ -7,7 +7,7 @@ use super::*;
|
||||
use crate::portable::collection::IdSet;
|
||||
use crate::portable::fixtures::geared_level_eighty;
|
||||
use crate::portable::ids::{CharacterId, SessionId};
|
||||
use crate::portable::model::PortableCharacter;
|
||||
use crate::portable::model::{PortableCharacter, Ruleset};
|
||||
use crate::portable::realm::knowledge::RealmKnowledge;
|
||||
use crate::portable::store::Store;
|
||||
|
||||
@@ -328,10 +328,10 @@ fn a_realm_that_lacks_an_unlock_never_removes_it_and_gets_what_it_knows_back() {
|
||||
// the Owner already holds a big wardrobe from other realms
|
||||
let profile = owner.default_profile().unwrap();
|
||||
owner
|
||||
.merge_collection(profile, APPEARANCE, &ids(1..=500))
|
||||
.merge_collection(profile, Ruleset::Coa, APPEARANCE, &ids(1..=500))
|
||||
.unwrap();
|
||||
owner
|
||||
.merge_collection(profile, VANITY, &ids(1000..=1010))
|
||||
.merge_collection(profile, Ruleset::Coa, VANITY, &ids(1000..=1010))
|
||||
.unwrap();
|
||||
// this realm knows only part of it and holds only a few
|
||||
realm.knowledge = knows(ids(1..=300), ids(1000..=1005));
|
||||
@@ -344,7 +344,11 @@ fn a_realm_that_lacks_an_unlock_never_removes_it_and_gets_what_it_knows_back() {
|
||||
// the Owner unioned the realm's ids (700 included: the realm showed it) and kept everything else
|
||||
let appearance_ack = acks.iter().find(|a| a.kind == APPEARANCE).unwrap();
|
||||
assert_eq!(appearance_ack.outcome, CollectionOutcome::Applied);
|
||||
let (_, canonical) = o.store().collection(profile, APPEARANCE).unwrap().unwrap();
|
||||
let (_, canonical) = o
|
||||
.store()
|
||||
.collection(profile, Ruleset::Coa, APPEARANCE)
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(canonical.len(), 501);
|
||||
assert!(
|
||||
canonical.contains(700) && canonical.contains(1) && canonical.contains(500),
|
||||
@@ -371,12 +375,14 @@ fn an_account_with_unlocks_arrives_on_a_second_realm_from_the_owners_state_alone
|
||||
let mut owner = Store::open_in_memory().unwrap();
|
||||
let profile = owner.default_profile().unwrap();
|
||||
owner
|
||||
.merge_collection(profile, APPEARANCE, &ids(1..=40))
|
||||
.merge_collection(profile, Ruleset::Coa, APPEARANCE, &ids(1..=40))
|
||||
.unwrap();
|
||||
owner
|
||||
.merge_collection(profile, VANITY, &ids(50..=60))
|
||||
.merge_collection(profile, Ruleset::Coa, VANITY, &ids(50..=60))
|
||||
.unwrap();
|
||||
let states = OwnerService::new(&mut owner)
|
||||
.collection_states(Ruleset::Coa)
|
||||
.unwrap();
|
||||
let states = OwnerService::new(&mut owner).collection_states().unwrap();
|
||||
assert_eq!(states.len(), 2);
|
||||
|
||||
let mut host = Store::open_in_memory().unwrap();
|
||||
@@ -415,16 +421,17 @@ fn hostile_or_broken_collection_messages_change_nothing() {
|
||||
let mut owner = Store::open_in_memory().unwrap();
|
||||
let profile = owner.default_profile().unwrap();
|
||||
let mut o = OwnerService::new(&mut owner);
|
||||
let good =
|
||||
collection_to_json(&CollectionObserved::new(SERVER, APPEARANCE, &ids(1..=10)).unwrap())
|
||||
.unwrap();
|
||||
let good = collection_to_json(
|
||||
&CollectionObserved::new(SERVER, Ruleset::Coa, APPEARANCE, &ids(1..=10)).unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
o.handle_collection(&good).unwrap().outcome,
|
||||
CollectionOutcome::Applied
|
||||
);
|
||||
let state_of = |o: &OwnerService| {
|
||||
o.store()
|
||||
.collection_info(profile, APPEARANCE)
|
||||
.collection_info(profile, Ruleset::Coa, APPEARANCE)
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
};
|
||||
@@ -487,13 +494,39 @@ fn hostile_or_broken_collection_messages_change_nothing() {
|
||||
// a set that decodes to more ids than the cap allows is refused before it is built
|
||||
let mut huge = vec![1u8];
|
||||
huge.extend([0xFF, 0xFF, 0xFF, 0xFF, 0x0F]);
|
||||
let message = serde_json::json!({"protocol_version": PROTOCOL_VERSION, "server_id": SERVER, "kind": APPEARANCE, "set": {"hash": "00".repeat(32), "count": 1, "ids": base64::Engine::encode(&base64::engine::general_purpose::STANDARD, huge)}});
|
||||
let message = serde_json::json!({"protocol_version": COLLECTION_PROTOCOL_VERSION, "ruleset": "coa", "server_id": SERVER, "kind": APPEARANCE, "set": {"hash": "00".repeat(32), "count": 1, "ids": base64::Engine::encode(&base64::engine::general_purpose::STANDARD, huge)}});
|
||||
assert!(matches!(
|
||||
o.handle_collection(&serde_json::to_vec(&message).unwrap())
|
||||
.unwrap()
|
||||
.outcome,
|
||||
CollectionOutcome::Rejected(_)
|
||||
));
|
||||
|
||||
// attack test: prefix-confusion collection kinds are strictly rejected with zero state change
|
||||
for evil_kind in [
|
||||
"coax:appearance",
|
||||
"coaevil:vanity",
|
||||
"wildcard2:appearance",
|
||||
"reborn-extra:vanity",
|
||||
"coa:",
|
||||
"unknown",
|
||||
"coa:appearance:extra",
|
||||
] {
|
||||
let mut v: serde_json::Value = serde_json::from_slice(&good).unwrap();
|
||||
v["kind"] = evil_kind.into();
|
||||
let ack = o
|
||||
.handle_collection(&serde_json::to_vec(&v).unwrap())
|
||||
.unwrap();
|
||||
assert!(
|
||||
matches!(ack.outcome, CollectionOutcome::Rejected(_)),
|
||||
"evil kind {evil_kind} must be rejected"
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
state_of(&o),
|
||||
before,
|
||||
"prefix confusion attacks must mutate nothing"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -555,7 +588,7 @@ fn ten_thousand_and_fifty_thousand_ids_stay_cheap() {
|
||||
assert_eq!(realm.full_reads, reads);
|
||||
let stored = o
|
||||
.store()
|
||||
.collection_info(profile, APPEARANCE)
|
||||
.collection_info(profile, Ruleset::Coa, APPEARANCE)
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(stored.count, count as usize);
|
||||
@@ -565,7 +598,7 @@ fn ten_thousand_and_fifty_thousand_ids_stay_cheap() {
|
||||
let mut empty_realm = FakeRealm::new(GUID);
|
||||
empty_realm.knowledge = realm.knowledge.clone();
|
||||
let state = o
|
||||
.collection_states()
|
||||
.collection_states(Ruleset::Coa)
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.find(|s| s.kind == APPEARANCE)
|
||||
@@ -627,7 +660,7 @@ fn a_lost_acknowledgement_resends_the_same_set_and_the_owner_counts_it_once() {
|
||||
.any(|p| p.kind == APPEARANCE));
|
||||
assert_eq!(
|
||||
o.store()
|
||||
.collection_info(profile, APPEARANCE)
|
||||
.collection_info(profile, Ruleset::Coa, APPEARANCE)
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.revision,
|
||||
@@ -738,3 +771,102 @@ fn a_session_that_changes_nothing_on_a_format_1_store_makes_no_new_revision() {
|
||||
"the same character in a newer format is not a change"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wildcard_and_coa_collections_remain_strictly_isolated() {
|
||||
let mut owner = Store::open_in_memory().unwrap();
|
||||
let profile = owner.default_profile().unwrap();
|
||||
|
||||
let coa_set = IdSet::from_ids([10, 20, 30]).unwrap();
|
||||
let wc_set = IdSet::from_ids([10, 40, 50]).unwrap();
|
||||
|
||||
owner
|
||||
.merge_collection(profile, Ruleset::Coa, "coa:appearance", &coa_set)
|
||||
.unwrap();
|
||||
owner
|
||||
.merge_collection(profile, Ruleset::Wildcard, "wildcard:appearance", &wc_set)
|
||||
.unwrap();
|
||||
|
||||
// Verify initial namespaces
|
||||
let (_, s_coa) = owner
|
||||
.collection(profile, Ruleset::Coa, "coa:appearance")
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(s_coa.ids(), &[10, 20, 30]);
|
||||
|
||||
let (_, s_wc) = owner
|
||||
.collection(profile, Ruleset::Wildcard, "wildcard:appearance")
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(s_wc.ids(), &[10, 40, 50]);
|
||||
|
||||
let mut o = OwnerService::new(&mut owner);
|
||||
|
||||
// 1. Valid Wildcard observation updates Wildcard collection only
|
||||
let wc_update = IdSet::from_ids([10, 40, 50, 60]).unwrap();
|
||||
let msg_wc = CollectionObserved {
|
||||
protocol_version: COLLECTION_PROTOCOL_VERSION,
|
||||
ruleset: Ruleset::Wildcard,
|
||||
server_id: "wc-realm".into(),
|
||||
kind: "wildcard:appearance".into(),
|
||||
set: CompactSet::seal("wildcard:appearance", &wc_update).unwrap(),
|
||||
};
|
||||
let ack = o.handle_collection(&to_json(&msg_wc).unwrap()).unwrap();
|
||||
assert!(matches!(
|
||||
ack.outcome,
|
||||
CollectionOutcome::Applied | CollectionOutcome::Unchanged
|
||||
));
|
||||
|
||||
// CoA remains exactly [10, 20, 30]
|
||||
let (_, s_coa_after) = o
|
||||
.store()
|
||||
.collection(profile, Ruleset::Coa, "coa:appearance")
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(s_coa_after.ids(), &[10, 20, 30]);
|
||||
|
||||
// Wildcard updated to [10, 40, 50, 60]
|
||||
let (_, s_wc_after) = o
|
||||
.store()
|
||||
.collection(profile, Ruleset::Wildcard, "wildcard:appearance")
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(s_wc_after.ids(), &[10, 40, 50, 60]);
|
||||
|
||||
// 2. Cross-ruleset injection attack: Wildcard message carrying coa:appearance is rejected
|
||||
let rogue_wc = CollectionObserved {
|
||||
protocol_version: COLLECTION_PROTOCOL_VERSION,
|
||||
ruleset: Ruleset::Wildcard,
|
||||
server_id: "wc-realm".into(),
|
||||
kind: "coa:appearance".into(),
|
||||
set: CompactSet::seal("coa:appearance", &IdSet::from_ids([999]).unwrap()).unwrap(),
|
||||
};
|
||||
let ack_rogue = o.handle_collection(&to_json(&rogue_wc).unwrap()).unwrap();
|
||||
assert!(matches!(ack_rogue.outcome, CollectionOutcome::Rejected(_)));
|
||||
|
||||
// 3. Cross-ruleset injection attack: CoA message carrying wildcard:appearance is rejected
|
||||
let rogue_coa = CollectionObserved {
|
||||
protocol_version: COLLECTION_PROTOCOL_VERSION,
|
||||
ruleset: Ruleset::Coa,
|
||||
server_id: "coa-realm".into(),
|
||||
kind: "wildcard:appearance".into(),
|
||||
set: CompactSet::seal("wildcard:appearance", &IdSet::from_ids([999]).unwrap()).unwrap(),
|
||||
};
|
||||
let ack_rogue2 = o.handle_collection(&to_json(&rogue_coa).unwrap()).unwrap();
|
||||
assert!(matches!(ack_rogue2.outcome, CollectionOutcome::Rejected(_)));
|
||||
|
||||
// Verify neither 999 touched CoA or Wildcard
|
||||
let (_, s_coa_final) = o
|
||||
.store()
|
||||
.collection(profile, Ruleset::Coa, "coa:appearance")
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(s_coa_final.ids(), &[10, 20, 30]);
|
||||
|
||||
let (_, s_wc_final) = o
|
||||
.store()
|
||||
.collection(profile, Ruleset::Wildcard, "wildcard:appearance")
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(s_wc_final.ids(), &[10, 40, 50, 60]);
|
||||
}
|
||||
@@ -467,16 +467,20 @@ impl RealmBridge for FakeRealm {
|
||||
impl FakeRealm {
|
||||
fn rows(&self, kind: &str) -> Result<&IdSet> {
|
||||
match kind {
|
||||
"coa:appearance" => Ok(&self.appearance_rows),
|
||||
"coa:vanity" => Ok(&self.vanity_rows),
|
||||
"coa:appearance" | "wildcard:appearance" | "reborn:appearance" => {
|
||||
Ok(&self.appearance_rows)
|
||||
}
|
||||
"coa:vanity" | "wildcard:vanity" | "reborn:vanity" => Ok(&self.vanity_rows),
|
||||
other => Err(PortableError::Invalid(format!("unknown kind {other}"))),
|
||||
}
|
||||
}
|
||||
|
||||
fn rows_mut(&mut self, kind: &str) -> Result<&mut IdSet> {
|
||||
match kind {
|
||||
"coa:appearance" => Ok(&mut self.appearance_rows),
|
||||
"coa:vanity" => Ok(&mut self.vanity_rows),
|
||||
"coa:appearance" | "wildcard:appearance" | "reborn:appearance" => {
|
||||
Ok(&mut self.appearance_rows)
|
||||
}
|
||||
"coa:vanity" | "wildcard:vanity" | "reborn:vanity" => Ok(&mut self.vanity_rows),
|
||||
other => Err(PortableError::Invalid(format!("unknown kind {other}"))),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -176,6 +176,26 @@ impl<'a> HostService<'a> {
|
||||
found: model.character_id,
|
||||
});
|
||||
}
|
||||
if offer.ruleset != model.ruleset {
|
||||
return Err(PortableError::RulesetMismatch {
|
||||
character: model.ruleset,
|
||||
realm: offer.ruleset,
|
||||
});
|
||||
}
|
||||
if let Some((_, rs)) = self.server_id.split_once(':') {
|
||||
let host_ruleset = rs.parse::<crate::portable::Ruleset>().map_err(|_| {
|
||||
PortableError::Invalid(format!(
|
||||
"malformed or unknown ruleset suffix in server_id: {:?}",
|
||||
self.server_id
|
||||
))
|
||||
})?;
|
||||
if offer.ruleset != host_ruleset || model.ruleset != host_ruleset {
|
||||
return Err(PortableError::RulesetMismatch {
|
||||
character: model.ruleset,
|
||||
realm: host_ruleset,
|
||||
});
|
||||
}
|
||||
}
|
||||
self.store
|
||||
.host_install_copy(profile, &model, offer.canonical_revision, "owner")?;
|
||||
self.store.host_prepare_session(offer, &model)
|
||||
@@ -606,8 +626,16 @@ impl<'a> HostService<'a> {
|
||||
let Some(account) = bridge.account_of(guid)? else {
|
||||
continue;
|
||||
};
|
||||
for kind in COLLECTION_KINDS {
|
||||
self.observe_collection(bridge, account, kind, now_secs, events)?;
|
||||
let character = self.store.character(s.character_id)?;
|
||||
for kind in collection_kinds(character.ruleset) {
|
||||
self.observe_collection(
|
||||
bridge,
|
||||
account,
|
||||
character.ruleset,
|
||||
kind,
|
||||
now_secs,
|
||||
events,
|
||||
)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
@@ -619,6 +647,7 @@ impl<'a> HostService<'a> {
|
||||
&mut self,
|
||||
bridge: &mut dyn RealmBridge,
|
||||
account: u32,
|
||||
ruleset: crate::portable::model::Ruleset,
|
||||
kind: &str,
|
||||
now_secs: u64,
|
||||
events: &mut Vec<HostEvent>,
|
||||
@@ -644,7 +673,12 @@ impl<'a> HostService<'a> {
|
||||
)?;
|
||||
return Ok(());
|
||||
}
|
||||
let bytes = collection_to_json(&CollectionObserved::new(&self.server_id, kind, &set)?)?;
|
||||
let bytes = collection_to_json(&CollectionObserved::new(
|
||||
&self.server_id,
|
||||
ruleset,
|
||||
kind,
|
||||
&set,
|
||||
)?)?;
|
||||
self.store.host_collection_observe(
|
||||
&self.server_id,
|
||||
account,
|
||||
@@ -674,7 +708,7 @@ impl<'a> HostService<'a> {
|
||||
account: u32,
|
||||
ack: &CollectionAck,
|
||||
) -> Result<Option<Applied>> {
|
||||
if !carried_kind(&ack.kind) {
|
||||
if !carried_kind_for(&ack.kind, ack.ruleset) {
|
||||
return Err(PortableError::Invalid(
|
||||
"the acknowledgement is for a kind that is not carried".into(),
|
||||
));
|
||||
@@ -742,7 +776,7 @@ impl<'a> HostService<'a> {
|
||||
account: u32,
|
||||
state: &CollectionState,
|
||||
) -> Result<Option<Applied>> {
|
||||
if !carried_kind(&state.kind) {
|
||||
if !carried_kind_for(&state.kind, state.ruleset) {
|
||||
return Err(PortableError::Invalid(
|
||||
"the collection kind is not carried".into(),
|
||||
));
|
||||
|
||||
@@ -49,10 +49,15 @@ impl<'a> OwnerService<'a> {
|
||||
pub fn handle_collection(&mut self, bytes: &[u8]) -> Result<CollectionAck> {
|
||||
let msg: CollectionObserved = collection_from_json(bytes)?;
|
||||
let profile = self.store.default_profile()?;
|
||||
let ruleset = msg.ruleset;
|
||||
let rejected = |store: &Store, reason: &str| -> Result<CollectionAck> {
|
||||
let info = store.collection_info(profile, &msg.kind).ok().flatten();
|
||||
let info = store
|
||||
.collection_info(profile, ruleset, &msg.kind)
|
||||
.ok()
|
||||
.flatten();
|
||||
Ok(CollectionAck {
|
||||
protocol_version: PROTOCOL_VERSION,
|
||||
protocol_version: crate::portable::session::protocol::COLLECTION_PROTOCOL_VERSION,
|
||||
ruleset,
|
||||
kind: msg.kind.clone(),
|
||||
outcome: CollectionOutcome::Rejected(reason.to_string()),
|
||||
collection_revision: info.as_ref().map_or(0, |i| i.revision),
|
||||
@@ -60,30 +65,39 @@ impl<'a> OwnerService<'a> {
|
||||
canonical: None,
|
||||
})
|
||||
};
|
||||
if !carried_kind(&msg.kind) {
|
||||
return rejected(self.store, "this collection kind is not carried");
|
||||
if !carried_kind_for(&msg.kind, ruleset) {
|
||||
return rejected(
|
||||
self.store,
|
||||
"this collection kind is not carried for this ruleset",
|
||||
);
|
||||
}
|
||||
let observed = match msg.set.open(&msg.kind) {
|
||||
Ok(set) => set,
|
||||
Err(e) => return rejected(self.store, &e.to_string()),
|
||||
};
|
||||
let merge = self.store.merge_collection(profile, &msg.kind, &observed)?;
|
||||
let merge = self
|
||||
.store
|
||||
.merge_collection(profile, ruleset, &msg.kind, &observed)?;
|
||||
let (info, canonical) = self
|
||||
.store
|
||||
.collection(profile, &msg.kind)?
|
||||
.collection(profile, ruleset, &msg.kind)?
|
||||
.map(|(i, s)| (Some(i), s))
|
||||
.unwrap_or((None, IdSet::new()));
|
||||
let canonical_state = match (
|
||||
&info,
|
||||
observed.count_new(&canonical) == 0 && canonical.count_new(&observed) == 0,
|
||||
) {
|
||||
(Some(info), false) => {
|
||||
Some(CollectionState::new(&msg.kind, info.revision, &canonical)?)
|
||||
}
|
||||
(Some(info), false) => Some(CollectionState::new(
|
||||
ruleset,
|
||||
&msg.kind,
|
||||
info.revision,
|
||||
&canonical,
|
||||
)?),
|
||||
_ => None,
|
||||
};
|
||||
Ok(CollectionAck {
|
||||
protocol_version: PROTOCOL_VERSION,
|
||||
protocol_version: crate::portable::session::protocol::COLLECTION_PROTOCOL_VERSION,
|
||||
ruleset,
|
||||
kind: msg.kind,
|
||||
outcome: if merge.changed {
|
||||
CollectionOutcome::Applied
|
||||
@@ -97,12 +111,15 @@ impl<'a> OwnerService<'a> {
|
||||
}
|
||||
|
||||
/// The canonical collections as messages (for a realm that has none of them yet, or a new one).
|
||||
pub fn collection_states(&mut self) -> Result<Vec<CollectionState>> {
|
||||
pub fn collection_states(
|
||||
&mut self,
|
||||
ruleset: crate::portable::model::Ruleset,
|
||||
) -> Result<Vec<CollectionState>> {
|
||||
let profile = self.store.default_profile()?;
|
||||
let mut out = Vec::new();
|
||||
for kind in COLLECTION_KINDS {
|
||||
if let Some((info, set)) = self.store.collection(profile, kind)? {
|
||||
out.push(CollectionState::new(kind, info.revision, &set)?);
|
||||
for kind in collection_kinds(ruleset) {
|
||||
if let Some((info, set)) = self.store.collection(profile, ruleset, kind)? {
|
||||
out.push(CollectionState::new(ruleset, kind, info.revision, &set)?);
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
|
||||
Loaded 100 of 298 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user