commit b9bc0b9619ffa25bcb3c76fd23d084249b490583
parent ecf71180395022e3aeb89062ba881dea4d0511a7
Author: anon <anon@example.com>
Date: Tue, 13 Oct 2026 00:29:27 +0000
Add persistent user controls, 13.2 compatibility, and browser terrain
Diffstat:
19 files changed, 1282 insertions(+), 140 deletions(-)
diff --git a/.gitignore b/.gitignore
@@ -19,4 +19,5 @@ data/users.yaml
data/users.yaml.tmp
node_modules/
browser/dist/
+browser/assets/
__pycache__/
diff --git a/README.md b/README.md
@@ -1,8 +1,9 @@
-# Anarchy Online 11.0
+# Anarchy Online
The first milestone is running the original 2001 Windows client against a
minimal local Go server, entering a playfield, and walking. The eventual goal
-is a web remake of that experience.
+is a web remake of that experience. The isolated working target currently runs
+the recovered 13.2 build; the agreed 13.24 hotfix cutoff is still unverified.
Start with [docs/README.md](docs/README.md) for original-client research:
observed behavior, recovered protocol, extracted game data, reverse-engineering
@@ -10,7 +11,8 @@ evidence, historical-server inferences, and open questions.
The mounted release disc was extracted with Unshield rather than installed.
`client-original/Gamefiles` is the untouched reference. `client-local` is the
-working copy; `client-peer` is a second copy for multiplayer checks. The modern
+11.0 working copy; `client-peer` is a second 11.0 copy for reference and multiplayer
+checks. `client-target` is the separately upgraded 13.2 working client. The modern
installation at `C:\Funcom\Anarchy Online` is untouched.
## Run
@@ -22,27 +24,41 @@ From this directory in PowerShell:
& 'C:\Program Files\Go\bin\go.exe' run ./server
```
-Then launch `client-local\anarchy.exe` with `client-local` as its working
+Then launch `client-target\anarchy.exe` with `client-target` as its working
directory. Use the synthetic username and password `localtest`. Select
`Local Rubi-Ka`, choose a graphics device, and keep `Run in window` checked.
-The patch script also sets `FullScreen 0` in `Prefs/Main.cfg`.
+The upgrade helper sets `FullScreen 0` in `Prefs/Main.cfg`.
The server binds only to localhost: HTTP 8080, login 7500, and world 7501.
-No executable bytes are patched. Local URL files and a dimension entry with
-version `11.0` let the launcher log in without requesting a game update.
+Local URL files and a dimension entry matching `client-target/version.id` let
+the launcher log in without requesting a game update. The preserved 11.0
+working copies still use their own dimension list. Go selects the recovered
+13.2 world layout from its first cookie packet; no Python proxy is needed.
+
+To reproduce the isolated upgrade, close all native AO games and run
+`venv\Scripts\python.exe tools\upgrade_client.py`. The required recovered
+media and patches are listed in [versions-and-patches.md](docs/versions-and-patches.md).
+The helper currently reaches 13.2, not a verified 13.24 build.
To quit, press X to sit, then choose OPT > Quit > To Windows. The original
logout countdown takes 30 seconds. Pressing X to stand prevents logout,
although the client's countdown bar currently remains visible.
-Open http://127.0.0.1:8080/control to see connected players, change the game
-time immediately, and select a teleport destination from the original zone
-catalog. Each player has a dropdown with 373 entries. The 25 names without
+Open http://127.0.0.1:8080/control to list all saved users, create a user, and
+change the game time immediately. Follow a user's name to edit their character
+in a YAML textarea or teleport them using the original zone catalog. Offline
+users and users reconnecting during a teleport stay on the list. Each user has
+a dropdown with 373 entries. The 25 names without
disc assets and four internal dependency maps are disabled; 344 maps have assets.
The page is plain HTML forms with no JavaScript or CSS. The world starts at
13:30. Rubi-Ka has a 27-hour day, running at 15 game seconds per real second.
-Hour values range from 0 to 26; minutes range from 0 to 59. Settings reset when
-the server restarts.
+Hour values range from 0 to 26; minutes range from 0 to 59. The clock resets when
+the server restarts. Users, character fields, zones, and received movement
+positions are saved in `data/users.yaml` and restored at startup. Each local
+user currently owns one character, with a stable ID. Saving character data
+refreshes an online character through the native zone reconnect sequence.
+Edit the file directly while the server is stopped, or use the web editor while
+it runs. The storage file is local development data and is ignored by Git.
For an autonomous two-client check, start the server and run:
@@ -50,12 +66,14 @@ For an autonomous two-client check, start the server and run:
.\venv\Scripts\python.exe tools\launch_clients.py
```
-This uses the existing `client-local` and `client-peer` directories, creates
+This reference check uses the existing 11.0 `client-local` and `client-peer` directories, creates
two synthetic local sessions, and supplies the original launcher's environment.
Both working copies have windowed graphics configured.
## Verified progress
+- The recovered 13.2 client connects directly to Go, renders heads/NPCs, walks,
+ and completes the Omni Training/Borealis teleport roundtrip.
- The original launcher loads the local dimension list and informational page.
- The login challenge and character list are accepted.
- A level 1 Soldier named Local Explorer appears in character selection.
@@ -76,18 +94,24 @@ Both working copies have windowed graphics configured.
- The complete original map catalog is available in each player's dropdown.
- X toggles sitting and standing; Quit to Windows finishes after 30 seconds.
-The first two milestones are working. Each login creates a synthetic level-1
-Solitus Soldier. Positions and zone membership are shared in memory. Movement
-is simulated by the original client; the server relays it without validation.
+The first two milestones are working. The native launcher lists saved users;
+an empty server creates a level-1 Solitus Soldier. The direct-launch test
+helpers create fresh saved users. Positions and zone membership are shared.
+Movement is simulated by the original client; the server relays it without validation.
Creature roaming is provisional: paths stay within four metres of each spawn,
with 1.5-metre-per-second walking and three-to-eight-second pauses. The client
continues moving between start and stop commands. Fixed
spawns and human placeholders stay at their posts. Only occupied zones are
simulated. Outdoor roaming follows decoded terrain while preserving each spawn's
authored ground offset. Indoor floor sampling, wall avoidance and pathfinding,
-combat, other NPC behavior, chat, account security, and disk persistence remain
-unimplemented. These are the original Windows clients; the
-browser remake has not started.
+combat, other NPC behavior, chat, and account security remain unimplemented.
+Character creation and editing cover the fields currently decoded by the server;
+inventories, equipment, and most gameplay stats are still placeholders.
+
+The browser prototype at http://127.0.0.1:8080/browser/ uses the original Omni
+Training height grid. Generate its local assets with
+`venv\Scripts\python.exe tools\browser_assets.py`. It is a terrain and movement
+experiment; the Windows clients remain the reference for the complete scene.
The server loads outdoor height grids from `data/terrain.bin` at startup. To
rebuild that file from the original disc data, run
diff --git a/docs/README.md b/docs/README.md
@@ -1,8 +1,8 @@
# Original Anarchy Online research
This is a record of findings about the original 2001 Anarchy Online 11.0
-client, its wire protocol, and its shipped assets. The eventual goal is a web
-remake of that experience. The original Windows client provides a reference
+client and the recovered 13.2 client, their wire protocols, and shipped assets.
+The eventual goal is a web remake of that experience. The original Windows client provides a reference
for recovering behavior and checking our interpretation.
These documents describe the original artifacts and recorded experiments.
@@ -17,20 +17,21 @@ current feature status. Read the source for implementation details and the
| [versions-and-patches.md](versions-and-patches.md) | Provisional 13.24 target, historical cutoff evidence, city-layout uncertainty, recovered patch inventory, and upgrade handoff checks. |
| [client-behavior.md](client-behavior.md) | Launch requirements, client simulation, visibility, appearance, lighting, logout, and inferred responsibilities of the historical server. |
| [protocol.md](protocol.md) | Framing, compression, login, entity messages, zoning, time, appearance, and original reader/activation addresses. |
+| [protocol-13.2.md](protocol-13.2.md) | Recovered 13.2 envelope, appearance, character, movement, and teleport differences, with native runtime checks. |
| [game-data.md](game-data.md) | Resource database, map/terrain decoding, original district populations, monster appearances, and unresolved template links. |
| [reverse-engineering.md](reverse-engineering.md) | Original binary hashes, saved evidence/snapshots, capture locations, and analysis recovery. |
| [open-questions.md](open-questions.md) | Unknown semantics, failed experiments worth preserving, and other server projects as research leads. |
-| [browser-porting.md](browser-porting.md) | Browser-port examples, emulation/static translation versus reconstruction, and an untested feasibility proposal for AO. |
+| [browser-porting.md](browser-porting.md) | Approach comparison, bounded runtime assessment, and the initial original-terrain browser scene. |
For a fresh session, read this page and client-behavior.md, then use the
protocol and game-data documents for the feature under investigation. Consult
saved evidence before repeating native analysis. Choose further work from the
user's latest instructions; the open questions are research leads.
-The selected historical target is now provisionally **13.24**, while the
-findings below remain evidence about **11.0**. Read versions-and-patches.md
-before any upgrade: the exact 13.24 binary path and preservation of the city
-gathering area are not yet verified. No upgrade was performed in that research.
+The selected historical target is provisionally **13.24**. The recovered patch
+chain has produced an isolated **13.2** client; the later hotfixes and city
+gathering-area cutoff remain unverified. Read versions-and-patches.md before
+upgrading, and use the protocol document for the specific tested build.
## Evidence standard
@@ -58,6 +59,7 @@ Drive letters and running processes must be rediscovered after a restart.
| --- | --- |
| `client-original/Gamefiles/` | Pristine release files extracted from the disc. |
| `client-local/`, `client-peer/` | Working original clients used for experiments. |
+| `client-target/` | Isolated 13.2 client produced from the recovered 12.0 disc and incremental patches. |
| `server/` | Local Go implementation; consult the source directly. |
| `tools/` | Extractors, decoded catalogs, REA snapshots, evidence, captures, and launch helpers. |
| `venv/` | Python environment used by the tools. |
diff --git a/docs/browser-porting.md b/docs/browser-porting.md
@@ -2,8 +2,8 @@
Primary-source research recorded on 2026-10-12. This compares ways to preserve
an old game's behavior in a browser and applies them to the release 11.0
-client. It is a research recommendation, not an implemented browser port.
-AO has not been tested with the runtimes or translators discussed here.
+client. The original approach recommendation is followed by the first bounded
+compatibility assessment and terrain prototype recorded at the end of this document.
Recheck project capabilities before choosing a dependency; their support
status can change independently of the original-client findings.
@@ -146,7 +146,7 @@ implementation decision, separate from the original protocol.
## Proposed decision process for AO
-This is a proposal; the compatibility experiments below have not been run.
+This was the initial proposal, before the bounded assessment recorded below.
1. Make a bounded compatibility assessment of Theseus and Boxedwine against
the release client and its DLLs. Record the actual first blockers instead
@@ -170,3 +170,116 @@ All routes still need the missing server reconstructed. Preserving the client
does not recover private 2001 NPC templates, combat/loot rules, scripts,
persistence, or encounter decisions. Existing original-client protocol and
asset findings remain useful whichever browser approach is selected.
+
+## First bounded assessment, 2026-10-12
+
+This assessment uses the preserved **11.0** reference, not an upgraded client.
+`Clientr.exe` SHA-256 is
+`e529a9a327a0d3a0d878c1125f01e2d005458c3ab6ab3c606c9ff8210bc83228`.
+The earlier REA startup evidence remains in `tools/clientr-evidence.json`,
+including `ev_34306b5e968156945f88211f169a8c7097e6c39f0faedc8e04d9707bb2cfd4f9`.
+The new PE import inventory records all 48 EXE/DLL files in the extracted
+reference directory; that count includes programs/libraries not necessarily
+loaded by a normal game session.
+
+### Theseus: static dependency assessment
+
+The inspected source revision is
+`ca302a35c0a680634cfb76ea3d241e8c8d5e592e`.
+Its [gatherer](https://github.com/evmar/theseus/blob/ca302a35c0a680634cfb76ea3d241e8c8d5e592e/tc/src/gather/mod.rs)
+maps imported functions to built-in module/function calls. AO's main executable
+imports 229 symbols across 13 DLL names absent from the
+[built-in API modules](https://github.com/evmar/theseus/blob/ca302a35c0a680634cfb76ea3d241e8c8d5e592e/win32/winapi/src/lib.rs):
+12 game-specific modules plus `msvcp60.dll`. For example, `ddr.dll` alone supplies
+106 of those imports. Translating only `Clientr.exe` therefore does not provide
+the original game libraries. Those libraries would need translation/linkage or
+replacements as well.
+
+This is an observed import/source mismatch, not a translator runtime failure.
+The translator was not run because this host has no Rust toolchain. Instruction
+coverage, DLL translation strategy, complete API coverage and browser performance
+remain untested. `tools/browser_probe.py` reproduces the PE inventory and module
+comparison against checkouts under `tools/browser-reference/`; its reports are
+`tools/browser-imports.json` and `tools/browser-compatibility.json`.
+
+### Boxedwine: actual AO startup attempts
+
+The [official 26R1 Web release](https://github.com/danoon2/Boxedwine/releases/tag/26R1.0)
+was downloaded and tested locally, using the full pristine game directory in a
+650,124,861-byte ZIP. The client was launched through a batch file setting
+`ANARCHY_CD=cd_image`, `ANARCHY_SETUP=Setupf`, `FullScreen 0` and the same local
+world address used by the native reference. Both included compact Wine 6 and
+Wine 11 filesystems were tried with the single-threaded WASM build.
+
+**Observed first blocker:** Wine reports that `MSWSOCK.dll`, needed by
+`ace.dll`, cannot load. The original ACE import table requires `AcceptEx` and
+`TransmitFile`. This produces cascading game-DLL load failures before an AO
+world window or server session appears. A small placeholder file named
+`mswsock.dll` exists in both compact filesystem archives; its presence does
+not establish that its Wine implementation is available. The retained Wine 11
+console log and screenshot are `tools/browser-wine11-log.json` and
+`tools/browser-wine11.png`.
+
+The missing socket implementation was then restored from the
+[official full Wine 11 filesystem](https://boxedwine.org/v2/14/TinyCore15Wine11.0.zip),
+whose SHA-256 is
+`6f95b31996704a4094e056880f6ebeb528ef5e29b367244610d5dd01f2ff8609`.
+`tools/browser_wine_overlay.py` extracts its 85,672-byte
+`opt/wine/lib/wine/i386-unix/mswsock.dll.so` into a small overlay ZIP.
+The placeholder DLL bytes match those in the compact Wine 11 image.
+
+**Observed next blocker:** this overlay eliminates the ACE import failure and
+lets AO reach graphics initialization. Wine then reports that OpenGL is
+disabled, no suitable pixel format/GL context exists, and AO requests a
+Direct3D device unsupported by the current DirectDraw renderer. The release's
+own `readme.txt` advertises the same lack of OpenGL/Direct3D support. This is
+now a tested graphics limitation of this release, not an inference from its
+documentation. Evidence is `tools/browser-wine11-sockets-log.json` and
+`tools/browser-wine11-sockets.png`. No AO world was entered; networking and
+usable performance remain untested.
+
+The inspected **master** revision
+`65467424603484756a73308412f40b906d28b650` is materially newer than that release.
+Its [Emscripten build instructions](https://github.com/danoon2/Boxedwine/blob/65467424603484756a73308412f40b906d28b650/project/emscripten/buildInstructions.md)
+describe WASM JIT targets, and the source includes a WebSocket network gateway.
+The README's older statement that a JIT is still needed should not be used as
+a capability inventory for that revision. Master was not compiled or tested
+with AO. The full-filesystem/master graphics and networking experiment remains
+open. These findings do not establish that newer browser graphics paths fail
+the same way; the tested 26R1 release is not an adequate AO execution environment.
+
+To reproduce the released-runtime attempt: download/unpack `Boxedwine26R1Web.zip`
+under `tools/browser-reference/boxedwine-web`, check out the two source projects
+alongside it, and run `venv/Scripts/python.exe tools/browser_probe.py`.
+Serve `boxedwine-web/SingleThreaded` on localhost, then visit
+`boxedwine.html?app=ao&p=run.bat&sound=false`. For the second attempt, copy
+`Wine11/boxedwine.zip` to `SingleThreaded/wine11.zip` and add `root=wine11`.
+For the socket-restored attempt, download the full Wine filesystem above as
+`SingleThreaded/wine11-full.zip`, run `tools/browser_wine_overlay.py`, then add
+`overlay=ao-sockets` to the Wine 11 URL.
+The third-party multithreaded server requires COOP/COEP headers.
+
+### Bounded reconstruction started
+
+The first local browser scene renders the **actual original Omni Training
+height grid**, 65 by 65 archived samples covering 256 by 256 world units.
+The raw grid SHA-256 is
+`50b8bc2ac49ae72cc660a0b9f1535ebc3b946515f7eaa3f2a3be3b9dfd404023`.
+No height samples are reduced: all 8,192 terrain triangles are rendered.
+This reuses the validated CHGA height decoding described in
+[game-data.md](game-data.md); it does not recover the native terrain diagonal.
+
+Browser verification showed a rendered terrain scene with no console errors.
+Holding W for about two seconds on the Go-served page moved Z from 56.875 to
+59.953, preserving X=52.625 and ground Y=14.000, consistent with the chosen
+1.5 m/s base walk speed and input scheduling. Turning was
+also exercised. Evidence is `tools/browser-terrain-runtime.json` and
+`tools/browser-terrain.png`.
+
+This scene uses diagnostic shading and local movement. Original textures,
+buildings, characters, collision, animation, game UI and networking are not
+implemented. Camera projection/eye height and the bilinear ground approximation
+are provisional. Successful WebGL drawing does not satisfy the AO-port success
+criteria above. It provides a concrete starting scene while the full original-
+binary compatibility questions remain open. Local generation and launch
+instructions live in [browser/README.md](../browser/README.md).
diff --git a/docs/protocol-13.2.md b/docs/protocol-13.2.md
@@ -0,0 +1,165 @@
+# Recovered 13.2 protocol differences
+
+These observations refer to the isolated client whose `version.id` says
+`13.2`, with the binary hashes recorded in
+[versions-and-patches.md](versions-and-patches.md). They are not a verified
+13.24 specification. The 11.0 layouts remain documented in
+[protocol.md](protocol.md).
+
+## Transport and N3 envelopes
+
+The 16-byte, big-endian transport header and four-byte packet alignment remain
+usable. System cookie packets and heartbeat packets retain their existing
+shape. The observed 13.2 client uses message ID `0xdfdf`, including its first
+cookie packet. This is an observed discriminator, not a negotiated version
+number or a demonstrated guarantee for every AO release.
+
+The native client also accepted server packets with message ID `1`; matching
+the client's `0xdfdf` value in outgoing server packets was not necessary for
+the tested world entry, rendering, and movement.
+
+The crucial change is the type-10 N3 envelope:
+
+| Offset | 11.0 | 13.2 |
+| --- | --- | --- |
+| 16 | uint32 uncompressed length; zero means uncompressed | uint32 message key |
+| 20 | uint32 message key | uint32 identity type |
+| 24 | uint32 identity type | uint32 identity instance |
+| 28 | uint32 identity instance | uint32 pass-on flag |
+| 32 | uint32 pass-on flag | subclass body |
+| 36 | subclass body | continued subclass body |
+
+13.2 has no per-message compression DWORD in this path. This applies to both
+directions. Sending the 11.0 zero field to 13.2 makes it see key zero and ignore
+world initialization. Conversely, treating a native 13.2 message key as an
+11.0 compression length produces an invalid-zlib error.
+
+`nr.dll` 13.2 `N3Message_t` constructor `0x10003c20` copies the body directly
+from packet offset `0x10`. Its `CreateDataBlock` at `0x10004050` writes the body
+directly at the same offset. The common N3 prefix still contains a **uint32**
+pass-on flag. The message-name XOR key algorithm is unchanged in the examined
+`llr.dll` functions.
+
+## SimpleCharFullUpdate
+
+Message key `0x271b3a6b` retains its byte version, flags, optional playfield,
+coordinates, and orientation before appearance. Appearance is now a **uint32**,
+not uint16, and its bit positions changed:
+
+| Field | 11.0 bits | 13.2 bits |
+| --- | --- | --- |
+| Race | 0-1 | 0-2 |
+| Fatness | 2-3 | 3-4 |
+| Breed | 4-6 | 5-7 |
+| Sex | 7-8 | 8-9 |
+| Side | 9-10 | 10-11 |
+| Face | 11-15 | 12-16 |
+
+Widening the old value without repacking changes the character's appearance.
+The tested human `0x315` becomes `0x629`; the generic creature candidate
+`0xe5` becomes `0x1c9`.
+
+The compact absolute coordinate scales are unchanged: unsigned X/Z in eighths,
+signed Y in sixteenths. In 13.2 the reader multiplies X/Z by `0.125` at
+`0x1015070c`, and Y by `0.0625` at `0x10150710`. Nearby constants and vtable
+data must not be mistaken for the Y conversion.
+
+NPCs have an additional value immediately after the name and before level.
+The usual form is uint16; flag `0x20000` selects a byte form. The reader stores
+it at object offset `0x7e`, and activation applies it as stat **455**. Its
+historical meaning and original values remain unresolved. Zero rendered the
+tested creatures. Players retain three uint32 fields and four uint16 fields
+at this point instead of the NPC-specific field.
+
+The examined reader is `kkr.dll:0x10076e90`, with appearance read at
+`0x10077076`, and the NPC branch at `0x100771d3`. The existing head, named
+texture, length-prefixed vehicle, and two empty-list choices were sufficient
+for the runtime experiments; this does not prove every optional branch.
+
+## FullCharacter and playfield initialization
+
+FullCharacter key `0x29304349` still accepts version **16**, and legacy 15.
+There are **seven** encoded lists before the four stat lists, rather than six.
+An empty encoded list is uint32 `1009`. The new list is read at
+`kkr.dll:0x10073e19` into member `0x30`; helper `0x1002ddc0` verifies and decodes
+the `(count + 1) * 1009` representation. The following stat map remains a
+plain count. Empty inventories and the existing level-one stats worked in the
+tested client.
+
+PlayfieldAnarchy key `0x5f4b1a39` retains the version-4 base: XYZ, the `'a'`
+six-uint32 playfield proxy, and optional database-object identity. The two
+world origins still follow it. The display-name length/string trailer from
+11.0 is no longer read by `kkr.dll:0x10138da0`. The client displayed the zone
+name using its own data.
+
+## Movement
+
+CharDCMove key `0x54111123` adds **one byte after the uint32 action and before
+XYZ**. This is native 13.2 transport offset 36, or offset 40 in an envelope
+that still includes the old compression DWORD. Zero followed by the existing
+XYZ/quaternion/two-float fields worked for server-driven NPC movement. Native
+player movement also sent zero in the examined path. The byte's remaining
+values and semantics are not established.
+
+Ignoring this byte shifts every coordinate and corrupts persisted character
+positions. Check an actual move against decoded floats, not just whether a
+movement message arrived. NumPad0 toggles continuous forward movement in the
+tested client; tapping W stops it. This allows a sustained movement test with
+computer-use tools that only send brief key presses.
+
+## Teleport
+
+n3Teleport key `0x43197d22` replaces the old uint32 zone flag after XYZ with a
+complete playfield proxy:
+
+```text
+float32 X, Y, Z
+byte 'a'
+uint32 51100, destination, destination, 0, 40016, destination
+identity 0:0
+identity 40016:destination
+uint32 stream length, then stream bytes
+```
+
+The two identities and empty stream in this tested form follow the proxy.
+`llr.dll:n3TeleportIIR_t::ReadSubClass`, `0x1003dc10`, calls proxy reader
+`0x100453e0`. Sending the old flag causes that reader to throw because its
+first byte is not `'a'`. The retained crash log placed the throw immediately
+after that call. The complete proxy successfully teleported the same native
+process from Omni Training to Borealis and back through world reconnection.
+
+## Evidence and verification limits
+
+`tools/inspect_target_protocol.py` retains bounded Capstone disassembly,
+source hashes, addresses, and imported BinaryStream symbol annotations in
+`tools/client-target-reader-disassembly.json`. It requires the workspace venv
+with `pefile` and `capstone`. These raw disassembly observations complement
+the retained REA startup and patcher evidence; they are not fabricated REA
+evidence IDs.
+
+The temporary network probe applied the recovered wire differences to the
+working 11.0 server without changing its game state or content rules. Verified
+results were:
+
+- Native 13.2 renders Omni Training with player heads and creature meshes.
+- A Giant Snake rendered beside the player at a known authored training area.
+- Continuous movement changed Z from `62.875` to `65.79564`; the server
+ persisted valid XYZ and quaternion values after accounting for the new byte.
+- NPC spawn and movement traffic was accepted.
+- Borealis teleport and return to Omni Training completed in the same process.
+- A live time update to noon produced a daylight scene.
+- X produced sitting action `86`. The native "To Windows" control produced
+ logout action `120`, showed its 30-second countdown, and exited with code
+ zero after the server closed the world connection.
+
+The Go server now emits these layouts directly for the recovered client and
+normalizes incoming movement before persistence and relay. Network-boundary
+regression checks cover initialization, NPC fields, mixed-version movement,
+and the teleport proxy. No network probe is needed for normal play.
+The native checks were repeated directly against Go: sustained movement changed
+Z from `53` to `59.343258` with valid Y `14.576907`, and the same process
+completed the Omni Training/Borealis roundtrip and daylight update.
+`tools/client-target-world.png` records that direct connection's rendered scene.
+More complex actions, inventory content,
+character creation, and exact original NPC stat-455 values remain unverified.
+The selected 13.24 hotfix build and city-scenery cutoff are still unresolved.
diff --git a/docs/versions-and-patches.md b/docs/versions-and-patches.md
@@ -15,16 +15,16 @@ launch world; early fixes and modest additions are welcome.
Two uncertainties must be resolved before claiming that target is achieved:
1. The recovered installer is named `AOPatch_v13.1-v13.2.exe`. Its actual
- resulting build has not been checked. Do not assume the filename means it
+ resulting marker is now verified as `13.2`. Do not assume the filename means it
includes hotfixes through 13.24. No separately identified 13.24 package has
been recovered.
2. The exact patch that removed buildings beside the Omni-Entertainment
gathering area remains unknown. 13.24 is a candidate for preserving that
layout, not a verified last version with the buildings intact.
-**11.0 remains the pristine fidelity reference.** No downloaded installers
-were executed, no client was upgraded, and no server compatibility with later
-clients was established during this research. The previous suggestion of
+**11.0 remains the pristine fidelity reference.** Initial patch recovery did
+not execute installers or establish later-client compatibility. The isolated
+upgrade below subsequently produced a verified 13.2 installation. The previous suggestion of
14.5.1 is superseded by the user's preference for an earlier city layout.
## Release landmarks
@@ -116,7 +116,8 @@ cumulative-patch ZIP. Their combined size is 947,976,967 bytes.
[manifest.json](../patches/manifest.json) is the exact inventory: filename,
size, SHA-256, original download URL, and ordered 12.0-to-14.5.1 sequence.
-Its `installation_tested` field is false. The longer sequence is an inventory
+Its original `installation_tested` field is false; the later 12.0-to-13.2
+application result is recorded below. The longer sequence is an inventory
of recovered material, not the selected upgrade target.
### Candidate path from the recovered 12.0 CD
@@ -139,9 +140,8 @@ AOPatch_v13.0-v13.1.exe
AOPatch_v13.1-v13.2.exe
```
-This is a **filename-supported path to 13.2**, not a tested installation path
-to 13.24. Stop at that distinction until installer contents or an isolated
-installation establish the actual build. The downloaded chain from the
+This sequence has now been applied to an isolated 12.0 extraction and produces
+**13.2**, not a verified 13.24 installation. The downloaded chain from the
project's original **11.0 CD to 12.0 or 13.2 is missing**.
### Later installers retained for research
@@ -213,18 +213,92 @@ returned 404. The Archive collection inspected did not expose a suitable
earlier cumulative package. These are bounded search results, not proof that
no surviving copy exists anywhere.
-## Handoff checks for reaching the selected version
+## Isolated upgrade and patcher behavior
+
+On 2026-10-12, the recovered 12.0 CD's `Gamefiles` group was extracted into
+`client-target` with `tools/unshield/unshield.exe`. Windows `tar` reads the ISO
+and the self-extracting patch packages directly. The twelve increments above
+were applied by their bundled native patcher, including their resource-database
+deltas. `client-original`, `client-local`, and `client-peer` remain 11.0.
+
+The resulting `version.id` is literally **`13.2`**. The last patch log records
+successful application of `v13.1-v13.2.RES`; the consumed resource delta was
+removed. This establishes that the recovered package produces that version
+marker. It does **not** establish that the package contains every hotfix listed
+as 13.21 through 13.24 in the surviving notes.
+
+Binary identities for this installation:
+
+| File | SHA-256 |
+| --- | --- |
+| `Clientr.exe` | `1bc236ced3a56a575c03a98579ea3f5e0eca878d3fadf2eebe864e2d7861135c` |
+| `kkr.dll` | `b0e0173b5dbe129c6ad53eadd4467a0f53796993e613fecb9b2aaa6fc9a403ac` |
+
+The 13.2 package's embedded timestamps date its data deltas to November 27,
+2001, and its `Changes.txt` to November 28. Its bundled patcher dates to
+November 13. These dates are further reasons to investigate the later hotfixes
+separately, rather than infer them from the abbreviated package filename.
+
+Important native-patcher observations:
+
+- It checks for **any** game window with class `Anarchy client` and title
+ `Anarchy`, posts a close request, then waits until it disappears. This is a
+ global guard, including a game running from another installation directory.
+ Close the reference games before upgrading the isolated copy.
+- Its command-line parser searches for the literal `AnarchyPatcher.exe"`.
+ Quote the executable explicitly even when its path contains no spaces:
+ `"C:\path\to\ao\client-target\AnarchyPatcher.exe" 13.2`.
+ An ordinary Python argument list leaves this path unquoted; the patcher then
+ loses the requested remote version and may fall back to its launcher.
+- Stage only increments starting at the installed version. Reintroducing
+ already-consumed earlier `.RTP` files can prevent progress.
+- `version.id` and `Rename.ini` can change **before** the resource delta finishes.
+ Wait for the explicit successful resource-patching/stop-for-renaming log,
+ then stop the patcher and process the rename marker. The marker is read-only.
+- The final 13.2 marker contains `run=SpeedRead.exe`. That program offers an
+ optional graphics database/cache speedup; its text explicitly says ordinary
+ loading remains available without it. It was not run during this upgrade.
+- Windows can classify the patcher as an installer and request elevation.
+ `__COMPAT_LAYER=RunAsInvoker` lets this directory-confined patch application
+ run without administrative installation.
+
+The focused reproduction helper is `tools/upgrade_client.py`. It creates or
+resumes `client-target`, stages the remaining recovered increments, handles
+patcher replacement, and writes local launcher URLs plus `FullScreen 0`.
+It currently stops at the recovered **13.2** build and says so explicitly.
+
+REA evidence is retained locally in `tools/client-upgrade-evidence.json` and
+`tools/client-upgrade-analysis.json`. The patcher's initialization/parser is
+`FUN_00401357`, evidence
+`ev_8190f47d54ed48a66b14a6bf4cea5373a623d3f30e0ae175837573ea96bfba80`,
+from patcher SHA-256
+`94c7507f2adb6de0c8dacf047203da2f468e82b2b0f7bf22564fc33fd43c183f`.
+Its packaged 13.2 counterpart has SHA-256
+`c14fa8be29c2b4d052f863aaeb7ff5c0c3de2d6291f33511cf7b3d07a4d303bf`.
+These are different binaries despite both reporting resource version 1.0.2.1.
+
+The 13.2 3D executable still accepts the same seven launch values: login,
+password, character ID, IPv4 integer, port, and two cookies. Its
+`FUN_00402cd0` confirms these fields in REA evidence
+`ev_bc0bda4db0510683087472ffb6ac945d776a090857215ab5e9e6d07b0c8a1d32`.
+With the recovered protocol adaptations, it rendered Omni Training with
+players and creatures, moved with valid persisted coordinates, and teleported
+to Borealis and back. The recovered wire differences are now supported directly
+by the Go server; the temporary network probe established their initial runtime
+behavior. See
+[the 13.2 protocol findings](protocol-13.2.md) for the wire evidence and limits.
+
+## Remaining checks for reaching the selected version
1. Preserve the pristine 11.0 reference and use a separate extraction/client
copy for any upgrade experiment. Rediscover mounted media and running
processes; no historical drive letter or session is guaranteed current.
-2. Inspect the recovered 13.2 installer/version metadata and determine which
- build it produces. If it stops before 13.24, identify the missing hotfixes
- rather than silently treating 13.2 as the agreed final build.
-3. Establish a working application path from the recovered 12.0 CD, or recover
- the missing early cumulative/incremental path from 11.0. The listed sequence
- has not been run, and archive extraction alone does not prove an installer
- will recognize the resulting directory.
+2. Recover or identify the hotfix packages after the verified 13.2 marker.
+ Inspect their resulting binaries and metadata rather than treating the
+ abbreviated 13.2 package name as the agreed final 13.24 build.
+3. Preserve the verified isolated 12.0-to-13.2 path. Recover the remaining
+ hotfixes or establish through authoritative build evidence that they are
+ included; the present 13.2 marker does not resolve that question.
4. Compare the Omni-Entertainment gathering area against the user's 11.0
screenshots. Comparing 13.2 with 13.4 should help narrow the demolition,
but inspect the assets/scene before assigning the change to a patch.
@@ -232,5 +306,5 @@ no surviving copy exists anywhere.
selected build. Existing 11.0 reverse-engineering addresses and layouts
must not be assumed to apply to 13.24. Run clients windowed.
-The user intends to give the main thread this document and ask it to perform
-the upgrade work. This research handoff itself did not upgrade anything.
+The Omni-Entertainment scenery comparison and the complete 13.24 build remain
+open. The isolated 13.2 installation is a concrete intermediate result.
diff --git a/server/control.go b/server/control.go
@@ -9,21 +9,61 @@ import (
"net/http"
"sort"
"strconv"
+ "strings"
"time"
+
+ "go.yaml.in/yaml/v3"
)
func (server *server) controlPage(w http.ResponseWriter, r *http.Request) {
- // Snapshot connected players before rendering the controls.
+ // Users remain visible while offline or reconnecting between zones.
server.mutex.Lock()
seconds := int(server.gameSeconds_locked())
- var players []character
+ players := server.users_locked()
+ connected := make(map[uint32]bool)
for id, client := range server.clients {
- if client.ready {
- players = append(players, *server.characters[id])
+ connected[id] = client.ready
+ }
+ server.mutex.Unlock()
+
+ w.Header().Set("Content-Type", "text/html; charset=utf-8")
+ fmt.Fprint(w, "<!doctype html><html><head><title>Server controls</title></head><body><h1>Server controls</h1><p><a href='/control'>Refresh</a></p>")
+ fmt.Fprintf(w, "<p>Game time: %02d:%02d. A day has 27 hours; time advances at 15x.</p>", seconds/3600, seconds/60%60)
+ fmt.Fprintf(w, "<form method='post' action='/time'><label>Hour <input type='number' name='hour' min='0' max='26' value='%d' required></label> <label>Minute <input type='number' name='minute' min='0' max='59' value='%d' required></label> <button>Set time</button></form>", seconds/3600, seconds/60%60)
+ fmt.Fprint(w, "<form method='post' action='/reload-npcs'><button>Reload NPC data</button></form><h2>Users</h2><table><tr><th>ID</th><th>Name</th><th>Status</th><th>Zone</th></tr>")
+ for _, player := range players {
+ status := "Offline"
+ if connected[player.ID] {
+ status = "Connected"
}
+ fmt.Fprintf(w, "<tr><td>%d</td><td><a href='/users/%d'>%s</a></td><td>%s</td><td>%s (%d)</td></tr>", player.ID, player.ID, html.EscapeString(player.Name), status, html.EscapeString(playfields[player.Playfield].name), player.Playfield)
}
+ fmt.Fprint(w, "</table><h2>Create user</h2><form method='post' action='/users'><label>Name <input name='name' required maxlength='254'></label> <button>Create user</button></form></body></html>")
+}
+
+func (server *server) userPage(w http.ResponseWriter, r *http.Request) {
+ id, err := strconv.ParseUint(r.PathValue("character"), 10, 32)
+ if err != nil {
+ http.Error(w, "Invalid user", http.StatusBadRequest)
+ return
+ }
+ server.mutex.Lock()
+ player := server.characters[uint32(id)]
+ if player == nil || player.npc {
+ server.mutex.Unlock()
+ http.NotFound(w, r)
+ return
+ }
+ data := player.userData()
+ connected := server.clients[data.ID] != nil && server.clients[data.ID].ready
server.mutex.Unlock()
- sort.Slice(players, func(i, j int) bool { return players[i].id < players[j].id })
+ contents, err := yaml.Marshal(data)
+ if err != nil {
+ http.Error(w, err.Error(), http.StatusInternalServerError)
+ return
+ }
+
+ // Keep the complete original zone catalog on each user's page.
var zones []uint32
for id := range playfields {
zones = append(zones, id)
@@ -36,29 +76,84 @@ func (server *server) controlPage(w http.ResponseWriter, r *http.Request) {
})
w.Header().Set("Content-Type", "text/html; charset=utf-8")
- fmt.Fprint(w, "<!doctype html><html><head><title>Server controls</title></head><body><h1>Server controls</h1><p><a href='/control'>Refresh</a></p>")
- fmt.Fprintf(w, "<p>Game time: %02d:%02d. A day has 27 hours; time advances at 15x.</p>", seconds/3600, seconds/60%60)
- fmt.Fprintf(w, "<form method='post' action='/time'><label>Hour <input type='number' name='hour' min='0' max='26' value='%d' required></label> <label>Minute <input type='number' name='minute' min='0' max='59' value='%d' required></label> <button>Set time</button></form>", seconds/3600, seconds/60%60)
+ fmt.Fprint(w, "<!doctype html><html><head><title>User</title></head><body><p><a href='/control'>All users</a></p>")
+ fmt.Fprintf(w, "<h1>%s</h1><p>User %d. Connected: %t.</p>", html.EscapeString(data.Name), data.ID, connected)
fmt.Fprint(w, "<p>Zones without disc assets and internal dependency maps are disabled.</p>")
- fmt.Fprint(w, "<form method='post' action='/reload-npcs'><button>Reload NPC data</button></form>")
- for _, player := range players {
- fmt.Fprintf(w, "<p>%s: playfield %d, position %.2f %.2f %.2f</p>", html.EscapeString(player.name), player.playfield, player.position[0], player.position[1], player.position[2])
- fmt.Fprintf(w, "<form method='post' action='/teleport/%d'><label>Zone <select name='playfield'>", player.id)
- for _, id := range zones {
- attributes := ""
- if id == player.playfield {
- attributes += " selected"
- }
- if playfields[id].unavailable {
- attributes += " disabled"
- }
- fmt.Fprintf(w, "<option value='%d'%s>%s (%d)</option>", id, attributes, html.EscapeString(playfields[id].name), id)
+ fmt.Fprintf(w, "<form method='post' action='/teleport/%d'><label>Zone <select name='playfield'>", data.ID)
+ for _, id := range zones {
+ attributes := ""
+ if id == data.Playfield {
+ attributes += " selected"
}
- fmt.Fprint(w, "</select></label> <button>Teleport</button></form>")
+ if playfields[id].unavailable {
+ attributes += " disabled"
+ }
+ fmt.Fprintf(w, "<option value='%d'%s>%s (%d)</option>", id, attributes, html.EscapeString(playfields[id].name), id)
}
+ fmt.Fprint(w, "</select></label> <button>Teleport</button></form>")
+ fmt.Fprintf(w, "<h2>Character data</h2><p>ID is fixed. Position is XYZ; rotation is XYZW. Saving reconnects an online character to apply the data.</p><form method='post' action='/users/%d'><textarea name='data' rows='20' cols='80' required>%s</textarea><p><button>Save character</button></p></form>", data.ID, html.EscapeString(string(contents)))
fmt.Fprint(w, "</body></html>")
}
+func (server *server) createUser(w http.ResponseWriter, r *http.Request) {
+ name := strings.TrimSpace(r.FormValue("name"))
+ server.mutex.Lock()
+ player := server.newCharacter_locked()
+ player.name = name
+ if err := player.userData().validate(); err != nil {
+ delete(server.characters, player.id)
+ server.nextCharacter--
+ server.mutex.Unlock()
+ http.Error(w, err.Error(), http.StatusBadRequest)
+ return
+ }
+ err := server.saveUsers_locked()
+ if err != nil {
+ delete(server.characters, player.id)
+ server.nextCharacter--
+ }
+ server.mutex.Unlock()
+ if err != nil {
+ http.Error(w, err.Error(), http.StatusInternalServerError)
+ return
+ }
+ http.Redirect(w, r, fmt.Sprintf("/users/%d", player.id), http.StatusSeeOther)
+}
+
+func (server *server) editUser(w http.ResponseWriter, r *http.Request) {
+ id, err := strconv.ParseUint(r.PathValue("character"), 10, 32)
+ if err != nil {
+ http.Error(w, "Invalid user", http.StatusBadRequest)
+ return
+ }
+ server.mutex.Lock()
+ player := server.characters[uint32(id)]
+ exists := player != nil && !player.npc
+ server.mutex.Unlock()
+ if !exists {
+ http.NotFound(w, r)
+ return
+ }
+ var data userData
+ if err := decodeUsers(strings.NewReader(r.FormValue("data")), &data); err != nil {
+ http.Error(w, err.Error(), http.StatusBadRequest)
+ return
+ }
+ if data.ID != uint32(id) {
+ http.Error(w, "User ID cannot change", http.StatusBadRequest)
+ return
+ }
+ if err := data.validate(); err != nil {
+ http.Error(w, err.Error(), http.StatusBadRequest)
+ return
+ }
+ if err := server.updateUser(data); err != nil {
+ http.Error(w, err.Error(), http.StatusInternalServerError)
+ return
+ }
+ http.Redirect(w, r, fmt.Sprintf("/users/%d", data.ID), http.StatusSeeOther)
+}
+
func (server *server) setGameTime(w http.ResponseWriter, r *http.Request) {
hour, hourError := strconv.Atoi(r.FormValue("hour"))
minute, minuteError := strconv.Atoi(r.FormValue("minute"))
@@ -88,10 +183,6 @@ func (server *server) setGameTime(w http.ResponseWriter, r *http.Request) {
}
func (server *server) teleportPlayer(w http.ResponseWriter, r *http.Request) {
- // Keep zone transitions from crossing a population replacement.
- server.npcReloadMutex.RLock()
- defer server.npcReloadMutex.RUnlock()
-
id, err := strconv.ParseUint(r.PathValue("character"), 10, 32)
if err != nil {
http.Error(w, "Invalid character", http.StatusBadRequest)
@@ -104,44 +195,72 @@ func (server *server) teleportPlayer(w http.ResponseWriter, r *http.Request) {
return
}
- // Remove the old connection from broadcasts while it changes playfield.
server.mutex.Lock()
- client := server.clients[uint32(id)]
- if client == nil || !client.ready {
+ character := server.characters[uint32(id)]
+ if character == nil || character.npc {
server.mutex.Unlock()
- http.Error(w, "Player is not connected", http.StatusNotFound)
+ http.NotFound(w, r)
return
}
- character := server.characters[uint32(id)]
- oldPlayfield := character.playfield
- character.playfield = uint32(playfield)
- character.position = zone.spawn
+ destination := character.userData()
+ server.mutex.Unlock()
+ destination.Playfield = uint32(playfield)
+ destination.Position = zone.spawn
if playfield == 950 {
- character.position[2] += float32((id-1)%4) * 3
+ destination.Position[2] += float32((id-1)%4) * 3
+ }
+ destination.Rotation = [4]float32{0, 0, 0, 1}
+ if err := server.updateUser(destination); err != nil {
+ http.Error(w, err.Error(), http.StatusInternalServerError)
+ return
+ }
+ http.Redirect(w, r, fmt.Sprintf("/users/%d", id), http.StatusSeeOther)
+}
+
+func (server *server) updateUser(destination userData) error {
+ // Persist the data before refreshing an online client's complete character.
+ server.npcReloadMutex.RLock()
+ defer server.npcReloadMutex.RUnlock()
+ server.mutex.Lock()
+ character := server.characters[destination.ID]
+ if character == nil || character.npc {
+ server.mutex.Unlock()
+ return fmt.Errorf("unknown user")
+ }
+ previous := *character
+ *character = *destination.character()
+ if err := server.saveUsers_locked(); err != nil {
+ *character = previous
+ server.mutex.Unlock()
+ return err
+ }
+ client := server.clients[character.id]
+ if client == nil || !client.ready {
+ server.mutex.Unlock()
+ return nil
}
- character.rotation = [4]float32{0, 0, 0, 1}
- destination := *character
client.ready = false
delete(server.clients, character.id)
server.mutex.Unlock()
// Original n3Teleport uses XYZ, a zone flag, two identities, and a stream.
var body []byte
- for _, value := range destination.position {
+ for _, value := range destination.Position {
body = binary.BigEndian.AppendUint32(body, math.Float32bits(value))
}
- for _, value := range []uint32{1, 0, 0, 40016, uint32(playfield), 0} {
+ for _, value := range []uint32{1, 0, 0, 40016, destination.Playfield, 0} {
body = binary.BigEndian.AppendUint32(body, value)
}
- if err := client.send(n3Packet(0x43197d22, 50000, uint32(id), body)); err != nil {
- http.Error(w, err.Error(), http.StatusInternalServerError)
- return
+ if err := client.send(n3Packet(0x43197d22, 50000, destination.ID, body)); err != nil {
+ client.conn.Close()
+ server.broadcast(previous.playfield, destination.ID, n3Packet(0x36510078, 50000, destination.ID, nil))
+ return err
}
- server.broadcast(oldPlayfield, uint32(id), n3Packet(0x36510078, 50000, uint32(id), nil))
+ server.broadcast(previous.playfield, destination.ID, n3Packet(0x36510078, 50000, destination.ID, nil))
body = []byte{127, 0, 0, 1, 0x1d, 0x4d}
- if err := client.send(systemPacket(0x3c, body)); err != nil {
- http.Error(w, err.Error(), http.StatusInternalServerError)
- return
+ err := client.send(systemPacket(0x3c, body))
+ if err != nil {
+ client.conn.Close()
}
- http.Redirect(w, r, "/control", http.StatusSeeOther)
+ return err
}
diff --git a/server/control_test.go b/server/control_test.go
@@ -11,7 +11,7 @@ import (
)
func TestSetGameTimeUpdatesConnectedPlayer(t *testing.T) {
- world := newServer()
+ world := newTestServer(t)
player := world.newCharacter()
player.playfield = 800
client, connection := net.Pipe()
@@ -45,7 +45,7 @@ func TestSetGameTimeUpdatesConnectedPlayer(t *testing.T) {
}
func TestSetGameTimeRejectsHourOutsideOriginalDay(t *testing.T) {
- world := newServer()
+ world := newTestServer(t)
request := httptest.NewRequest("POST", "/time", strings.NewReader("hour=27&minute=0"))
request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
response := httptest.NewRecorder()
@@ -57,13 +57,15 @@ func TestSetGameTimeRejectsHourOutsideOriginalDay(t *testing.T) {
}
}
-func TestControlPageListsOriginalZonesInDropdown(t *testing.T) {
- world := newServer()
+func TestUserPageListsOriginalZonesInDropdown(t *testing.T) {
+ world := newTestServer(t)
player := world.newCharacter()
world.clients[player.id] = &worldClient{ready: true}
response := httptest.NewRecorder()
- world.controlPage(response, httptest.NewRequest("GET", "/control", nil))
+ request := httptest.NewRequest("GET", "/users/1", nil)
+ request.SetPathValue("character", "1")
+ world.userPage(response, request)
body := response.Body.String()
if strings.Count(body, "<option value=") != 373 || !strings.Contains(body, "<select name='playfield'>") {
@@ -75,7 +77,7 @@ func TestControlPageListsOriginalZonesInDropdown(t *testing.T) {
}
func TestTeleportRejectsZoneWithoutOriginalAssets(t *testing.T) {
- world := newServer()
+ world := newTestServer(t)
player := world.newCharacter()
mux := http.NewServeMux()
mux.HandleFunc("POST /teleport/{character}", world.teleportPlayer)
diff --git a/server/main.go b/server/main.go
@@ -10,6 +10,7 @@ import (
"math"
"net"
"net/http"
+ "os"
"strings"
"time"
)
@@ -17,6 +18,10 @@ import (
func main() {
server := newServer()
http.HandleFunc("GET /control", server.controlPage)
+ http.HandleFunc("GET /users/{character}", server.userPage)
+ http.HandleFunc("POST /users", server.createUser)
+ http.HandleFunc("POST /users/{character}", server.editUser)
+ http.Handle("GET /browser/", http.StripPrefix("/browser/", http.FileServer(http.Dir("browser"))))
http.HandleFunc("POST /time", server.setGameTime)
http.HandleFunc("POST /teleport/{character}", server.teleportPlayer)
http.HandleFunc("POST /reload-npcs", server.reloadNPCData)
@@ -24,10 +29,10 @@ func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
log.Printf("HTTP %s %s", r.Method, r.URL.Path)
if strings.HasSuffix(r.URL.Path, "dimensions.txt") {
- fmt.Fprint(w, "STARTINFO\r\nconnect=127.0.0.1\r\ndescription=Local Rubi-Ka\r\nversion=11.0\r\nports=7500\r\nurl=http://127.0.0.1:8080/messages\r\nENDINFO\r\n")
+ dimensionList(w, r)
return
}
- fmt.Fprint(w, "<html><body>Local Anarchy Online 11.0 development server.</body></html>")
+ fmt.Fprint(w, "<html><body>Local Anarchy Online development server.</body></html>")
})
go func() {
log.Fatal(http.ListenAndServe("127.0.0.1:8080", nil))
@@ -55,6 +60,20 @@ func main() {
}
}
+func dimensionList(w http.ResponseWriter, r *http.Request) {
+ // Let the preserved release copy and upgraded copy use their own launcher versions.
+ version := "11.0"
+ if r.URL.Path == "/target/dimensions.txt" {
+ contents, err := os.ReadFile("client-target/version.id")
+ if err != nil {
+ http.Error(w, err.Error(), http.StatusServiceUnavailable)
+ return
+ }
+ version = strings.TrimSpace(string(contents))
+ }
+ fmt.Fprintf(w, "STARTINFO\r\nconnect=127.0.0.1\r\ndescription=Local Rubi-Ka\r\nversion=%s\r\nports=7500\r\nurl=http://127.0.0.1:8080/messages\r\nENDINFO\r\n", version)
+}
+
func readPacket(r io.Reader) ([]byte, error) {
// The length excludes four-byte alignment padding used by the launcher.
header := make([]byte, 16)
@@ -104,20 +123,45 @@ func (server *server) serveLogin(conn net.Conn) error {
response = systemPacket(0x24, []byte("0123456789abcdef0123456789abcdef\x00"))
case 0x25:
// Local test credentials are accepted without contacting Funcom.
- character = server.newCharacter()
- var body []byte
- for _, value := range []uint32{1, 3, character.id, character.playfield, 0, 3, character.id, uint32(len(character.name))} {
- body = binary.BigEndian.AppendUint32(body, value)
+ server.mutex.Lock()
+ users := server.users_locked()
+ if len(users) == 0 || len(packet) == 20 {
+ // The direct-launch test helpers request a fresh synthetic session.
+ character = server.newCharacter_locked()
+ if err := server.saveUsers_locked(); err != nil {
+ server.mutex.Unlock()
+ return err
+ }
+ users = []userData{character.userData()}
}
- body = append(body, character.name...)
- for _, value := range []uint32{5, 1, 1, 1, 0, 0, 0} {
- body = binary.BigEndian.AppendUint32(body, value)
+ character = server.characters[users[0].ID]
+ server.mutex.Unlock()
+ body := binary.BigEndian.AppendUint32(nil, uint32(len(users)))
+ for _, user := range users {
+ for _, value := range []uint32{3, user.ID, user.Playfield, 0, 3, user.ID, uint32(len(user.Name))} {
+ body = binary.BigEndian.AppendUint32(body, value)
+ }
+ body = append(body, user.Name...)
+ for _, value := range []uint32{5, uint32(user.Level), 1, 1, 0, 0, 0} {
+ body = binary.BigEndian.AppendUint32(body, value)
+ }
}
response = systemPacket(0x0e, body)
case 0x0f, 0x16:
+ if len(packet) < 24 {
+ return fmt.Errorf("short character selection")
+ }
+ server.mutex.Lock()
+ character = server.characters[binary.BigEndian.Uint32(packet[20:24])]
+ if character == nil || character.npc {
+ server.mutex.Unlock()
+ return fmt.Errorf("unknown selected user")
+ }
+ id := character.id
+ server.mutex.Unlock()
// Redirect the test character to the local world connection.
body := make([]byte, 18)
- binary.BigEndian.PutUint32(body[:4], character.id)
+ binary.BigEndian.PutUint32(body[:4], id)
copy(body[4:8], []byte{127, 0, 0, 1})
binary.BigEndian.PutUint16(body[8:10], 7501)
response = systemPacket(0x17, body)
@@ -184,14 +228,20 @@ func (server *server) serveWorldConnection(conn net.Conn) error {
switch binary.BigEndian.Uint16(packet[2:4]) {
case 1:
if binary.BigEndian.Uint32(packet[16:20]) == 0x1b {
+ // The recovered 13.2 client uses this message ID on its first cookie.
+ client.target = binary.BigEndian.Uint16(packet[0:2]) == 0xdfdf
server.npcReloadMutex.RLock()
server.mutex.Lock()
character = server.characters[binary.BigEndian.Uint32(packet[20:24])]
- if character == nil {
+ if character == nil || character.npc {
server.mutex.Unlock()
server.npcReloadMutex.RUnlock()
return fmt.Errorf("unknown world character")
}
+ if previous := server.clients[character.id]; previous != nil {
+ previous.ready = false
+ previous.conn.Close()
+ }
server.clients[character.id] = client
client.id = character.id
updates := [][]byte{playfieldPacket(character), characterPacket(character)}
@@ -206,7 +256,7 @@ func (server *server) serveWorldConnection(conn net.Conn) error {
}
}
}
- updates = append(updates, fullCharacterPacket(character.id))
+ updates = append(updates, fullCharacterPacket(character))
updates = append(updates, gameTimePacket(character.id, server.gameSeconds_locked()))
spawn := characterPacket(character)
playfield := character.playfield
@@ -226,8 +276,11 @@ func (server *server) serveWorldConnection(conn net.Conn) error {
}
case 10:
// The client compresses individual movement messages with zlib.
- body := packet[20:]
- if binary.BigEndian.Uint32(packet[16:20]) != 0 {
+ body := packet[16:]
+ if !client.target {
+ body = packet[20:]
+ }
+ if !client.target && binary.BigEndian.Uint32(packet[16:20]) != 0 {
reader, err := zlib.NewReader(bytes.NewReader(body))
if err != nil {
return err
@@ -279,6 +332,13 @@ func (server *server) serveWorldConnection(conn net.Conn) error {
server.mutex.Unlock()
server.broadcast(playfield, character.id, response)
case 0x54111123:
+ if client.target {
+ if len(body) < 49 {
+ return fmt.Errorf("short target character movement message")
+ }
+ // Normalize the extra byte before decoding and relaying movement.
+ body = append(body[:20:20], body[21:]...)
+ }
if len(body) < 48 {
return fmt.Errorf("short character movement message")
}
@@ -295,6 +355,10 @@ func (server *server) serveWorldConnection(conn net.Conn) error {
}
playfield := character.playfield
log.Printf("Character %d action=%d position=%v", character.id, binary.BigEndian.Uint32(body[16:20]), character.position)
+ if err := server.saveUsers_locked(); err != nil {
+ server.mutex.Unlock()
+ return err
+ }
server.mutex.Unlock()
server.broadcast(playfield, character.id, n3Packet(0x54111123, 50000, character.id, body[16:]))
}
diff --git a/server/main_test.go b/server/main_test.go
@@ -8,11 +8,31 @@ import (
"net"
"net/http"
"net/http/httptest"
+ "os"
"strings"
"testing"
"time"
)
+func TestTargetDimensionListUsesInstalledVersionWithoutChangingReleaseList(t *testing.T) {
+ useNPCData(t, editedNPCData)
+ if err := os.Mkdir("client-target", 0755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile("client-target/version.id", []byte("13.2\r\n"), 0644); err != nil {
+ t.Fatal(err)
+ }
+ target := httptest.NewRecorder()
+ release := httptest.NewRecorder()
+
+ dimensionList(target, httptest.NewRequest("GET", "/target/dimensions.txt", nil))
+ dimensionList(release, httptest.NewRequest("GET", "/dimensions/dimensions.txt", nil))
+
+ if !strings.Contains(target.Body.String(), "version=13.2\r\n") || !strings.Contains(release.Body.String(), "version=11.0\r\n") {
+ t.Fatalf("dimension versions: %s %s", target.Body.String(), release.Body.String())
+ }
+}
+
func TestReadPacketConsumesPadding(t *testing.T) {
data, err := hex.DecodeString("0001000100010015000000010000000000000024410000000002000100010014000000010000000000000023")
if err != nil {
@@ -38,7 +58,7 @@ func TestReadPacketConsumesPadding(t *testing.T) {
}
func TestTeleportReconnectsSameCharacterInDestination(t *testing.T) {
- world := newServer()
+ world := newTestServer(t)
world.newCharacter()
client, connection := net.Pipe()
defer client.Close()
@@ -72,6 +92,8 @@ func TestTeleportReconnectsSameCharacterInDestination(t *testing.T) {
t.Fatal(err)
}
<-done
+ page := httptest.NewRecorder()
+ world.controlPage(page, httptest.NewRequest("GET", "/control", nil))
client.Close()
reconnected, nextConnection := net.Pipe()
defer reconnected.Close()
@@ -87,6 +109,9 @@ func TestTeleportReconnectsSameCharacterInDestination(t *testing.T) {
if response.Code != http.StatusSeeOther {
t.Fatalf("teleport HTTP status: %d", response.Code)
}
+ if !strings.Contains(page.Body.String(), "href='/users/1'>Local Explorer 1</a>") {
+ t.Fatal("user disappeared while reconnecting")
+ }
if hex.EncodeToString(teleport[20:36]) != "43197d220000c3500000000100000000" || hex.EncodeToString(teleport[48:72]) != "00000001000000000000000000009c500000032000000000" {
t.Fatalf("original teleport: %x", teleport)
}
@@ -99,7 +124,7 @@ func TestTeleportReconnectsSameCharacterInDestination(t *testing.T) {
}
func TestTwoPlayersShareMovementAndDisconnect(t *testing.T) {
- world := newServer()
+ world := newTestServer(t)
world.newCharacter()
world.newCharacter()
first, firstServer := net.Pipe()
@@ -151,7 +176,7 @@ func TestTwoPlayersShareMovementAndDisconnect(t *testing.T) {
}
func TestSitAndStandAreAcknowledged(t *testing.T) {
- world := newServer()
+ world := newTestServer(t)
world.newCharacter()
client, connection := net.Pipe()
defer client.Close()
@@ -185,7 +210,7 @@ func TestSitAndStandAreAcknowledged(t *testing.T) {
}
func TestLogoutCompletesAfterCountdown(t *testing.T) {
- world := newServer()
+ world := newTestServer(t)
world.newCharacter()
client, connection := net.Pipe()
defer client.Close()
@@ -248,7 +273,7 @@ func TestLoginChallengeAcrossSplitWrites(t *testing.T) {
func TestWorldCookieThenPing(t *testing.T) {
client, server := net.Pipe()
- world := newServer()
+ world := newTestServer(t)
world.newCharacter()
defer client.Close()
done := make(chan error, 1)
diff --git a/server/npc_data_test.go b/server/npc_data_test.go
@@ -68,7 +68,7 @@ func useNPCData(t *testing.T, contents string) {
func TestNPCDataPreservesGeneratedPopulation(t *testing.T) {
digest := sha256.New()
- world := newServer()
+ world := newTestServer(t)
for id := uint32(1000000); id < 1062175; id++ {
spawn := world.characters[id]
if spawn == nil {
@@ -91,7 +91,7 @@ func TestNPCDataPreservesGeneratedPopulation(t *testing.T) {
}
func TestReloadNPCDataUpdatesConnectedPlayer(t *testing.T) {
- world := newServer()
+ world := newTestServer(t)
player := world.newCharacter()
client, connection := net.Pipe()
defer client.Close()
@@ -142,7 +142,7 @@ func TestReloadNPCDataUpdatesConnectedPlayer(t *testing.T) {
}
func TestReloadNPCDataRejectsUnclassifiedAppearance(t *testing.T) {
- world := newServer()
+ world := newTestServer(t)
useNPCData(t, strings.ReplaceAll(editedNPCData, "appearance_status: placeholder_creature", "appearance_status: typo"))
mux := http.NewServeMux()
mux.HandleFunc("POST /reload-npcs", world.reloadNPCData)
diff --git a/server/npcs_test.go b/server/npcs_test.go
@@ -6,16 +6,53 @@ import (
"encoding/json"
"net"
"os"
+ "path/filepath"
"testing"
"time"
)
func TestMain(m *testing.M) {
- // The server reads data relative to the project root.
+ // Keep persistence tests away from the developer's live user file.
if err := os.Chdir(".."); err != nil {
panic(err)
}
- os.Exit(m.Run())
+ directory, err := os.MkdirTemp("", "ao-tests-")
+ if err != nil {
+ panic(err)
+ }
+ for _, name := range []string{"data", "tools"} {
+ if err := os.Mkdir(filepath.Join(directory, name), 0755); err != nil {
+ panic(err)
+ }
+ }
+ for _, name := range []string{"data/npc_spawns.yaml", "data/terrain.bin", "tools/original-npc-spawns.json"} {
+ contents, err := os.ReadFile(name)
+ if err != nil {
+ panic(err)
+ }
+ if err := os.WriteFile(filepath.Join(directory, name), contents, 0644); err != nil {
+ panic(err)
+ }
+ }
+ if err := os.Chdir(directory); err != nil {
+ panic(err)
+ }
+ code := m.Run()
+ if err := os.Chdir(os.TempDir()); err != nil {
+ panic(err)
+ }
+ if err := os.RemoveAll(directory); err != nil {
+ panic(err)
+ }
+ os.Exit(code)
+}
+
+func newTestServer(t *testing.T) *server {
+ t.Helper()
+ if err := os.Remove("data/users.yaml"); err != nil && !os.IsNotExist(err) {
+ t.Fatal(err)
+ }
+ return newServer()
}
func readWorldUpdates(t *testing.T, client net.Conn) [][]byte {
@@ -34,7 +71,7 @@ func readWorldUpdates(t *testing.T, client net.Conn) [][]byte {
}
func TestOriginalPopulationsAreSharedAndZoneScoped(t *testing.T) {
- world := newServer()
+ world := newTestServer(t)
var clients []net.Conn
zones := []uint32{950, 950, 952, 954, 646}
for _, zone := range zones {
@@ -108,7 +145,7 @@ func TestEveryAuthoredPopulationIsSent(t *testing.T) {
if err := json.Unmarshal(data, &catalog); err != nil {
t.Fatal(err)
}
- world := newServer()
+ world := newTestServer(t)
total, populated := 0, 0
var guard, highLevel []byte
diff --git a/server/roaming_test.go b/server/roaming_test.go
@@ -36,7 +36,7 @@ func TestRoamingIsSharedBoundedAndZoneScoped(t *testing.T) {
- [100, 14, 100]
`
useNPCData(t, data)
- world := newServer()
+ world := newTestServer(t)
var clients []net.Conn
for range 2 {
player := world.newCharacter()
@@ -98,7 +98,7 @@ func TestRoamingIsSharedBoundedAndZoneScoped(t *testing.T) {
func TestRoamingDoesNotResetPositionDuringWalk(t *testing.T) {
useNPCData(t, strings.ReplaceAll(editedNPCData, "fixed_point", "authored_point"))
- world := newServer()
+ world := newTestServer(t)
player := world.newCharacter()
client, connection := net.Pipe()
defer client.Close()
@@ -142,7 +142,7 @@ func TestRoamingDoesNotResetPositionDuringWalk(t *testing.T) {
func TestJoiningPlayerReceivesOngoingNPCMovement(t *testing.T) {
useNPCData(t, strings.ReplaceAll(editedNPCData, "fixed_point", "authored_point"))
- world := newServer()
+ world := newTestServer(t)
world.characters[1000000].position = [3]float32{53, 14, 56}
world.characters[1000000].roaming.moving = true
player := world.newCharacter()
@@ -169,7 +169,7 @@ func TestJoiningPlayerReceivesOngoingNPCMovement(t *testing.T) {
func TestRoamingStopsAndPausesAtDestination(t *testing.T) {
useNPCData(t, strings.ReplaceAll(editedNPCData, "fixed_point", "authored_point"))
- world := newServer()
+ world := newTestServer(t)
player := world.newCharacter()
client, connection := net.Pipe()
defer client.Close()
@@ -204,7 +204,7 @@ func TestRoamingStopsAndPausesAtDestination(t *testing.T) {
func TestFixedCreatureDoesNotRoam(t *testing.T) {
useNPCData(t, editedNPCData)
- world := newServer()
+ world := newTestServer(t)
if world.characters[1000000].roaming != nil {
t.Fatal("fixed creature received roaming behavior")
@@ -213,7 +213,7 @@ func TestFixedCreatureDoesNotRoam(t *testing.T) {
func TestRoamingFollowsTerrainWithAuthoredOffset(t *testing.T) {
useNPCData(t, strings.ReplaceAll(editedNPCData, "fixed_point", "authored_point"))
- world := newServer()
+ world := newTestServer(t)
world.terrain[950] = &terrain{width: 1, height: 1, spacing: 128, scale: 1, heights: []byte{0, 64, 0, 64}}
player := world.newCharacter()
client, connection := net.Pipe()
@@ -244,7 +244,7 @@ func TestRoamingFollowsTerrainWithAuthoredOffset(t *testing.T) {
func TestRoamingStopsAtTerrainBoundary(t *testing.T) {
useNPCData(t, strings.ReplaceAll(editedNPCData, "fixed_point", "authored_point"))
- world := newServer()
+ world := newTestServer(t)
world.terrain[950] = &terrain{width: 1, height: 1, spacing: 64, scale: 1, heights: []byte{0, 32, 0, 32}}
player := world.newCharacter()
client, connection := net.Pipe()
diff --git a/server/state.go b/server/state.go
@@ -24,10 +24,11 @@ type character struct {
}
type worldClient struct {
- conn net.Conn
- mutex sync.Mutex
- ready bool
- id uint32
+ conn net.Conn
+ mutex sync.Mutex
+ ready bool
+ id uint32
+ target bool
}
func (client *worldClient) send(packet []byte) error {
@@ -35,6 +36,9 @@ func (client *worldClient) send(packet []byte) error {
client.mutex.Lock()
defer client.mutex.Unlock()
packet = append([]byte(nil), packet...)
+ if client.target && binary.BigEndian.Uint16(packet[2:4]) == 10 {
+ packet = targetPacket(packet)
+ }
binary.BigEndian.PutUint32(packet[12:16], client.id)
_, err := client.conn.Write(packet)
return err
@@ -73,6 +77,9 @@ func newServer() *server {
server.characters[spawn.id] = &spawn
}
server.nextNPC = 1000000 + uint32(len(spawns))
+ if err := server.loadUsers(); err != nil {
+ panic(err)
+ }
return server
}
@@ -84,6 +91,10 @@ func (server *server) gameSeconds_locked() float64 {
func (server *server) newCharacter() *character {
server.mutex.Lock()
defer server.mutex.Unlock()
+ return server.newCharacter_locked()
+}
+
+func (server *server) newCharacter_locked() *character {
server.nextCharacter++
character := &character{
id: server.nextCharacter, name: fmt.Sprintf("Local Explorer %d", server.nextCharacter),
diff --git a/server/target_protocol.go b/server/target_protocol.go
@@ -0,0 +1,52 @@
+package main
+
+import "encoding/binary"
+
+func targetPacket(packet []byte) []byte {
+ // Convert the shared 11.0 message representation to the recovered 13.2 wire layout.
+ packet = packet[:binary.BigEndian.Uint16(packet[6:8])]
+ switch binary.BigEndian.Uint32(packet[20:24]) {
+ case 0x5f4b1a39:
+ // Playfield initialization ends after its two world origins.
+ packet = packet[:93]
+ case 0x271b3a6b:
+ // Appearance has a wider race field and shifts every subsequent field.
+ appearance := uint32(binary.BigEndian.Uint16(packet[67:69]))
+ packed := appearance&3 | (appearance>>2&3)<<3 | (appearance>>4&7)<<5
+ packed |= (appearance>>7&3)<<8 | (appearance>>9&3)<<10 | (appearance>>11&31)<<12
+ tail := append([]byte(nil), packet[69:]...)
+ packet = binary.BigEndian.AppendUint32(packet[:67], packed)
+ packet = append(packet, tail...)
+ if binary.BigEndian.Uint32(packet[37:41])&1 != 0 {
+ // The new NPC stat 455 follows the length-prefixed name.
+ nameEnd := 72 + int(packet[71])
+ tail = append([]byte(nil), packet[nameEnd:]...)
+ packet = append(packet[:nameEnd], 0, 0)
+ packet = append(packet, tail...)
+ }
+ case 0x29304349:
+ // FullCharacter has seven encoded lists before its stats.
+ tail := append([]byte(nil), packet[64:]...)
+ packet = binary.BigEndian.AppendUint32(packet[:64], 1009)
+ packet = append(packet, tail...)
+ case 0x54111123:
+ // CharDCMove carries a byte between the action and position.
+ tail := append([]byte(nil), packet[40:]...)
+ packet = append(packet[:40], 0)
+ packet = append(packet, tail...)
+ case 0x43197d22:
+ // Teleport carries the full playfield proxy after XYZ.
+ zone := binary.BigEndian.Uint32(packet[64:68])
+ tail := append([]byte(nil), packet[52:]...)
+ packet = append(packet[:48], 'a')
+ for _, value := range []uint32{51100, zone, zone, 0, 40016, zone} {
+ packet = binary.BigEndian.AppendUint32(packet, value)
+ }
+ packet = append(packet, tail...)
+ }
+
+ // The 13.2 N3 envelope omits the old compression DWORD.
+ packet = append(packet[:16], packet[20:]...)
+ binary.BigEndian.PutUint16(packet[6:8], uint16(len(packet)))
+ return append(packet, make([]byte, (-len(packet))&3)...)
+}
diff --git a/server/target_protocol_test.go b/server/target_protocol_test.go
@@ -0,0 +1,158 @@
+package main
+
+import (
+ "encoding/binary"
+ "encoding/hex"
+ "net"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+)
+
+func TestTargetWorldInitializationUsesRecoveredLayouts(t *testing.T) {
+ useNPCData(t, editedNPCData)
+ world := newTestServer(t)
+ world.newCharacter()
+ client, connection := net.Pipe()
+ defer client.Close()
+ client.SetDeadline(time.Now().Add(5 * time.Second))
+ go func() { defer connection.Close(); world.serveWorldConnection(connection) }()
+ cookie, _ := hex.DecodeString("dfdf00010001002000000001000000020000001b000000010000000000000000")
+ var playfield, player, npc, full []byte
+
+ client.Write(cookie)
+ for {
+ packet, err := readPacket(client)
+ if err != nil {
+ t.Fatal(err)
+ }
+ switch binary.BigEndian.Uint32(packet[16:20]) {
+ case 0x5f4b1a39:
+ playfield = packet
+ case 0x271b3a6b:
+ if binary.BigEndian.Uint32(packet[24:28]) == 1 {
+ player = packet
+ } else {
+ npc = packet
+ }
+ case 0x29304349:
+ full = packet
+ case 0x5f52412e:
+ goto initialized
+ }
+ }
+initialized:
+
+ if len(playfield) != 89 || hex.EncodeToString(player[63:68]) != "0000062911" || string(player[68:85]) != "Local Explorer 1\x00" {
+ t.Fatalf("target playfield or player: %x %x", playfield, player)
+ }
+ if hex.EncodeToString(npc[63:82]) != "000001c90b456469746564204e504300000007" {
+ t.Fatalf("target NPC appearance, name and new stat: %x", npc[63:82])
+ }
+ if hex.EncodeToString(full[60:76]) != "000003f100003f100000003600000001" {
+ t.Fatalf("target seventh list and first stat: %x", full[60:76])
+ }
+}
+
+func TestTargetMovementIsPersistedAndRelayedToReleaseClient(t *testing.T) {
+ useNPCData(t, editedNPCData)
+ world := newTestServer(t)
+ var clients []net.Conn
+ for id := uint32(1); id <= 2; id++ {
+ world.newCharacter()
+ client, connection := net.Pipe()
+ clients = append(clients, client)
+ defer client.Close()
+ client.SetDeadline(time.Now().Add(5 * time.Second))
+ go func() { defer connection.Close(); world.serveWorldConnection(connection) }()
+ cookie := systemPacket(0x1b, []byte{0, 0, 0, byte(id), 0, 0, 0, 0, 0, 0, 0, 0})
+ if id == 2 {
+ binary.BigEndian.PutUint16(cookie, 0xdfdf)
+ }
+ client.Write(cookie)
+ for {
+ packet, err := readPacket(client)
+ if err != nil {
+ t.Fatal(err)
+ }
+ keyOffset := 20
+ if id == 2 {
+ keyOffset = 16
+ }
+ if binary.BigEndian.Uint32(packet[keyOffset:]) == 0x5f52412e {
+ break
+ }
+ }
+ if id == 2 {
+ readPacket(clients[0])
+ }
+ ping := systemPacket(1, nil)
+ binary.BigEndian.PutUint16(ping[2:4], 11)
+ client.Write(ping)
+ readPacket(client)
+ }
+ movement, _ := hex.DecodeString("dfdf000a000100490000000200000002541111230000c350000000020000000000000001004254000041600000427400000000000000000000000000003f8000000000000000000000000000")
+
+ clients[1].Write(movement)
+ relay, err := readPacket(clients[0])
+ if err != nil {
+ t.Fatal(err)
+ }
+ restarted := newServer()
+
+ if restarted.characters[2].position != [3]float32{53, 14, 61} || restarted.characters[2].rotation != [4]float32{0, 0, 0, 1} {
+ t.Fatalf("target movement corrupted saved coordinates: %+v", restarted.characters[2])
+ }
+ if hex.EncodeToString(relay[36:52]) != "00000001425400004160000042740000" {
+ t.Fatalf("release client movement layout: %x", relay)
+ }
+}
+
+func TestTargetTeleportIncludesFullPlayfieldProxy(t *testing.T) {
+ useNPCData(t, editedNPCData)
+ world := newTestServer(t)
+ world.newCharacter()
+ client, connection := net.Pipe()
+ defer client.Close()
+ client.SetDeadline(time.Now().Add(5 * time.Second))
+ go func() { defer connection.Close(); world.serveWorldConnection(connection) }()
+ cookie, _ := hex.DecodeString("dfdf00010001002000000001000000020000001b000000010000000000000000")
+ client.Write(cookie)
+ for {
+ packet, err := readPacket(client)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if binary.BigEndian.Uint32(packet[16:20]) == 0x5f52412e {
+ break
+ }
+ }
+ // A ping ensures initialization is complete before the HTTP action.
+ ping := systemPacket(1, nil)
+ binary.BigEndian.PutUint16(ping[2:4], 11)
+ client.Write(ping)
+ readPacket(client)
+ request := httptest.NewRequest("POST", "/teleport/1", strings.NewReader("playfield=800"))
+ request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ request.SetPathValue("character", "1")
+ done := make(chan struct{})
+
+ go func() { world.teleportPlayer(httptest.NewRecorder(), request); close(done) }()
+ teleport, err := readPacket(client)
+ if err != nil {
+ t.Fatal(err)
+ }
+ redirect, err := readPacket(client)
+ if err != nil {
+ t.Fatal(err)
+ }
+ <-done
+
+ if hex.EncodeToString(teleport[44:89]) != "610000c79c00000320000003200000000000009c5000000320000000000000000000009c500000032000000000" {
+ t.Fatalf("target teleport proxy and identities: %x", teleport)
+ }
+ if binary.BigEndian.Uint32(redirect[16:20]) != 0x3c || world.characters[1].playfield != 800 {
+ t.Fatalf("target teleport redirect: %x", redirect)
+ }
+}
diff --git a/server/users.go b/server/users.go
@@ -0,0 +1,131 @@
+package main
+
+import (
+ "bytes"
+ "fmt"
+ "io"
+ "math"
+ "os"
+ "sort"
+ "strings"
+
+ "go.yaml.in/yaml/v3"
+)
+
+// User IDs are stable; each local user currently owns one character.
+type userData struct {
+ ID uint32 `yaml:"id"`
+ Name string `yaml:"name"`
+ Playfield uint32 `yaml:"playfield"`
+ Position [3]float32 `yaml:"position,flow"`
+ Rotation [4]float32 `yaml:"rotation,flow"`
+ Appearance uint16 `yaml:"appearance"`
+ MonsterData uint32 `yaml:"monster_data"`
+ Level uint16 `yaml:"level"`
+}
+
+func (character *character) userData() userData {
+ return userData{character.id, character.name, character.playfield, character.position,
+ character.rotation, character.appearance, character.monsterData, character.level}
+}
+
+func (data userData) character() *character {
+ return &character{id: data.ID, name: data.Name, playfield: data.Playfield, position: data.Position,
+ rotation: data.Rotation, appearance: data.Appearance, monsterData: data.MonsterData, level: data.Level}
+}
+
+func (data userData) validate() error {
+ if data.ID == 0 || data.ID >= 1000000 {
+ return fmt.Errorf("user ID must be between 1 and 999999")
+ }
+ if len(strings.TrimSpace(data.Name)) == 0 || len(data.Name) > 254 || strings.ContainsRune(data.Name, 0) {
+ return fmt.Errorf("name must contain 1-254 bytes without a NUL")
+ }
+ zone, exists := playfields[data.Playfield]
+ if !exists || zone.unavailable {
+ return fmt.Errorf("playfield has no playable client assets")
+ }
+ if data.Level == 0 {
+ return fmt.Errorf("level must be at least 1")
+ }
+ for index, value := range data.Position {
+ minimum, maximum := float32(0), float32(8191.875)
+ if index == 1 {
+ minimum, maximum = -2048, 2047.9375
+ }
+ if math.IsNaN(float64(value)) || value < minimum || value > maximum {
+ return fmt.Errorf("position cannot be represented by the client")
+ }
+ }
+ var magnitude float64
+ for _, value := range data.Rotation {
+ magnitude += float64(value) * float64(value)
+ }
+ if math.IsNaN(magnitude) || math.Abs(magnitude-1) > 0.01 {
+ return fmt.Errorf("rotation must be a unit quaternion in XYZW order")
+ }
+ return nil
+}
+
+func decodeUsers(reader io.Reader, value any) error {
+ decoder := yaml.NewDecoder(reader)
+ decoder.KnownFields(true)
+ if err := decoder.Decode(value); err != nil {
+ return err
+ }
+ var extra any
+ if err := decoder.Decode(&extra); err != io.EOF {
+ return fmt.Errorf("expected one YAML document")
+ }
+ return nil
+}
+
+func (server *server) loadUsers() error {
+ contents, err := os.ReadFile("data/users.yaml")
+ if os.IsNotExist(err) {
+ return nil
+ }
+ if err != nil {
+ return err
+ }
+ var users []userData
+ if err := decodeUsers(bytes.NewReader(contents), &users); err != nil {
+ return err
+ }
+ for _, user := range users {
+ if err := user.validate(); err != nil {
+ return fmt.Errorf("user %d: %w", user.ID, err)
+ }
+ if server.characters[user.ID] != nil {
+ return fmt.Errorf("duplicate user ID %d", user.ID)
+ }
+ server.characters[user.ID] = user.character()
+ if user.ID > server.nextCharacter {
+ server.nextCharacter = user.ID
+ }
+ }
+ return nil
+}
+
+func (server *server) users_locked() []userData {
+ users := make([]userData, 0)
+ for _, character := range server.characters {
+ if !character.npc {
+ users = append(users, character.userData())
+ }
+ }
+ sort.Slice(users, func(i, j int) bool { return users[i].ID < users[j].ID })
+ return users
+}
+
+func (server *server) saveUsers_locked() error {
+ contents, err := yaml.Marshal(server.users_locked())
+ if err != nil {
+ return err
+ }
+ // Replace the file only after the complete new document has been written.
+ if err := os.WriteFile("data/users.yaml.tmp", contents, 0600); err != nil {
+ return err
+ }
+ return os.Rename("data/users.yaml.tmp", "data/users.yaml")
+}
diff --git a/server/users_test.go b/server/users_test.go
@@ -0,0 +1,164 @@
+package main
+
+import (
+ "bytes"
+ "encoding/binary"
+ "encoding/hex"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "os"
+ "strings"
+ "testing"
+ "time"
+)
+
+func TestUserCreationEditingAndOfflineTeleportSurviveRestart(t *testing.T) {
+ useNPCData(t, editedNPCData)
+ world := newTestServer(t)
+ mux := http.NewServeMux()
+ mux.HandleFunc("POST /users", world.createUser)
+ mux.HandleFunc("POST /users/{character}", world.editUser)
+ mux.HandleFunc("POST /teleport/{character}", world.teleportPlayer)
+ creation := httptest.NewRequest("POST", "/users", strings.NewReader("name=Explorer"))
+ creation.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ created := httptest.NewRecorder()
+ data := `id: 1
+name: Edited Explorer
+playfield: 950
+position: [53, 14, 60]
+rotation: [0, 0, 0, 1]
+appearance: 789
+monster_data: 0
+level: 7
+`
+ edition := httptest.NewRequest("POST", "/users/1", strings.NewReader(url.Values{"data": {data}}.Encode()))
+ edition.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ edited := httptest.NewRecorder()
+ teleport := httptest.NewRequest("POST", "/teleport/1", strings.NewReader("playfield=800"))
+ teleport.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ teleported := httptest.NewRecorder()
+
+ mux.ServeHTTP(created, creation)
+ mux.ServeHTTP(edited, edition)
+ mux.ServeHTTP(teleported, teleport)
+ restarted := newServer()
+ page := httptest.NewRecorder()
+ restarted.controlPage(page, httptest.NewRequest("GET", "/control", nil))
+
+ for _, response := range []*httptest.ResponseRecorder{created, edited, teleported} {
+ if response.Code != http.StatusSeeOther || response.Header().Get("Location") != "/users/1" {
+ t.Fatalf("user form response: %d %s", response.Code, response.Body.String())
+ }
+ }
+ player := restarted.characters[1]
+ if player.name != "Edited Explorer" || player.playfield != 800 || player.level != 7 || player.appearance != 789 || player.position != [3]float32{679.625, 74.75, 537.875} {
+ t.Fatalf("saved character: %+v", player)
+ }
+ if restarted.nextCharacter != 1 || !strings.Contains(page.Body.String(), "href='/users/1'>Edited Explorer</a>") || !strings.Contains(page.Body.String(), "Offline") {
+ t.Fatalf("offline user disappeared: %s", page.Body.String())
+ }
+ contents, err := os.ReadFile("data/users.yaml")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if bytes.Contains(contents, []byte("Edited NPC")) {
+ t.Fatal("NPC population was written into the user file")
+ }
+}
+
+func TestUserEditorRejectsUnknownFieldsWithoutChangingSavedData(t *testing.T) {
+ useNPCData(t, editedNPCData)
+ world := newTestServer(t)
+ creation := httptest.NewRequest("POST", "/users", strings.NewReader("name=Explorer"))
+ creation.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ world.createUser(httptest.NewRecorder(), creation)
+ before, err := os.ReadFile("data/users.yaml")
+ if err != nil {
+ t.Fatal(err)
+ }
+ request := httptest.NewRequest("POST", "/users/1", strings.NewReader(url.Values{"data": {"id: 1\nname: Changed\nlevle: 7\n"}}.Encode()))
+ request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ request.SetPathValue("character", "1")
+ response := httptest.NewRecorder()
+
+ world.editUser(response, request)
+ after, err := os.ReadFile("data/users.yaml")
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ if response.Code != http.StatusBadRequest || world.characters[1].name != "Explorer" || !bytes.Equal(before, after) {
+ t.Fatalf("invalid YAML changed a user: %d %s", response.Code, response.Body.String())
+ }
+}
+
+func TestLauncherListsSavedUsersAndSelectsRequestedCharacter(t *testing.T) {
+ useNPCData(t, editedNPCData)
+ world := newTestServer(t)
+ for _, name := range []string{"First", "Second"} {
+ request := httptest.NewRequest("POST", "/users", strings.NewReader("name="+name))
+ request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ world.createUser(httptest.NewRecorder(), request)
+ }
+ restarted := newServer()
+ client, connection := net.Pipe()
+ defer client.Close()
+ client.SetDeadline(time.Now().Add(5 * time.Second))
+ go func() { defer connection.Close(); restarted.serveLogin(connection) }()
+
+ client.Write(systemPacket(0x25, []byte{0}))
+ list, err := readPacket(client)
+ if err != nil {
+ t.Fatal(err)
+ }
+ client.Write(systemPacket(0x16, []byte{0, 0, 0, 2}))
+ selection, err := readPacket(client)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ if binary.BigEndian.Uint32(list[20:24]) != 2 || !bytes.Contains(list, []byte("First")) || !bytes.Contains(list, []byte("Second")) || restarted.nextCharacter != 2 {
+ t.Fatalf("saved login list: %x", list)
+ }
+ if binary.BigEndian.Uint32(selection[20:24]) != 2 {
+ t.Fatalf("selected wrong user: %x", selection)
+ }
+}
+
+func TestEditedCharacterLevelAndPositionReachWorldClient(t *testing.T) {
+ useNPCData(t, editedNPCData)
+ world := newTestServer(t)
+ request := httptest.NewRequest("POST", "/users", strings.NewReader("name=Explorer"))
+ request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ world.createUser(httptest.NewRecorder(), request)
+ data := "id: 1\nname: Explorer\nplayfield: 950\nposition: [53, 14, 60]\nrotation: [0, 0, 0, 1]\nappearance: 789\nmonster_data: 0\nlevel: 7\n"
+ request = httptest.NewRequest("POST", "/users/1", strings.NewReader(url.Values{"data": {data}}.Encode()))
+ request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ request.SetPathValue("character", "1")
+ world.editUser(httptest.NewRecorder(), request)
+ restarted := newServer()
+ client, connection := net.Pipe()
+ defer client.Close()
+ client.SetDeadline(time.Now().Add(5 * time.Second))
+ go func() { defer connection.Close(); restarted.serveWorldConnection(connection) }()
+
+ client.Write(systemPacket(0x1b, []byte{0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0}))
+ updates := readWorldUpdates(t, client)
+
+ var spawn, full []byte
+ for _, packet := range updates {
+ switch binary.BigEndian.Uint32(packet[20:24]) {
+ case 0x271b3a6b:
+ if binary.BigEndian.Uint32(packet[28:32]) == 1 {
+ spawn = packet
+ }
+ case 0x29304349:
+ full = packet
+ }
+ }
+ if hex.EncodeToString(spawn[45:51]) != "01a800e001e0" || binary.BigEndian.Uint32(full[72:76]) != 7 {
+ t.Fatalf("saved position or level missing: %x %x", spawn, full)
+ }
+}
diff --git a/server/world.go b/server/world.go
@@ -122,13 +122,13 @@ func characterPacket(character *character) []byte {
return n3Packet(0x271b3a6b, 50000, character.id, body)
}
-func fullCharacterPacket(id uint32) []byte {
+func fullCharacterPacket(character *character) []byte {
// Version 16 begins with six encoded lists, followed by four stat lists.
body := binary.BigEndian.AppendUint32(nil, 16)
for range 6 {
body = binary.BigEndian.AppendUint32(body, 1009)
}
- stats := [][2]uint32{{54, 1}, {4, 1}, {47, 1}, {60, 1}, {59, 2}, {156, 100}, {16, 10}, {17, 10}, {18, 10}, {19, 10}, {20, 10}, {21, 10}, {27, 100}, {123, 100}, {124, 100}}
+ stats := [][2]uint32{{54, uint32(character.level)}, {4, uint32(character.appearance >> 4 & 7)}, {47, 1}, {60, uint32(character.appearance >> 9 & 3)}, {59, uint32(character.appearance >> 7 & 3)}, {156, 100}, {16, 10}, {17, 10}, {18, 10}, {19, 10}, {20, 10}, {21, 10}, {27, 100}, {123, 100}, {124, 100}}
body = binary.BigEndian.AppendUint32(body, uint32(len(stats)+1)*1009)
for _, stat := range stats {
body = binary.BigEndian.AppendUint32(body, stat[0])
@@ -142,5 +142,5 @@ func fullCharacterPacket(id uint32) []byte {
for _, value := range []uint32{0, 1009, 0, 0, 1009} {
body = binary.BigEndian.AppendUint32(body, value)
}
- return n3Packet(0x29304349, 50000, id, body)
+ return n3Packet(0x29304349, 50000, character.id, body)
}