aorecomp

Anarchy Online classic in the browser

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


commit da441710b0b98ad3b1ea134746dbd5305421ee0a
parent 70fda5d8f7c687776adaa82c600bf60c3129d452
Author: anon <anon@example.com>
Date:   Sat, 24 Oct 2026 11:43:28 +0000

Persist native Ignore lists and correct vicinity chat modes

Diffstat:
MTODO.md | 35+++++++++++++++++++++++++++++++++--
Mclient/runtime/browser_host.c | 60+++++++++++++++---------------------------------------------
Mclient/tests/browser_storage.c | 62++++++++++++++++++++++++++++++++++++++++++++++++++++++--------
Mdocs/character-info.md | 10++++++----
Adocs/ignore.md | 100+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mdocs/inventory.md | 12++++++------
Mdocs/protocol.md | 24++++++++++++++++++++----
Mdocs/teams.md | 3++-
Mserver/chat.go | 6+++---
Mserver/chat_history_test.go | 8++++----
Mserver/chat_integration_test.go | 56++++++++++++++++++++++++++++++++++++++++++++++++++++----
Mserver/chat_test.go | 2++
Mserver/main.go | 17++++++++---------
13 files changed, 305 insertions(+), 90 deletions(-)

diff --git a/TODO.md b/TODO.md @@ -753,11 +753,39 @@ and unresolved indoor lifecycle are explicit in [flight](docs/vehicles.md#yalmah 20/21-record load boundaries, 1024-byte text limits, truncated/invalid files and failed writes follow the original parser and save behavior; loading never accidentally saves or loses an already loaded prefix. -- [ ] Ignore one player. Check: the supported chat channels honor the saved - ignore entry and removing it restores delivery. +- [x] Persist native player Ignore and honor it for live chat. Native local + `IgnoreList.bin` now lives in the persistent character directory, with native + file names and missing-file semantics. Two hardware WASM clients verified + all seven paths (Team, Global, tell, say, whisper, shout and text emote), + removal restoring display/AFK replies, outgoing delivery, invalid commands, + reload and browser/server restart. Incoming frames still reach the original + native ID filter. See [native ignore](docs/ignore.md). +- [x] Correct native world text mode parsing. The byte after counted text is + say/whisper/shout/emote mode, not a NUL terminator. Real `/whisper`, `/shout` + and `/me` no longer disconnect; mode3 uses native emote display and vicinity + range. Complete/fragmented WebSocket regressions, malformed packets, spoofed + identity/metadata, range and history checks cover the corrected boundary. + See [chat protocol](docs/protocol.md) and `local/ignore-research/text-message.md`. +- [ ] Resolve chat-history replay fidelity and Ignore. The custom login replay + sends S2C36 system text without sender IDs, bypassing the native ignore filter. + Establish the original reconnect/scrollback behavior before choosing a replay + policy; preserve correct tell side effects and channel identity. The native + PageUp/PageDown paths inspected so far only scroll local output. See + [native ignore](docs/ignore.md). +- [ ] Extend native Ignore regressions to list growth beyond 20 entries, + duplicate IDs, truncated/corrupt files, failed writes and the special tell/ + vicinity metadata branches. Do not assume an empty file is a valid empty list. +- [ ] Audit native ignored nametag refresh. The overhead IGNORED badge remained + after `/ignore` removed the entry and live delivery resumed. Determine the + original invalidation path and verify changes without requiring actor reload. - [ ] Recover original channel flags, preferences and flood rules. Check: native listen/mute/log controls and rate limits follow period evidence across reconnect; Team announcement flags/blob policy is explicitly verified. +- [ ] Validate and relay native chat reference/voice metadata. Public world + text carries optional record0 `BIIISS` and record1 `BBBSS` after its mode; + they are currently discarded. Check bounded lengths, ordering, exact end, + links/voice display and malformed/unknown records. Never relay client-supplied + type2 ignore-bypass authority. See `local/ignore-research/text-message.md`. - [ ] Create one organization. Check: its name, identity and founder membership survive restart. - [ ] Invite an organization member. Check: accepting a valid invitation creates @@ -1086,6 +1114,9 @@ and server restarts. Turn every reproduced bug into a focused regression test. ## Checks that apply to each milestone +- [ ] Repair the browser-profile worker test fixture. Its VM context lacks + `URL`/`location` required by the current worker, so + `node client/tests/browser_profile.mjs` fails before exercising its assertions. - [ ] Align the declared Go test/toolchain requirement with `WaitGroup.Go` usage. The module declares Go1.24 while existing concurrency tests use the Go1.25 API; full `go vet` reports `stdversion` errors. The other analyzers diff --git a/client/runtime/browser_host.c b/client/runtime/browser_host.c @@ -114,58 +114,28 @@ void browser_initialize(unsigned character_id) } } free(manifest); - /* Seed native first-run preferences; persistent character files take precedence. */ - char character_path[128]; - snprintf(character_path, sizeof(character_path), "Prefs/localtest/Char%u", character_id); - assert(mkdir(character_path, 0755) == 0 || errno == EEXIST); - strcat(character_path, "/Char.cfg"); - FILE *original = fopen(character_path, "r"); - assert(original || errno == ENOENT); - FILE *character_preferences = fopen("Prefs/visitor.cfg", "w"); - assert(character_preferences); - if (original) { - char line[4096]; - while (fgets(line, sizeof(line), original)) { - if (strncmp(line, "IsFirstTime ", 12) && strncmp(line, "IsTipEnabled ", 13)) - fputs(line, character_preferences); - } - assert(!ferror(original)); - fclose(original); - } - fputs("IsFirstTime 1\nIsTipEnabled 0\n", character_preferences); - assert(fclose(character_preferences) == 0); - assert(rename("Prefs/visitor.cfg", character_path) == 0); - - /* Keep native character preferences across browser reloads. */ + /* Keep the native character directory in origin-private browser storage. */ backend_t persistent = wasmfs_create_opfs_backend(); assert(wasmfs_create_directory("/persistent", 0755, persistent) == 0); char *directory = browser_preferences_directory(base); free(base); assert(mkdir(directory, 0755) == 0 || errno == EEXIST); char persistent_path[4096]; - const struct { const char *name, *suffix; } files[] = { - {"Char.cfg", "cfg"}, {"IconPositions.bin", "bin"}, {"References.bin", "refs"}, - }; - for (unsigned i = 0; i < sizeof(files) / sizeof(files[0]); ++i) { - snprintf(persistent_path, sizeof(persistent_path), "%s/%u.%s", directory, character_id, files[i].suffix); - snprintf(character_path, sizeof(character_path), "Prefs/localtest/Char%u/%s", character_id, files[i].name); - int saved = open(persistent_path, O_CREAT | O_EXCL | O_WRONLY, 0600); - if (saved >= 0) { - FILE *original = fopen(character_path, "rb"); - if (original) { - unsigned char buffer[8192]; - size_t size; - while ((size = fread(buffer, 1, sizeof(buffer), original))) - assert(write(saved, buffer, size) == (ssize_t)size); - assert(!ferror(original)); - fclose(original); - } else assert(errno == ENOENT); - assert(close(saved) == 0); - } else assert(errno == EEXIST); - assert(unlink(character_path) == 0 || errno == ENOENT); - assert(symlink(persistent_path, character_path) == 0); - } + snprintf(persistent_path, sizeof(persistent_path), "%s/%u", directory, character_id); + assert(mkdir(persistent_path, 0755) == 0 || errno == EEXIST); free(directory); + char character_path[128]; + snprintf(character_path, sizeof(character_path), "Prefs/localtest/Char%u", character_id); + assert(symlink(persistent_path, character_path) == 0); + + /* Seed first-run settings once; native writers create the other files. */ + strcat(character_path, "/Char.cfg"); + int preferences_file = open(character_path, O_CREAT | O_EXCL | O_WRONLY, 0600); + if (preferences_file >= 0) { + const char first_run[] = "IsFirstTime 1\nIsTipEnabled 0\n"; + assert(write(preferences_file, first_run, sizeof(first_run) - 1) == sizeof(first_run) - 1); + assert(close(preferences_file) == 0); + } else assert(errno == EEXIST); /* Start the guest with the viewport size, including nonstandard aspect ratios. */ int width, height; diff --git a/client/tests/browser_storage.c b/client/tests/browser_storage.c @@ -1,4 +1,5 @@ #include <assert.h> +#include <errno.h> #include <stdio.h> #include <string.h> #include <sys/stat.h> @@ -97,8 +98,7 @@ static void icon_positions_survive_reload(unsigned character_id) if (!resume) { if (character_id == 43) { FILE *file = fopen(path, "rb"); - assert(file && fgetc(file) == EOF); - assert(fclose(file) == 0); + assert(!file && errno == ENOENT); } FILE *file = fopen(path, "wb"); assert(file); @@ -127,16 +127,19 @@ static void references_survive_reload(unsigned character_id, int resume) size_t length = cleared ? sizeof(empty) : sizeof(first); unsigned char actual[32] = {0}; FILE *file = fopen(path, "rb"); - assert(file); - size_t size = fread(actual, 1, sizeof(actual), file); - assert(!ferror(file)); - assert(fclose(file) == 0); + size_t size = 0; + if (resume) { + assert(file); + size = fread(actual, 1, sizeof(actual), file); + assert(!ferror(file)); + assert(fclose(file) == 0); + } if (resume) { assert(size == length && !memcmp(actual, expected, length)); } else { - assert(size == 0); + assert(!file && errno == ENOENT); file = fopen(path, "wb"); assert(file && fwrite(expected, 1, length, file) == length); assert(fclose(file) == 0); @@ -151,6 +154,45 @@ static void references_survive_reload(unsigned character_id, int resume) } } +static void ignored_players_survive_reload(unsigned character_id, int resume) +{ + char path[128]; + snprintf(path, sizeof(path), "Prefs/localtest/Char%u/IgnoreList.bin", character_id); + const unsigned char first[] = {0,0,0,2, 0,0,0,53, 0,0,0,54}; + const unsigned char other[] = {0,0,0,1, 0,0,0,42}; + const unsigned char empty[] = {0,0,0,0}; + int cleared = MAIN_THREAD_EM_ASM_INT({ return new URLSearchParams(location.search).has('empty'); }); + const unsigned char *expected = cleared ? empty : character_id == 42 ? first : other; + size_t length = cleared ? sizeof(empty) : character_id == 42 ? sizeof(first) : sizeof(other); + + FILE *file = fopen(path, "rb"); + unsigned char actual[16] = {0}; + size_t size = 0; + if (resume) { + assert(file); + size = fread(actual, 1, sizeof(actual), file); + assert(!ferror(file)); + assert(fclose(file) == 0); + } + + if (resume) { + assert(size == length && !memcmp(actual, expected, length)); + } else { + assert(!file && errno == ENOENT); + file = fopen(path, "wb"); + assert(file && fwrite(expected, 1, length, file) == length); + assert(fclose(file) == 0); + } + + /* Removing the last ignore saves a zero count, truncating the old IDs. */ + int clear = MAIN_THREAD_EM_ASM_INT({ return new URLSearchParams(location.search).has('clear'); }); + if (clear) { + file = fopen(path, "wb"); + assert(file && fwrite(empty, 1, sizeof(empty), file) == sizeof(empty)); + assert(fclose(file) == 0); + } +} + int main(void) { unsigned character_id = MAIN_THREAD_EM_ASM_INT({ @@ -180,7 +222,10 @@ int main(void) } preferences_use_canvas_dimensions(); icon_positions_survive_reload(character_id); - if (!pending) references_survive_reload(character_id, resume); + if (!pending) { + references_survive_reload(character_id, resume); + ignored_players_survive_reload(character_id, resume); + } replace_occlusion_cache(); create_occlusion_cache(); read_across_asset_chunk(); @@ -190,4 +235,5 @@ int main(void) puts("PASS: native first-run state and character preference edits persist"); puts("PASS: native icon positions use persistent browser storage"); puts("PASS: native references persist with character isolation and deletion"); + puts("PASS: native ignore lists persist with character isolation and removal"); } diff --git a/docs/character-info.md b/docs/character-info.md @@ -113,10 +113,12 @@ after a requested description replacement too. All three string paths share this exit; the original save flag is captured before its stack slot is reused for text length. Load-time additions with save=false remain deferred. -`browser_initialize` links the native file to `<character-id>.refs` beside the -existing config and icon-position files in origin-private storage, under the -server asset URL. The native serializer and loader read and write those bytes -directly. Other preference files remain in memory. Complete original exports, +`browser_initialize` links the native character directory to +`<encoded-server-asset-url>/<character-id>/` in origin-private storage. +`References.bin`, `Char.cfg`, `IconPositions.bin` and `IgnoreList.bin` keep +their native names. The native serializer and loader read and write those bytes +directly. Missing files remain absent until their native writers create them. +Complete original exports, matching snapshots and the save/loader evidence ledger are retained in `local/knowledge-research/persistence.md`. diff --git a/docs/ignore.md b/docs/ignore.md @@ -0,0 +1,100 @@ +# Native player ignore + +`/ignore <name>` toggles a local ignore entry. The command is case insensitive; +without a name it uses the selected player. Self, invalid selection, unknown +names and extra arguments produce native feedback without changing the list. +Ordinary names use the existing chat name lookup, C2S21 `S` and S2C21 `IS`. +The original client has no separate ignore mutation packet in this path. + +OOR `IgnoreSystem_t` stores numeric character IDs, separately from buddies. +The browser keeps the native character preference directory in origin-private +storage, partitioned by server asset URL and character ID. Native files retain +their names; there is no extra server ignore table or browser-specific format. + +## Native persistence + +`client/game/oor.dll/lifted-0000.c` contains IgnoreCharacter `sub_3E001120`, +UnignoreCharacter `sub_3E001310`, IsCharacterIgnored `sub_3E0013A0`, Load +`sub_3E0013F0` and Save `sub_3E001650`. New IDs and successful removals save +immediately. Duplicate additions and missing removals do not save. Loading does +not save, and the destructor only frees state. + +`Prefs/localtest/Char<id>/IgnoreList.bin` contains a big-endian 32-bit count, +followed by that many big-endian character IDs. Removing the last entry rewrites +the file to four zero bytes. The initial vector reserve of 20 is not a limit. +Only identity IDs are compared; command callers impose player/self checks. + +Missing files are safe. The original loader does not validate empty or truncated +files, so browser initialization must not manufacture an empty file. The native +character path links to an existing OPFS directory: native writers can create +valid files without the dangling-file-symlink creation failure in WasmFS. +Only `Char.cfg` is seeded, once, to request first-run actions with tips disabled. + +## Delivery boundary + +Native DDR checks sender IDs before displaying ordinary live tells, public +groups including Global and Team, and vicinity/whisper/shout/text-emote messages. +It also suppresses ignored ordinary tell side effects, including recent-buddy +insertion and AFK replies. It does not prevent outgoing chat to that player. +System text has no sender ID and is still displayed. + +Tell and vicinity metadata bit 0x01 bypasses the ordinary ignore guard. Its +authority is unverified. Structured type-2 tells take a separate display path; +their intended authority is also unresolved. These exceptions must not be +generalized into an administrative privilege without further evidence. + +The server's custom login history uses senderless S2C36 system text and therefore +bypasses native ignore filtering. History fidelity remains a separate TODO. +The inspected native PageUp/PageDown history actions scroll local output only; +that bounded finding does not establish every original history feature. + +## Evidence and verification + +Complete original DDR/OOR/BR exports, matching snapshots, native function +dependencies and a ledger of 36 validated Evidence citations are retained in +`local/ignore-research/ignore.md` and `manifest.json`. Key records are OOR Save +`ev_fd1979ad3c93fbf6c2212d3e9ce34df536675a0b3d186207df22b6b54b86fdbc`, +DDR command parser +`ev_fe429984672f71b88db53803eba85385817137f25418ea7c16ce041c00bd3556`, +group filter +`ev_f7590d1ab782aa2205a6c4d8d0628112f7bf9d8649415152bc475c7c391cc04d` +and system-message handler +`ev_34b3301086e8ebd0ee87588fd0d252cc1a4c3910610b66091264decd04021f24`. +These are static original-client contracts, not observations of original server +execution. + +`client/tests/browser_storage.c` checks initially missing files, native-shaped +ignore/reference bytes, reloads, character isolation, removal/truncation, existing +config/icon persistence, first-run state and unchanged remote assets. The browser +harness reuses the shared HTTPS preview and closes its owned context in `finally`. + +Two GPU WASM clients verified Team, Global, tell, say, whisper, shout and +text-emote filtering. Each blocked message reached the receiver's chat socket, +while its native scrollback stayed exactly unchanged. Toggling Ignore off +restored all seven displays and native AFK replies. Invalid self/unknown/extra +arguments preserved the file; mixed-case lookup and command tokens worked. +Saved eight-byte membership survived page, browser and server restarts; +removal wrote the four-byte zero count. Outgoing tells still reached the other +player. Screenshots, wire frames, OPFS dumps and assertions are retained in +`local/ignore-smoke/`. +Switching characters within one browser profile showed an initially absent +second ignore list and empty Knowledge view. Saving its opposite ignore entry +left the first character's cleared list and reference/config/icon bytes unchanged. +Returning to the first character restored its Knowledge icon; the reference +still contained its original Soldier/level-1 description. + +These tests also exposed a server parser error: the byte after counted world +text is its mode, rather than a terminating NUL. Correct parsing restores +whisper/shout/emote without disconnecting; see [chat wire layout](protocol.md). +Go regressions cover all four mode/subtype pairs in complete and fragmented +WebSocket streams, authenticated sender identity, discarded client metadata, +eight malformed payload cases, emote distance and durable history. The stale +overhead IGNORED badge after removal remains an explicit native refresh TODO. +The full Go suite passed in 357 seconds; the changed Go cases passed twice under +the race detector in 99 seconds. The other vet analyzers passed with the existing +Go toolchain `stdversion` mismatch disabled. Browser storage passed nine stages, +browser controls passed all 73 tests, and publisher tests passed. The separate +profile-worker VM fixture currently fails because its context lacks `URL`; +that pre-existing fixture repair remains in TODO. +Owned characters 55/56, their 56 history copies and two buddy rows were cleaned; +all other database rows stayed unchanged, with integrity and foreign keys valid. diff --git a/docs/inventory.md b/docs/inventory.md @@ -156,13 +156,13 @@ Its logical server slot remains unchanged. change. Browser builds save that completed map immediately, since page reloads skip the native shutdown destructor that ordinarily saves it. -`browser_initialize` in `client/runtime/browser_host.c` links this native binary -file, `Char.cfg` and `References.bin` to the browser's origin-private filesystem. -The directory is keyed by the server asset URL; character ID selects the -`.bin`, `.cfg` and `.refs` files. Knowledge storage is described in +`browser_initialize` in `client/runtime/browser_host.c` links the native character +directory to the browser's origin-private filesystem. The directory is keyed +by the server asset URL and character ID; files retain their native names. +Knowledge storage is described in [player references](character-info.md#knowledge-storage). -Other preferences and occlusion caches keep their existing in-memory behavior. -Existing bytes are preserved. A missing icon-position file starts empty; a new +Preferences outside that directory and occlusion caches remain in memory. +Existing bytes are preserved. A missing icon-position file stays absent; a new character config enables native first-run initialization with tips disabled. Native loads and saves use the same formats and logical identities. diff --git a/docs/protocol.md b/docs/protocol.md @@ -533,14 +533,30 @@ REA evidence: `ev_4ad673598287cb676be8cb1963e67065ae0f58db2e562dd6f593a08912e263 and `ev_491820b034f54f5189a9b23587f921c61cce5199ee34da1e30ce13587d8ac7a1`. Vicinity input uses world packet type 5, with a 32-bit subtype at offset 16: -2 whisper, 3 say, 4 shout. The body at offset 20 is target identity (two -32-bit fields), a 32-bit payload length, then a 16-bit text length, text bytes, -and a terminating NUL. A captured browser `hello` message has payload length -8, text length 5, and bytes `68 65 6c 6c 6f 00`. The sender comes from the +2 whisper, 3 say/emote, 4 shout. The body at offset 20 is target identity (two +32-bit fields), a 32-bit payload length, then a 16-bit text length, exactly +that many text bytes, a mode byte and optional metadata. Modes are 0 say, +1 whisper, 2 shout and 3 emote. A captured browser `hello` message has payload +length 8, text length 5, and bytes `68 65 6c 6c 6f 00`; the final zero is its +say mode, not a string terminator. The sender comes from the authenticated connection. `ffr.dll` `Client_t::SendVicinityMessage` at 0x10002ec0 and `nr.dll` `TextMessage_t::CreateDataBlock` at 0x10004c20 establish this layout (evidence `ev_74ddee74efc8a860c945fad27b1f4b290e8c603f4715508d0c2e92ddf25f92c4` and `ev_aa82e813076ca6be5f383500c0f53dcda42bd930ab71777ae3f5b6afcf8831ca`). +DDR prepares the counted text/mode before FFR sends it. Its public producer +derives subtype and mode together; the server validates those pairs. Native +whisper/shout text already includes `whispers: `/`shouts: `, which is preserved. +Text emotes use ordinary vicinity distance and native mode-3 display. +See `local/ignore-research/text-message.md` for original serializer/parser +evidence, complete exports and declared-size captures separated from padding. + +The native public metadata producer can append reference record0 (`BIIISS`) +and voice record1 (`BBBSS`), in that order. The server currently discards +unimplemented client metadata after the counted text and mode. It does not +relay arbitrary client flags: incoming native metadata type2 can bypass Ignore, +and that record is absent from the public producer. Supporting references and +voices requires bounded record validation before relay; see +[native ignore](ignore.md). The separate chat stream uses big-endian 16-bit type and body length, with 16-bit byte lengths for strings/blobs. Original `ddr.dll` dispatch at diff --git a/docs/teams.md b/docs/teams.md @@ -27,7 +27,8 @@ Addresses below use the original image bases. These use key `5e477770` and the sending player's envelope. Recruit's boolean is distinct from the acceptance boolean. The native CreateTeam export is an empty return and emits no extra request. Ignore invokes the client's ignore -subsystem and then the same No action; server ignore persistence remains open. +subsystem and then the same No action; the [ignore list](ignore.md) is local +character preference data. An incoming action 26 in the invitee's envelope, with inviter identity, reaches `10076c90 -> 1001cf10 -> CMsg_TeamJoinRequest`. GUI event 344 displays the diff --git a/server/chat.go b/server/chat.go @@ -334,10 +334,10 @@ func (server *server) handleChatMessage(client *chatClient, kind uint16, body [] func (server *server) sendVicinity(id uint32, kind uint32, message string) { message = strings.TrimSuffix(message, "\x00") - if kind > 2 || len(message) == 0 || len(message) > 4096 || strings.ContainsRune(message, 0) { + if kind > 3 || len(message) == 0 || len(message) > 4096 || strings.ContainsRune(message, 0) { return } - radius := [3]float32{10, 1.5, 60}[kind] + radius := [4]float32{10, 1.5, 60, 10}[kind] server.chatLogMutex.Lock() server.mutex.Lock() sender := server.characters[id] @@ -364,7 +364,7 @@ func (server *server) sendVicinity(id uint32, kind uint32, message string) { } server.mutex.Unlock() - server.logChat_locked(chatHistoryEntry{Channel: [3]string{"say", "whisper", "shout"}[kind], SenderID: id, Sender: name, Playfield: playfield, Message: message}, recipients) + server.logChat_locked(chatHistoryEntry{Channel: [4]string{"say", "whisper", "shout", "emote"}[kind], SenderID: id, Sender: name, Playfield: playfield, Message: message}, recipients) server.chatLogMutex.Unlock() body := appendChatString(binary.BigEndian.AppendUint32(nil, id), message) body = append(body, 0, 1, byte(kind)) diff --git a/server/chat_history_test.go b/server/chat_history_test.go @@ -44,7 +44,7 @@ func TestChatHistoryRecordsChannelsAndLegacyText(t *testing.T) { if err := <-disconnected; err != nil { t.Fatal(err) } - for _, kind := range []uint32{0, 1, 2} { + for _, kind := range []uint32{0, 1, 2, 3} { server.sendVicinity(2, kind, message) } @@ -58,10 +58,10 @@ func TestChatHistoryRecordsChannelsAndLegacyText(t *testing.T) { } data = append(data, bobData...) lines := bytes.Split(bytes.TrimSpace(data), []byte{'\n'}) - if len(lines) != 5 { + if len(lines) != 6 { t.Fatalf("history has %d records: %s", len(lines), data) } - for index, channel := range []string{"tell", "Global", "say", "whisper", "shout"} { + for index, channel := range []string{"tell", "Global", "say", "whisper", "shout", "emote"} { var entry chatHistoryEntry if err := json.Unmarshal(lines[index], &entry); err != nil { t.Fatal(err) @@ -102,7 +102,7 @@ func TestChatHistoryExcludesRejectedMessages(t *testing.T) { for _, message := range []string{"", "bad\x00message", strings.Repeat("x", 4097)} { server.sendVicinity(1, 0, message) } - server.sendVicinity(1, 3, "invalid kind") + server.sendVicinity(1, 4, "invalid kind") server.sendVicinity(3, 0, "unknown sender") if _, err := os.Stat("data/world.sqlite"); !os.IsNotExist(err) { diff --git a/server/chat_integration_test.go b/server/chat_integration_test.go @@ -156,12 +156,17 @@ func TestBrowserWorldVicinityMatchesAcrossWebSocketBoundaries(t *testing.T) { } } var delivered [][]byte - for _, subtype := range []byte{3, 2, 4} { + for index, message := range [][2]byte{{3, 0}, {2, 1}, {4, 2}, {3, 3}, {3, 0}} { // Both the header sender and the target claim Bob; the session is Alice. packet := []byte{ 0xdf, 0xdf, 0, 5, 0, 1, 0, 37, 0, 0, 0, 1, 0, 0, 0, 2, - 0, 0, 0, subtype, 0, 0, 0xc3, 0x50, 0, 0, 0, 2, - 0, 0, 0, 5, 0, 2, 'h', 0xe9, 0, 0, 0, 0, + 0, 0, 0, message[0], 0, 0, 0xc3, 0x50, 0, 0, 0, 2, + 0, 0, 0, 5, 0, 2, 'h', 0xe9, message[1], 0, 0, 0, + } + if index == 4 { + // Unverified metadata must not grant the receiver's ignore bypass. + packet = append(packet[:37], 2, 1, 0) + packet[7], packet[31] = 39, 7 } write(worldSocket, packet) for range 2 { @@ -181,7 +186,7 @@ func TestBrowserWorldVicinityMatchesAcrossWebSocketBoundaries(t *testing.T) { }) { t.Fatalf("chat server announcement: %x", announcement) } - for index, expectedKind := range []byte{0, 1, 2} { + for index, expectedKind := range []byte{0, 1, 2, 3, 0} { if !bytes.Equal(delivered[index*2], []byte{0, 20, 0, 11, 0, 0, 0, 1, 0, 5, 'A', 'l', 'i', 'c', 'e'}) { t.Fatalf("vicinity sender name: %x", delivered[index*2]) } @@ -309,3 +314,46 @@ func TestBrowserChatHistoryFollowsPlayerAcrossSessionsAndTokenChanges(t *testing t.Fatalf("restoring history recorded duplicate messages: %q %v", data, err) } } + +func TestWorldVicinityRejectsMalformedPayloads(t *testing.T) { + for _, test := range []struct { + name string + change func([]byte) []byte + }{ + {"missing mode", func(packet []byte) []byte { return packet[:35] }}, + {"short payload length", func(packet []byte) []byte { packet[31] = 3; return packet }}, + {"long payload length", func(packet []byte) []byte { packet[31] = 5; return packet }}, + {"text overlaps mode", func(packet []byte) []byte { packet[33] = 2; return packet }}, + {"unknown mode", func(packet []byte) []byte { packet[35] = 4; return packet }}, + {"unknown subtype", func(packet []byte) []byte { packet[19] = 5; return packet }}, + {"mismatched subtype", func(packet []byte) []byte { packet[19] = 2; return packet }}, + {"NUL text", func(packet []byte) []byte { packet[34] = 0; return packet }}, + } { + t.Run(test.name, func(t *testing.T) { + world := chatTestServer(t) + world.clients = make(map[uint32]*worldClient) + packet := test.change([]byte{ + 0xdf, 0xdf, 0, 5, 0, 1, 0, 36, 0, 0, 0, 1, 0, 0, 0, 2, + 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 4, 0, 1, 'x', 0, + }) + binary.BigEndian.PutUint16(packet[6:8], uint16(len(packet))) + for len(packet)%4 != 0 { + packet = append(packet, 0) + } + input := systemPacket(0x1b, []byte{0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0}) + input = append(input, n3Packet(0x570c2039, 50000, 1, nil)...) + conn := &combatInterestConn{input: bytes.NewReader(append(input, packet...))} + + err := world.serveWorldClient(&worldClient{conn: conn, loading: true}) + + if err == nil || !strings.Contains(err.Error(), "invalid vicinity") { + t.Fatalf("malformed vicinity was accepted: %v", err) + } + history, err := world.chatHistory_locked(1) + if err != nil || len(history) != 0 { + t.Fatalf("malformed vicinity entered history: %+v %v", history, err) + } + }) + } +} diff --git a/server/chat_test.go b/server/chat_test.go @@ -212,6 +212,8 @@ func TestChatVicinityUsesWorldDistanceAndReadiness(t *testing.T) { {"whisper far", 1, 2, 710, true, false}, {"shout near", 2, 60, 710, true, true}, {"shout far", 2, 61, 710, true, false}, + {"emote near", 3, 10, 710, true, true}, + {"emote far", 3, 11, 710, true, false}, {"other playfield", 0, 0, 950, true, false}, {"loading", 0, 0, 710, false, false}, } { diff --git a/server/main.go b/server/main.go @@ -432,26 +432,25 @@ func (server *server) serveWorldClient(client *worldClient) error { server.updateMutex.Unlock() } case 5: - // TextMessage_t wraps a length-prefixed, NUL-terminated string. + // TextMessage_t carries counted text, a mode byte and optional metadata. if character == nil || len(packet) < 35 { return fmt.Errorf("short or unauthenticated vicinity message") } subtype := binary.BigEndian.Uint32(packet[16:20]) length := int(binary.BigEndian.Uint32(packet[28:32])) textLength := int(binary.BigEndian.Uint16(packet[32:34])) - if subtype < 2 || subtype > 4 || length != len(packet)-32 || textLength != length-3 || textLength > 4096 || packet[len(packet)-1] != 0 { + if length != len(packet)-32 || textLength > length-3 || textLength > 4096 { return fmt.Errorf("invalid vicinity message") } - message := string(packet[34 : len(packet)-1]) + kind := uint32(packet[34+textLength]) + if kind > 3 || subtype != [4]uint32{3, 2, 4, 3}[kind] { + return fmt.Errorf("invalid vicinity mode") + } + message := string(packet[34 : 34+textLength]) if strings.ContainsRune(message, '\x00') { return fmt.Errorf("invalid vicinity text") } - kind := uint32(0) - if subtype == 2 { - kind = 1 - } else if subtype == 4 { - kind = 2 - } + // Client metadata is not relayed until its reference/voice records are validated. server.sendVicinity(character.id, kind, message) case 10: // The client compresses individual movement messages with zlib.