aorecomp

Anarchy Online classic in the browser

git clone https://aorecomp.ubeagle.com/code/aorecomp.git


commit 3cb4a235af36c3251637359c088cc75651815e1f
parent 499401cd6eb6d8c133f8927664feec11516e6c96
Author: anon <anon@example.com>
Date:   Tue, 13 Oct 2026 05:23:48 +0000

Advance client-target browser startup through WinMain diagnostics

Diffstat:
M.gitignore | 1+
Mdocs/browser-porting.md | 109++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
Aserver/browser_assets.go | 93+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/browser_assets_test.go | 93+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/browser_launch.go | 21+++++++++++++++++++++
Aserver/browser_launch_test.go | 37+++++++++++++++++++++++++++++++++++++
Mserver/main.go | 2++
7 files changed, 353 insertions(+), 3 deletions(-)

diff --git a/.gitignore b/.gitignore @@ -4,6 +4,7 @@ venv/ tools/unshield/ tools/*.7z tools/*.exe +tools/*.exe~ tools/*.log tools/cellao-reference/ tools/aotomation-reference/ diff --git a/docs/browser-porting.md b/docs/browser-porting.md @@ -502,9 +502,8 @@ math error handler, builds argv/environment through `__getmainargs`, and executes its initializer tables. It then scans `_acmdln` itself and calls WinMain at RVA `0x1080` from RVA `0x45b5`. DLL attach success therefore does not establish that the executable has reached WinMain. -The current harness supplies only `Clientr.exe` as its command line; actual -game launch arguments and environment still need the original launcher's -contract. +The original launcher's command line and environment are part of the client +startup contract described below. The observed executable initializer path reaches ACE's Winsock startup before WinMain. Its `ws2_32.dll` import by ordinal 115 is `WSAStartup`, as confirmed against the Windows PE export table. In the pinned ACE image, @@ -601,3 +600,107 @@ Rust automatically. Keep generated code reproducible; place readable graphics, network and platform adapters alongside it. Selected methods can later be replaced with recovered Rust implementations after comparing their outputs and side effects against the translated/native behavior. + +### Launcher arguments, environment and file access + +These observations use the pinned `client-target` 13.2 images. Clientr's +parser at RVA `0x2cd0` uses seven `%s` conversions (format at RVA `0x9750`). +It accepts conversion counts 3 or 7; additional tokens after the seventh +are ignored. With another count, RVA `0x2d58` calls +`_spawnv(1, "Anarchy.exe", ["Anarchy.exe", NULL])` and returns -1. +The parser does not understand quoted whitespace in credentials. + +The seven fields are username, password, decimal character ID, decimal +IPv4 address, port and two cookies. The address is in host order: loopback +is `2130706433` (`0x7f000001`). FFR's redirect at RVA `0x2cd0` passes it to +ACE_INET_Addr::set with encoding enabled; ACE RVA `0x31b01` calls htonl. +The three-field form does not supply the redirect endpoint or cookies. +Character IDs and cookies must match the local server's launch contract. +REA evidence: `ev_fa803a45aa90a7341d37c3c66d6df8cff0079b53c7d6ca5e255cdf18c87169a5`. + +BR's GetCDPath (RVA `0x1030`) checks `ANARCHY_CD`, and GetSetupPath +(RVA `0x1170`) checks `ANARCHY_SETUP`. The original launch environment's +explicit values `cd_image` and `Setupf` become cached `cd_image/` and +`Setupf/`, relative to the current directory. Both getters append a +separator and normalize backslashes. Without overrides they use `ANARCHY` +to form `<root>/cd_image` and `<root>/common/Setupfiles`. GetDBPath +(RVA `0x13f0`) separately uses the current directory and creates `Databases`. +REA evidence: `ev_15e3a22947458372a4ffbb2a4dd7408cd9796b0075b337b746eeaea4a8e13585` +and `ev_efc713c8f251857b7b459d43d4f814023ac8ca5506779cabeca748929ac9c6fb`. +These are static observations; they do not establish successful world login. + +WinMain redirects stderr with `freopen("stderr.txt", "w", stderr)` at +Clientr RVA `0x118d`, resuming at `0x1193`. Reopening preserves the FILE +pointer at `_iob+64`; the eight-word FILE structure includes flags at +12 +and the descriptor at +16. Text streams translate LF writes to CRLF. +File APIs must share one guest filesystem so Win32 and CRT paths see the +same assets, directory changes, preferences and logs. Original assets can +remain read-only while writes live in a separate overlay. Browser delivery +can use HTTP ranges; it does not require preloading the large DAT files. +See Microsoft's [freopen contract](https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/freopen-wfreopen). + +The next WinMain instructions construct a base `exception` object through +MSVCRT at RVA `0x11b1`, then install FFR and Clientr-derived virtual tables. +MSVC x86 uses ECX for `this` and callee cleanup for explicit constructor +arguments. Its base exception layout is three words: vtable, message +pointer and ownership flag. Copies duplicate owned messages and retain +borrowed pointers. Providing these object methods does not provide C++ +throw dispatch, unwinding or RTTI. Compatibility reference: +[Wine's exception objects](https://github.com/wine-mirror/wine/blob/master/dlls/msvcrt/cppexcept.h). +REA evidence: `ev_549928a89b4a80febebbb485bd9091d999b7153d7fcb993b00156234e93e555e`. + +FFR RVA `0x532c` attempts `ShellExecuteA(0, "open", "dxdiag.exe", +"DXDiagOutput.txt", 0, 1)`. A translated native run continued after a +failure return from that optional helper launch. Subsequent version +formatting uses `sprintf` with `%d.%02d.%d %s`; printf-family adapters must +consume x86 stack arguments and implement the observed width/zero padding. + +FFR's BugReport_t::Init (RVA `0x33e0`) calibrates CPU MHz for crash-report +text. It executes RDTSC at RVA `0x358c` and uses +QueryPerformanceCounter/QueryPerformanceFrequency around repeated Sleep(1) +calls. It computes `(deltaTSC / deltaQPC) * QPF`, then scales by 1e-6 to +format `%s. %u Mhz` at RVA `0x3622`. This routine has no zero-delta guard +or minimum-MHz gate. The timestamp instruction returns a 64-bit count in EDX:EAX; +see [Intel's instruction reference](https://cdrdv2-public.intel.com/789581/325383-sdm-vol-2abcd.pdf). +A portable runtime can supply a monotonic synthetic counter, but must keep +its rate consistent between reads and actually wait during calibration. +The browser worker needs a timed atomic wait because its WASM standard +library does not provide native thread sleeping. + +The calibration calls MSVCRT `_ftol` at RVAs `0x35ef` and `0x3603`. +This helper consumes x87 ST(0), truncates toward zero independently of +the rounding mode, and returns a signed 64-bit value in EDX:EAX. +The float MHz scale is slightly below 1e-6, so an exact synthetic 1 GHz +counter can correctly format as 999 MHz after truncation. +GlobalMemoryStatus at RVA `0x362b` receives an uninitialized legacy +MEMORYSTATUS buffer. It must write all eight DWORDs, including dwLength=32; +FFR reads total physical memory at +8 and formats `%uMb` at RVA `0x3642`. + +FFR's allocation setup registers a guest `_set_new_handler` callback at +RVA `0x5c7a`, enables malloc's new-handler mode at RVA `0x5c82`, and +allocates a 1 MiB buffer. Registration returns the previous callback/mode. +Handling allocation failure also requires invoking the guest callback; +recording registration alone does not implement that path. See Microsoft's +[_set_new_handler](https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/set-new-handler) +and [_set_new_mode](https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/set-new-mode). + +Native tracing identified three later low-page warnings as valid unnamed +event creation: ACE RVA `0x57c71` calls +`CreateEventA(NULL, FALSE, FALSE, NULL)`. A null event name is optional and +must not be read as a string. +Four earlier warnings came from ctreestd's environment scans at RVAs +`0x3db5d`/`0x3db9d` and MSS32's scans at `0x36ca9`/`0x36ce9`. +Their embedded CRTs call GetEnvironmentStringsW, size/convert the entire +multi-string block through WideCharToMultiByte with CP_ACP and flags 0, +then scan the resulting ANSI block. A zero conversion result leaves a +null pointer that those scans dereference. Positive UTF-16 lengths must +preserve embedded NULs; -1 lengths include the terminating NUL. The +conversion's used-default-character output is a 32-bit BOOL. + +The verified environment conversion covers CP_ACP/Windows-1252 with flags +zero, directly representable characters and default-character replacement. +UTF-8, composition and Windows best-fit transliteration remain unsupported. +On 2026-10-12 native Rust and browser WASM runs completed the observed +diagnostic initialization and directory creation without low-page warnings, +then both stopped at BR's imported `_chmod` call (RVA `0x2257`). This is +further startup progress, not successful world loading or rendering. diff --git a/server/browser_assets.go b/server/browser_assets.go @@ -0,0 +1,93 @@ +package main + +import ( + "encoding/json" + "net/http" + "os" + "path/filepath" + "strings" +) + +func browserAsset(w http.ResponseWriter, r *http.Request) { + // Resolve guest filenames without depending on the host's case sensitivity. + name := strings.ReplaceAll(r.PathValue("path"), "\\", "/") + if name != "" && !filepath.IsLocal(filepath.FromSlash(name)) { + http.NotFound(w, r) + return + } + path := "client-target" + for _, part := range strings.Split(name, "/") { + if part == "" { + continue + } + entries, err := os.ReadDir(path) + if err != nil { + http.NotFound(w, r) + return + } + found := false + for _, entry := range entries { + if strings.EqualFold(entry.Name(), part) && entry.Type()&os.ModeSymlink == 0 { + path = filepath.Join(path, entry.Name()) + found = true + break + } + } + if !found { + http.NotFound(w, r) + return + } + } + + // ServeContent seeks directly in the original file for HTTP range requests. + file, err := os.Open(path) + if err != nil { + http.NotFound(w, r) + return + } + defer file.Close() + info, err := file.Stat() + if err != nil { + http.NotFound(w, r) + return + } + w.Header().Set("Cross-Origin-Resource-Policy", "same-origin") + w.Header().Set("Cache-Control", "no-cache") + if info.IsDir() { + entries, err := file.ReadDir(-1) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + listing := make([][]any, 0, len(entries)) + for _, entry := range entries { + if entry.Type()&os.ModeSymlink != 0 { + continue + } + metadata, err := entry.Info() + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + listing = append(listing, []any{entry.Name(), entry.IsDir(), metadata.Size()}) + } + w.Header().Set("X-AO-Directory", "1") + w.Header().Set("Content-Type", "application/json") + if r.Method == "HEAD" { + return + } + if err := json.NewEncoder(w).Encode(listing); err != nil { + return + } + return + } + if !info.Mode().IsRegular() { + http.NotFound(w, r) + return + } + if r.Header.Get("X-AO-Directory") == "1" { + http.NotFound(w, r) + return + } + http.ServeContent(w, r, info.Name(), info.ModTime(), file) +} diff --git a/server/browser_assets_test.go b/server/browser_assets_test.go @@ -0,0 +1,93 @@ +package main + +import ( + "net/http" + "net/http/httptest" + "os" + "testing" +) + +func TestBrowserAssetRange(t *testing.T) { + t.Chdir(t.TempDir()) + if err := os.MkdirAll("client-target/cd_image/data/db", 0755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile("client-target/cd_image/data/db/ResourceDatabase.dat", []byte("0123456789"), 0644); err != nil { + t.Fatal(err) + } + mux := http.NewServeMux() + mux.HandleFunc("GET /browser-assets/{path...}", browserAsset) + request := httptest.NewRequest("GET", "/browser-assets/CD_IMAGE/DATA/DB/resourcedatabase.DAT", nil) + request.Header.Set("Range", "bytes=3-6") + response := httptest.NewRecorder() + + mux.ServeHTTP(response, request) + + if response.Code != http.StatusPartialContent || response.Body.String() != "3456" { + t.Fatalf("range response: %d %q", response.Code, response.Body.String()) + } + if response.Header().Get("Content-Range") != "bytes 3-6/10" { + t.Fatal(response.Header()) + } +} + +func TestBrowserAssetRejectsOutsidePath(t *testing.T) { + t.Chdir(t.TempDir()) + if err := os.Mkdir("client-target", 0755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile("secret.txt", []byte("outside"), 0644); err != nil { + t.Fatal(err) + } + request := httptest.NewRequest("GET", "/browser-assets/outside", nil) + request.SetPathValue("path", "../secret.txt") + response := httptest.NewRecorder() + + browserAsset(response, request) + + if response.Code != http.StatusNotFound { + t.Fatalf("outside file response: %d", response.Code) + } +} + +func TestBrowserAssetDirectoryMetadata(t *testing.T) { + t.Chdir(t.TempDir()) + if err := os.MkdirAll("client-target/cd_image/data/db", 0755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile("client-target/cd_image/data/db/ResourceDatabase.dat", []byte("0123456789"), 0644); err != nil { + t.Fatal(err) + } + mux := http.NewServeMux() + mux.HandleFunc("GET /browser-assets/{path...}", browserAsset) + request := httptest.NewRequest("GET", "/browser-assets/cd_image/data/db", nil) + request.Header.Set("X-AO-Directory", "1") + response := httptest.NewRecorder() + + mux.ServeHTTP(response, request) + + if response.Code != http.StatusOK || response.Header().Get("X-AO-Directory") != "1" || response.Body.String() != "[[\"ResourceDatabase.dat\",false,10]]\n" { + t.Fatalf("directory metadata: %d %q", response.Code, response.Body.String()) + } +} + +func TestBrowserAssetDirectoryRequestRejectsRegularFile(t *testing.T) { + t.Chdir(t.TempDir()) + if err := os.Mkdir("client-target", 0755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile("client-target/database.dat", []byte("large asset"), 0644); err != nil { + t.Fatal(err) + } + mux := http.NewServeMux() + mux.HandleFunc("GET /browser-assets/{path...}", browserAsset) + request := httptest.NewRequest("GET", "/browser-assets/database.dat", nil) + request.Header.Set("X-AO-Directory", "1") + response := httptest.NewRecorder() + + mux.ServeHTTP(response, request) + + if response.Code != http.StatusNotFound { + t.Fatalf("regular file listing response: %d", response.Code) + } +} diff --git a/server/browser_launch.go b/server/browser_launch.go @@ -0,0 +1,21 @@ +package main + +import ( + "fmt" + "net/http" +) + +func (server *server) browserLaunch(w http.ResponseWriter, r *http.Request) { + server.mutex.Lock() + defer server.mutex.Unlock() + + // Supply an existing offline character to the original launcher contract. + for _, user := range server.users_locked() { + if server.clients[user.ID] == nil { + w.Header().Set("Content-Type", "text/plain") + fmt.Fprintf(w, "Clientr.exe localtest localtest %d 2130706433 7501 0 0", user.ID) + return + } + } + http.Error(w, "Create an offline character in the control panel first.", http.StatusConflict) +} diff --git a/server/browser_launch_test.go b/server/browser_launch_test.go @@ -0,0 +1,37 @@ +package main + +import ( + "net/http" + "net/http/httptest" + "testing" +) + +func TestBrowserLaunchSelectsAnOfflinePlayer(t *testing.T) { + world := &server{ + characters: map[uint32]*character{1: {id: 1}, 3: {id: 3}, 1000001: {id: 1000001, npc: true}}, + clients: map[uint32]*worldClient{1: {}}, + } + request := httptest.NewRequest("POST", "/browser-launch", nil) + response := httptest.NewRecorder() + + world.browserLaunch(response, request) + + if response.Code != http.StatusOK || response.Body.String() != "Clientr.exe localtest localtest 3 2130706433 7501 0 0" { + t.Fatalf("launch response: %d %q", response.Code, response.Body.String()) + } +} + +func TestBrowserLaunchRequiresAnOfflinePlayer(t *testing.T) { + world := &server{ + characters: map[uint32]*character{1: {id: 1}}, + clients: map[uint32]*worldClient{1: {}}, + } + request := httptest.NewRequest("POST", "/browser-launch", nil) + response := httptest.NewRecorder() + + world.browserLaunch(response, request) + + if response.Code != http.StatusConflict { + t.Fatalf("launch response: %d %q", response.Code, response.Body.String()) + } +} diff --git a/server/main.go b/server/main.go @@ -21,6 +21,8 @@ func main() { http.HandleFunc("GET /users/{character}", server.userPage) http.HandleFunc("POST /users", server.createUser) http.HandleFunc("POST /users/{character}", server.editUser) + http.HandleFunc("GET /browser-assets/{path...}", browserAsset) + http.HandleFunc("POST /browser-launch", server.browserLaunch) browserFiles := http.StripPrefix("/browser/", http.FileServer(http.Dir("browser"))) http.HandleFunc("GET /browser/", func(w http.ResponseWriter, r *http.Request) { // Shared WASM memory lets the client worker wait for browser host calls.