aorecomp

Anarchy Online classic in the browser

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


commit 776bb5403e7ae7de4e0f1696b53080b0e87534f5
parent 32cd94ee80103a45391893ba9e2f1ec6ad338079
Author: anon <anon@example.com>
Date:   Sat, 24 Oct 2026 12:30:24 +0000

Relay native chat references and voices

Diffstat:
MTODO.md | 20+++++++++++++++-----
Mclient/Makefile.wasm | 4++++
Mclient/game/mmr.dll/lifted-0000.c | 6++++++
Mclient/runtime/browser_host.js | 9+++++++--
Mclient/tests/browser_sound_metadata.mjs | 11+++++++++++
Aclient/tests/player_voice.c | 94+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Adocs/chat-metadata.md | 123+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mdocs/ignore.md | 6++++--
Mdocs/protocol.md | 12++++++------
Mserver/chat.go | 41+++++++++++++++++++++++++++--------------
Mserver/chat_history_test.go | 32++++++++++++++++++--------------
Mserver/chat_integration_test.go | 54+++++++++++++++++++++++++++++++++---------------------
Aserver/chat_metadata.go | 32++++++++++++++++++++++++++++++++
Aserver/chat_metadata_test.go | 294+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/chat_output_test.go | 2+-
Mserver/chat_test.go | 6+++---
Mserver/main.go | 7+++++--
Mserver/users_test.go | 2+-
18 files changed, 684 insertions(+), 71 deletions(-)

diff --git a/TODO.md b/TODO.md @@ -781,11 +781,21 @@ and unresolved indoor lifecycle are explicit in [flight](docs/vehicles.md#yalmah - [ ] 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`. +- [x] Validate and relay native chat reference/voice metadata. Live tell, + Global, Team and vicinity paths preserve record0 `BIIISS` and record1 `BBBSS`. + Counted fields, order, exact end, enclosing frame size and authenticated + sessions are checked; client type2 ignore-bypass authority is rejected. + Hardware WASM clients verified received character/item links, cached info, + exact relay bytes, native Ignore and voice decoding with an isolated fixture. + Metadata-only voices survive empty text; relative sound paths resolve in the + browser manifest and the native filename queue enforces its actual capacity. + See [chat metadata](docs/chat-metadata.md). +- [ ] Recover the original Notum Wars player voice assets and publish the + correct account entitlement (stat389 bit0). The supplied 14.9.1 assets lack + `sound/sfx/player`; ordinary `/voice` currently reports LandControl required. + Check all shipped effects, custom voice names/paths, style/breed/sex fallback, + channel hearing preferences, Ignore, rate limits and real playback. Fixture + coverage of metadata is not a substitute for the original voice pack. - [ ] Create one organization. Check: its name, identity and founder membership survive restart. - [ ] Invite an organization member. Check: accepting a valid invitation creates diff --git a/client/Makefile.wasm b/client/Makefile.wasm @@ -240,3 +240,7 @@ build/wasm/character-reference.js: tests/character_reference.c game/ddr.dll/lift build/wasm/reference-persistence.js: tests/reference_persistence.c game/or.dll/lifted-0000.c runtime/guest_msvcp.c runtime/guest_heap.c runtime/guest_memory.c runtime/recomp_state.c runtime/recomp_types.h runtime/guest_memory.h runtime/guest_msvcp.h runtime/guest_heap.h @mkdir -p $(@D) $(CC) $(CPPFLAGS) $(CFLAGS) -ffunction-sections -fdata-sections $(filter %.c,$^) -Wl,--gc-sections -lm -o $@ + +build/wasm/player-voice.js: tests/player_voice.c game/mmr.dll/lifted-0000.c game/mmr.dll/lifted-0002.c runtime/guest_memory.c runtime/recomp_state.c runtime/recomp_types.h runtime/guest_memory.h + @mkdir -p $(@D) + $(CC) $(CPPFLAGS) $(CFLAGS) -ffunction-sections -fdata-sections $(filter %.c,$^) -Wl,--gc-sections -lm -o $@ diff --git a/client/game/mmr.dll/lifted-0000.c b/client/game/mmr.dll/lifted-0000.c @@ -11486,6 +11486,12 @@ L_3A002F1E: } void sub_3A002F50(void) { + /* The 260-byte descriptor filename includes the 11-byte sfx\\Player\\ prefix. */ + if (strlen((char *)ADDR(MEM32(g_esp + 4))) > 248) { + g_esp += 12; + return; + } + int _fpu_cmp = 0; uint32_t _cf = 0; int _df = 1; diff --git a/client/runtime/browser_host.js b/client/runtime/browser_host.js @@ -123,8 +123,13 @@ addToLibrary({ }, ao_sound_file_size__deps: ['$AOSoundSizes', '$UTF8ToString'], ao_sound_file_size: (filename) => { - const name = UTF8ToString(filename).replaceAll('\\', '/').replace(/^\.\//, '').toLowerCase(); - return AOSoundSizes[name] ?? -1; + // Native custom voices can resolve through Player/../other sound folders. + const parts = []; + for (const part of UTF8ToString(filename).replaceAll('\\', '/').split('/')) { + if (part === '..' && parts.length && parts.at(-1) !== '..') parts.pop(); + else if (part && part !== '.') parts.push(part); + } + return AOSoundSizes[parts.join('/').toLowerCase()] ?? -1; }, ao_asset_base_url__deps: ['$stringToNewUTF8'], ao_asset_base_url__proxy: 'sync', diff --git a/client/tests/browser_sound_metadata.mjs b/client/tests/browser_sound_metadata.mjs @@ -46,6 +46,17 @@ assert.equal(requests, initializedRequests); assert.equal(requests, 1); console.log('PASS: sound sizes use startup metadata without filesystem access or later requests'); +const relativeSounds = ['cd_image/sound/Player/../Test.wav', + '.\\CD_IMAGE\\SOUND\\Player\\..\\TEST.WAV', + './cd_image//sound/./Test.wav', '../cd_image/sound/Test.wav', + 'cd_image/sound/../data/file.dat']; + +const relativeSizes = relativeSounds.map(library.ao_sound_file_size); + +assert.deepEqual(relativeSizes, [1234, 1234, 1234, -1, -1]); +assert.equal(requests, initializedRequests); +console.log('PASS: native relative sound paths use the same manifest entry'); + const fetch = context.fetch; const delays = []; let attempts = 0, warnings = 0; diff --git a/client/tests/player_voice.c b/client/tests/player_voice.c @@ -0,0 +1,94 @@ +#include "recomp_types.h" +#include <assert.h> + +void sub_3A007940(void); +void sub_3A002F50(void); + +static unsigned formats, lookups, scheduled; + +/* Keep native formatting/cache selection; observe its existing sound boundary. */ +static void format_filename(void) +{ + assert(!strcmp((char *)ADDR(MEM32(g_esp + 8)), "sfx\\Player\\%s")); + g_eax = sprintf((char *)ADDR(MEM32(g_esp + 4)), "sfx\\Player\\%s", + (char *)ADDR(MEM32(g_esp + 12))); + ++formats; + g_esp += 4; +} + +static void hash_filename(void) +{ + assert(!strncmp((char *)ADDR(MEM32(g_esp + 4)), "sfx\\Player\\", 11)); + g_eax = 123; + g_esp += 4; +} + +static void find_sound(void) +{ + assert(g_ecx == 0x50001000 && MEM32(g_esp + 4) == 123); + ++lookups; + g_eax = 0x50002000; + g_esp += 8; +} + +static void schedule_sound(void) +{ + assert(g_ecx == 0x50001000 && MEM32(g_esp + 4) == 0x50002000); + assert(*(float *)ADDR(g_esp + 8) == 0.375f); + ++scheduled; + g_esp += 60; +} + +recomp_func_t recomp_lookup(uint32_t address) +{ + switch (address) { + case 0x3a002f50: return sub_3A002F50; + case 0x3a0022e0: return hash_filename; + case 0x3a002300: return find_sound; + case 0x3a002360: return schedule_sound; + case 0x70000000: return format_filename; + default: fprintf(stderr, "unexpected player voice call %08x\n", address); abort(); + } +} +recomp_func_t recomp_lookup_manual(uint32_t address) { return NULL; } +recomp_func_t recomp_lookup_import(uint32_t address) { abort(); } + +static void test_filename(unsigned length) +{ + memset((void *)ADDR(0x51000000), 'a', length); + memcpy((void *)ADDR(0x51000000 + length - 4), ".wav", 5); + formats = lookups = scheduled = 0; + g_esp = 0x50008000; + MEM32(g_esp) = 0; + MEM32(g_esp + 4) = 0x51000000; + *(float *)ADDR(g_esp + 8) = 0.75f; + g_ebx = 11; g_esi = 22; g_edi = 33; g_ebp = 44; + g_fs_base = 0x52000000; + MEM32(g_fs_base) = 55; + g_fp_top = 0; + + sub_3A007940(); + + assert(formats == (length <= 248)); + assert(lookups == (length <= 248) && scheduled == (length <= 248)); + assert(g_esp == 0x50008004 && g_ebx == 11 && g_esi == 22 && g_edi == 33 && g_ebp == 44); + assert(MEM32(g_fs_base) == 55 && g_fp_top == 0); +} + +int main(void) +{ + assert(guest_map("player voice globals", 0x3a000000, 0x10000)); + assert(guest_map("player voice fixture", 0x50000000, 0x10000)); + assert(guest_map("player voice filename", 0x51000000, 0x10000)); + assert(guest_map("player voice exceptions", 0x52000000, 0x10000)); + MEM32(0x3a00d2ec) = 0x50001000; + *(float *)ADDR(0x3a00d280) = 0.5f; + MEM32(0x3a00a058) = 0x70000000; + strcpy((char *)ADDR(0x3a00d044), "sfx\\Player\\%s"); + test_filename(4); + test_filename(248); + test_filename(249); + test_filename(2048); + test_filename(65535); + puts("player voice: native filename boundary, volume, cache scheduling and ABI passed"); +} diff --git a/docs/chat-metadata.md b/docs/chat-metadata.md @@ -0,0 +1,123 @@ +# Native chat references and voices + +The server preserves native reference and voice records in live tells, Global, +Team and vicinity messages. Sender identity, channel membership and vicinity +range still come from the authenticated connections. The client handles link +display, template lookup, cached character descriptions and voice playback. + +## Original wire contract + +All counts and integers are big endian. `B` is one byte, `I` is a 32-bit integer, +`S` is a 16-bit byte count followed by string bytes without a terminator, and +`D` is a 16-bit byte count followed by raw bytes. Empty strings and blobs have +count zero. Valid metadata can accompany empty text, as a native voice can do. +Plain empty messages remain silent. Metadata contains at most one of each +record, in this order: + +| Record | Fields | +| --- | --- | +| Reference | `B(0) I I I S S` | +| Voice | `B(1) B B S S` | + +There is no record count or separate record length. The server requires exact +exhaustion, rejects truncated strings, embedded NUL, repeated/reversed records +and unknown record types. Native record2 can override Ignore and is absent from +the public producer; clients cannot relay it. These admission checks follow the +public producer, rather than the more permissive native receiver. They are +reconstruction policy, not recovered original-server moderation rules. + +Tell packet30 uses `ISD`, with a leading mode byte0 inside `D`. Group packet65 +uses `GSD`, with records alone inside `D`; server delivery inserts the sender's +`I` after `G`. The extra four bytes must fit the enclosing 16-bit frame length. +Vicinity input carries records after its text mode, and delivery packet34 puts +that mode followed by records inside `D`. Empty metadata remains valid. + +Character references contain identity type50000, character ID and zero. Their +second string is the cached description. Item references contain low/high +template IDs and quality level; their second string is empty. The visible link +label is in the message text between bytes0x11 and0x12. The first metadata +string can be empty, as it is in actual native drops. The server preserves +these fields without inventing item-template or character-description rules. + +Native voice records contain breed/sex bytes and style/effect strings. The +client resolves nickname, breed, sex and style variants before the plain effect +name. `/voice` accepts custom effects and quoted arguments, including relative +asset paths; the six examples in help are not a command whitelist. The literal +style `distunguished` comes from the original producer. Unknown breed/sex values +use native fallbacks. The relay imposes no additional enum or filename policy. +The browser sound-size lookup resolves relative components before consulting +its manifest, matching native filesystem lookup for custom voice paths. + +The MMR queue has a 260-byte filename field, prefixed by eleven bytes before +the input name. Its entry rejects names longer than 248 bytes, including `.wav`, +before formatting or allocation. It does not truncate or alias cache names. +This protects the actual native storage boundary without restricting server +voice tokens according to the receiver's possible assets or nickname. + +## Evidence and limits + +Original 14.9.1 DDR SHA256 is +`3c937161de8f690351c3c08e158431417cee9ced77a41b677e7123b61a8c9883`; +CCR SHA256 is +`4c6d8dfc7eaa39044935d94e678ee4ead922decad36ed616a7843dcb51e7c55a`. +DDR producer1000b740 defines the records; queue10009670 distinguishes tell/group +blobs; encoder100a5e10 defines empty/count behavior. CCR InsertLink10006870 and +DDR click path100052c0 establish link attachment and information-window events. +DDR command1000d540, resolver10002450 and text loader10001ce0 establish custom +voice production and local-file requirements. Complete exports, matching +snapshots and 57 validated citations are retained in +`local/chat-metadata-research/metadata.md`, `voice-playback.md` and their +manifest. Original MMR queue10002f50 and initializer10001210 establish the +filename field and its neighboring state byte. Static client +evidence does not establish original network-service policy. + +Voice requires stat389 bit0 (LandControl/Notum Wars) and both local WAV and TXT +files. The current server does not publish that entitlement, and the supplied +asset trees lack `cd_image/sound/sfx/player`. These remain separate TODOs. +The existing custom login history stores plain text and replays senderless +system messages. It does not restore references/voices or honor native Ignore; +original reconnect/history behavior still needs research. + +## Verification + +Go tests exercise authenticated tell/Global/Team delivery with no metadata, +reference, voice and both records. They cover every truncated record prefix, +unknown/privileged records, duplicates/order, embedded NUL, unsupported tell +modes, metadata-only voices, unchanged plain empty messages, maximum group +frame size, rejected-message history and stale world +sessions. World tests cover all four vicinity modes with complete and fragmented +WebSocket input and exact output bytes. The full Go suite passed in 383 seconds. + +Two GPU WASM clients reproduced the dropped-reference bug before the fix. +Afterward, native Knowledge drops delivered byte-identical metadata through +Global/tell/vicinity, and clicking received links opened the cached Soldier +description. An actual Solar-Powered Pistol inventory drop opened its native +template details. An ignored linked message reached the socket while native +scrollback stayed exactly unchanged. Runtime artifacts are retained in +`local/chat-metadata-smoke/`. + +Native voice records and local text substitution worked through Global, +vicinity and Team; Ignore left the receiver's full scrollback unchanged. A +browser-only fixture supplied a TXT companion for an existing original game +WAV and temporarily set stat389 on the two owned guest actors. The custom +relative voice path fetched that WAV and reached the real audio decoder on +both clients after the manifest lookup fix. This exercises the native path +without claiming recovery of the missing player voice pack. +Reloading both clients with an empty TXT fixture also delivered the native +metadata-only Team message and decoded its WAV on both sides. + +The native MMR fixture calls the real exported PlayPlayerFX entry and queue, +observing only formatting, cache lookup and scheduling boundaries. Linux and +WASM runs accept input length248 and reject249,2048,65535 before formatting; +volume multiplication, guest stack, preserved registers, FPU depth and exception +chain remain correct. Sound-metadata tests cover case, slash and relative-path +normalization without extra filesystem/network work. Controls (73), profiling +and publisher regressions pass. All affected Go cases passed twice under the +race detector in 154 seconds; the other vet analyzers pass with the already +tracked Go `stdversion` mismatch excluded. + +The owned team was dissolved through the native UI. Characters57/58, their +28 history copies, one buddy row and the single owned item220/location were +removed. All other database rows stayed unchanged; integrity and foreign keys +passed. Owned browser contexts closed, and the one shared LAN preview remains +on HTTPS8443. diff --git a/docs/ignore.md b/docs/ignore.md @@ -87,8 +87,10 @@ 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 +WebSocket streams, authenticated sender identity, validated client metadata, +malformed payloads, emote distance and durable history. Live reference and voice +records preserve the same native Ignore boundary; see [chat metadata](chat-metadata.md). +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 diff --git a/docs/protocol.md b/docs/protocol.md @@ -551,12 +551,12 @@ 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). +and voice record1 (`BBBSS`), in that order. The server validates counted fields, +order and exact exhaustion before relaying these records. It rejects native +type2, which can bypass Ignore and is absent from the public producer. Tell +blobs start with mode0; group blobs contain records alone. Empty strings/blobs +have count zero, without a fallback NUL. See [chat metadata](chat-metadata.md) +for native link/voice behavior, evidence and verification. 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/server/chat.go b/server/chat.go @@ -25,9 +25,6 @@ func chatPacket(kind uint16, body []byte) []byte { } func appendChatString(body []byte, value string) []byte { - if value == "" { - value = "\x00" - } body = binary.BigEndian.AppendUint16(body, uint16(len(value))) return append(body, value...) } @@ -241,6 +238,10 @@ func (server *server) serveChatClient(client *chatClient) error { } func (server *server) handleChatMessage(client *chatClient, kind uint16, body []byte) error { + // Public-group delivery adds a sender ID to the client's counted body. + if kind == 65 && len(body) > 65531 { + return fmt.Errorf("chat message exceeds delivery frame") + } var recipient, groupID uint32 var groupType byte if kind == 30 { @@ -258,12 +259,22 @@ func (server *server) handleChatMessage(client *chatClient, kind uint16, body [] body = body[5:] } message, ok := readChatString(&body) - _, blobOK := readChatString(&body) + blob, blobOK := readChatString(&body) message = strings.TrimSuffix(message, "\x00") if !ok || !blobOK || len(body) != 0 || len(message) > 4096 || strings.ContainsRune(message, 0) { return fmt.Errorf("invalid chat message") } - if message == "" { + metadata := []byte(blob) + if kind == 30 { + if len(metadata) == 0 || metadata[0] != 0 { + return fmt.Errorf("invalid chat tell mode") + } + metadata = metadata[1:] + } + if !validChatMetadata(metadata) { + return fmt.Errorf("invalid chat metadata") + } + if message == "" && len(metadata) == 0 { return nil } @@ -314,7 +325,7 @@ func (server *server) handleChatMessage(client *chatClient, kind uint16, body [] } outgoing = binary.BigEndian.AppendUint32(outgoing, id) outgoing = appendChatString(outgoing, message) - outgoing = appendChatString(outgoing, "") + outgoing = appendChatString(outgoing, blob) channel := "tell" if kind == 65 { channel = "Global" @@ -332,16 +343,16 @@ func (server *server) handleChatMessage(client *chatClient, kind uint16, body [] return nil } -func (server *server) sendVicinity(id uint32, kind uint32, message string) { +func (server *server) sendVicinity(client *worldClient, kind uint32, message string, metadata []byte) { message = strings.TrimSuffix(message, "\x00") - if kind > 3 || len(message) == 0 || len(message) > 4096 || strings.ContainsRune(message, 0) { + if kind > 3 || len(message) == 0 && len(metadata) == 0 || len(message) > 4096 || strings.ContainsRune(message, 0) { return } radius := [4]float32{10, 1.5, 60, 10}[kind] server.chatLogMutex.Lock() server.mutex.Lock() - sender := server.characters[id] - if sender == nil || server.clients[id] == nil || !server.clients[id].ready { + sender := server.characters[client.id] + if sender == nil || server.clients[client.id] != client || !client.ready { server.mutex.Unlock() server.chatLogMutex.Unlock() return @@ -364,12 +375,14 @@ func (server *server) sendVicinity(id uint32, kind uint32, message string) { } server.mutex.Unlock() - server.logChat_locked(chatHistoryEntry{Channel: [4]string{"say", "whisper", "shout", "emote"}[kind], SenderID: id, Sender: name, Playfield: playfield, Message: message}, recipients) + server.logChat_locked(chatHistoryEntry{Channel: [4]string{"say", "whisper", "shout", "emote"}[kind], SenderID: client.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)) + body := appendChatString(binary.BigEndian.AppendUint32(nil, client.id), message) + body = binary.BigEndian.AppendUint16(body, uint16(1+len(metadata))) + body = append(body, byte(kind)) + body = append(body, metadata...) for _, target := range recipients { - if target.send(chatNamePacket(id, name)) == nil { + if target.send(chatNamePacket(client.id, name)) == nil { target.send(chatPacket(34, body)) } } diff --git a/server/chat_history_test.go b/server/chat_history_test.go @@ -31,7 +31,11 @@ func TestChatHistoryRecordsChannelsAndLegacyText(t *testing.T) { if kind == 65 { body = []byte{0x87, 0, 0, 0, 1} } - if _, err := alice.Write(chatPacket(kind, appendChatString(appendChatString(body, message), ""))); err != nil { + blob := "" + if kind == 30 { + blob = "\x00" + } + if _, err := alice.Write(chatPacket(kind, appendChatString(appendChatString(body, message), blob))); err != nil { t.Fatal(err) } for range 2 { @@ -45,7 +49,7 @@ func TestChatHistoryRecordsChannelsAndLegacyText(t *testing.T) { t.Fatal(err) } for _, kind := range []uint32{0, 1, 2, 3} { - server.sendVicinity(2, kind, message) + server.sendVicinity(server.clients[2], kind, message, nil) } data, err := readTestChatHistory(server, 1) @@ -80,10 +84,10 @@ func TestChatHistoryRecordsChannelsAndLegacyText(t *testing.T) { func TestChatHistoryPersistsAcrossDatabaseConnections(t *testing.T) { world := chatTestServer(t) - world.sendVicinity(1, 0, "first") + world.sendVicinity(world.clients[1], 0, "first", nil) restarted := &server{characters: world.characters, clients: world.clients} - restarted.sendVicinity(1, 0, "second") + restarted.sendVicinity(restarted.clients[1], 0, "second", nil) defer restarted.db.Close() history, err := restarted.chatHistory_locked(1) info, statErr := os.Stat("data/world.sqlite") @@ -100,10 +104,10 @@ func TestChatHistoryExcludesRejectedMessages(t *testing.T) { server := chatTestServer(t) for _, message := range []string{"", "bad\x00message", strings.Repeat("x", 4097)} { - server.sendVicinity(1, 0, message) + server.sendVicinity(server.clients[1], 0, message, nil) } - server.sendVicinity(1, 4, "invalid kind") - server.sendVicinity(3, 0, "unknown sender") + server.sendVicinity(server.clients[1], 4, "invalid kind", nil) + server.sendVicinity(&worldClient{id: 3, ready: true}, 0, "unknown sender", nil) if _, err := os.Stat("data/world.sqlite"); !os.IsNotExist(err) { t.Fatalf("rejected messages created history: %v", err) @@ -118,7 +122,7 @@ func TestChatHistoryKeepsConcurrentMessagesIntact(t *testing.T) { writers.Add(1) go func() { defer writers.Done() - server.sendVicinity(1, 0, "concurrent message") + server.sendVicinity(server.clients[1], 0, "concurrent message", nil) }() } writers.Wait() @@ -146,7 +150,7 @@ func TestChatHistoryFailureDoesNotPreventDelivery(t *testing.T) { done := make(chan struct{}) go func() { - server.sendVicinity(2, 0, "still delivered") + server.sendVicinity(server.clients[2], 0, "still delivered", nil) close(done) }() _, _, nameErr := readChatPacket(alice) @@ -163,7 +167,7 @@ func TestChatHistoryRestoresReceivedMessagesAfterMovingAndRestarting(t *testing. alice := loginChatTest(t, world, 1) done := make(chan struct{}) go func() { - world.sendVicinity(2, 0, "h\xe9 from Bob") + world.sendVicinity(world.clients[2], 0, "h\xe9 from Bob", nil) close(done) }() for range 2 { @@ -176,7 +180,7 @@ func TestChatHistoryRestoresReceivedMessagesAfterMovingAndRestarting(t *testing. world.mutex.Lock() world.characters[2].position[0] = 11 world.mutex.Unlock() - world.sendVicinity(2, 0, "outside Alice's vicinity") + world.sendVicinity(world.clients[2], 0, "outside Alice's vicinity", nil) world.mutex.Lock() world.characters[1].position[0] = 100 world.mutex.Unlock() @@ -204,7 +208,7 @@ func TestChatHistoryRestoresTellsOnlyForTheirParticipants(t *testing.T) { alice := loginChatTest(t, world, 1) bob := loginChatTest(t, world, 2) packet := binary.BigEndian.AppendUint32(nil, 2) - packet = appendChatString(appendChatString(packet, "private conversation"), "") + packet = appendChatString(appendChatString(packet, "private conversation"), "\x00") if _, err := alice.Write(chatPacket(30, packet)); err != nil { t.Fatal(err) } @@ -292,7 +296,7 @@ func TestChatHistoryRestoresNewestEntriesOnlyForItsOwner(t *testing.T) { func TestChatHistoryFinishesBeforeLiveDelivery(t *testing.T) { world := chatTestServer(t) - world.sendVicinity(1, 0, "earlier message") + world.sendVicinity(world.clients[1], 0, "earlier message", nil) alice, _ := startChatTest(t, world, 0) if _, err := alice.Write(chatTestAuth(1)); err != nil { t.Fatal(err) @@ -303,7 +307,7 @@ func TestChatHistoryFinishesBeforeLiveDelivery(t *testing.T) { done := make(chan struct{}) go func() { - world.sendVicinity(2, 0, "new message") + world.sendVicinity(world.clients[2], 0, "new message", nil) close(done) }() var kinds []uint16 diff --git a/server/chat_integration_test.go b/server/chat_integration_test.go @@ -155,26 +155,31 @@ func TestBrowserWorldVicinityMatchesAcrossWebSocketBoundaries(t *testing.T) { t.Fatalf("chat initialization: %d %v", kind, err) } } + metadata := []byte{0, 0, 0, 195, 80, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 4, 'i', 'n', 'f', 'o', + 1, 1, 3, 0, 6, 's', 'i', 'm', 'p', 'l', 'e', 0, 3, 'y', 'e', 's'} var delivered [][]byte - 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, 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 { - kind, body, err := readChatPacket(chatConnection) - if err != nil { - t.Fatal(err) + for _, extra := range [][]byte{nil, metadata} { + for _, message := range [][2]byte{{3, 0}, {2, 1}, {4, 2}, {3, 3}} { + // 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, message[0], 0, 0, 0xc3, 0x50, 0, 0, 0, 2, + 0, 0, 0, 5, 0, 2, 'h', 0xe9, message[1], + } + packet = append(packet, extra...) + binary.BigEndian.PutUint16(packet[6:8], uint16(len(packet))) + binary.BigEndian.PutUint32(packet[28:32], uint32(len(packet)-32)) + for len(packet)%4 != 0 { + packet = append(packet, 0) + } + write(worldSocket, packet) + for range 2 { + kind, body, err := readChatPacket(chatConnection) + if err != nil { + t.Fatal(err) + } + delivered = append(delivered, chatPacket(kind, body)) } - delivered = append(delivered, chatPacket(kind, body)) } } @@ -186,11 +191,16 @@ func TestBrowserWorldVicinityMatchesAcrossWebSocketBoundaries(t *testing.T) { }) { t.Fatalf("chat server announcement: %x", announcement) } - for index, expectedKind := range []byte{0, 1, 2, 3, 0} { + for index, expectedKind := range []byte{0, 1, 2, 3, 0, 1, 2, 3} { 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]) } - if !bytes.Equal(delivered[index*2+1], []byte{0, 34, 0, 11, 0, 0, 0, 1, 0, 2, 'h', 0xe9, 0, 1, expectedKind}) { + expected := []byte{0, 34, 0, 11, 0, 0, 0, 1, 0, 2, 'h', 0xe9, 0, 1, expectedKind} + if index >= 4 { + expected[3], expected[13] = 48, 38 + expected = append(expected, metadata...) + } + if !bytes.Equal(delivered[index*2+1], expected) { t.Fatalf("vicinity subtype %d: %x", expectedKind, delivered[index*2+1]) } } @@ -289,7 +299,7 @@ func TestBrowserChatHistoryFollowsPlayerAcrossSessionsAndTokenChanges(t *testing } } if index == 0 { - world.sendVicinity(2, 0, "remember across browsers") + world.sendVicinity(world.clients[2], 0, "remember across browsers", nil) for _, expected := range []uint16{20, 34} { if kind, _, err := readChatPacket(connection); err != nil || kind != expected { t.Fatalf("live chat: %d %v", kind, err) @@ -328,6 +338,8 @@ func TestWorldVicinityRejectsMalformedPayloads(t *testing.T) { {"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 }}, + {"override metadata", func(packet []byte) []byte { packet[31] = 6; return append(packet, 2, 1) }}, + {"truncated metadata", func(packet []byte) []byte { packet[31] = 5; return append(packet, 0) }}, } { t.Run(test.name, func(t *testing.T) { world := chatTestServer(t) diff --git a/server/chat_metadata.go b/server/chat_metadata.go @@ -0,0 +1,32 @@ +package main + +import "strings" + +func validChatMetadata(data []byte) bool { + // Native public messages contain at most one reference, then one voice record. + for record := byte(0); record < 2; record++ { + if len(data) == 0 { + return true + } + if data[0] != record { + continue + } + length := 13 // Record type and three reference integers. + if record == 1 { + length = 3 // Record type and two voice bytes. + } + if len(data) < length { + return false + } + data = data[length:] + + // Both records end in two counted C strings, excluding the terminator. + for range 2 { + text, ok := readChatString(&data) + if !ok || strings.ContainsRune(text, 0) { + return false + } + } + } + return len(data) == 0 +} diff --git a/server/chat_metadata_test.go b/server/chat_metadata_test.go @@ -0,0 +1,294 @@ +package main + +import ( + "bytes" + "fmt" + "io" + "strings" + "testing" +) + +func TestChatRelaysNativeMetadata(t *testing.T) { + reference := []byte{0, 0, 0, 195, 80, 0, 0, 0, 2, 0, 0, 0, 0, 0, 3, 'B', 'o', 'b', 0, 4, 'i', 'n', 'f', 'o'} + voice := []byte{1, 1, 3, 0, 6, 's', 'i', 'm', 'p', 'l', 'e', 0, 3, 'y', 'e', 's'} + for _, metadata := range [][]byte{nil, reference, voice, append(append([]byte(nil), reference...), voice...)} { + for _, channel := range []string{"tell", "Global", "Team"} { + t.Run(fmt.Sprintf("%s/metadata_%d", channel, len(metadata)), func(t *testing.T) { + world := teamChatWorld(t) + if channel == "Team" { + formTestTeam(t, world, 1, 2) + } + alice := loginTeamChat(t, world, 1) + bob := loginTeamChat(t, world, 2) + if channel == "Team" { + expectTeamChatGroup(t, alice, 60, 1) + expectTeamChatGroup(t, bob, 60, 1) + } + kind := uint16(65) + prefix := []byte{0x87, 0, 0, 0, 1} + blob := metadata + if channel == "tell" { + kind = 30 + prefix = []byte{0, 0, 0, 2} + blob = append([]byte{0}, metadata...) + } else if channel == "Team" { + prefix[0] = 2 + } + body := appendChatString(prefix, "hello") + body = append(body, byte(len(blob)>>8), byte(len(blob))) + body = append(body, blob...) + + if _, err := alice.Write(chatPacket(kind, body)); err != nil { + t.Fatal(err) + } + nameKind, nameBody, nameErr := readChatPacket(bob) + actualKind, actual, err := readChatPacket(bob) + + if nameErr != nil || nameKind != 20 || !bytes.Equal(nameBody[:4], []byte{0, 0, 0, 1}) { + t.Fatalf("sender identity: %d %x %v", nameKind, nameBody, nameErr) + } + expected := []byte{0, 0, 0, 1} + if kind == 65 { + expected = append(append([]byte(nil), prefix...), expected...) + } + expected = append(expected, 0, 5, 'h', 'e', 'l', 'l', 'o', byte(len(blob)>>8), byte(len(blob))) + expected = append(expected, blob...) + if err != nil || actualKind != kind || !bytes.Equal(actual, expected) { + t.Fatalf("metadata relay: %d %x expected %x error %v", actualKind, actual, expected, err) + } + }) + } + } +} + +func TestChatRejectsMalformedMetadata(t *testing.T) { + reference := []byte{0, 0, 0, 195, 80, 0, 0, 0, 2, 0, 0, 0, 0, 0, 1, 'x', 0, 0} + voice := []byte{1, 1, 3, 0, 6, 's', 'i', 'm', 'p', 'l', 'e', 0, 3, 'y', 'e', 's'} + cases := [][]byte{ + {2, 1}, {255}, {0}, {1}, + append(append([]byte(nil), reference...), reference...), + append(append([]byte(nil), voice...), voice...), + append(append([]byte(nil), voice...), reference...), + append(append([]byte(nil), reference...), 2, 1), + append(append([]byte(nil), reference...), 255), + {0, 0, 0, 195, 80, 0, 0, 0, 2, 0, 0, 0, 0, 0, 1, 0, 0, 0}, + } + for length := 1; length < len(reference); length++ { + cases = append(cases, reference[:length]) + } + for length := 1; length < len(voice); length++ { + cases = append(cases, voice[:length]) + } + for index, metadata := range cases { + for _, kind := range []uint16{30, 65} { + t.Run(fmt.Sprintf("kind_%d/case_%d", kind, index), func(t *testing.T) { + world := chatTestServer(t) + peer, done := startChatTest(t, world, 0) + if _, err := peer.Write(chatTestAuth(1)); err != nil { + t.Fatal(err) + } + for range 3 { + if _, _, err := readChatPacket(peer); err != nil { + t.Fatal(err) + } + } + prefix := []byte{0x87, 0, 0, 0, 1} + blob := metadata + if kind == 30 { + prefix = []byte{0, 0, 0, 2} + blob = append([]byte{0}, metadata...) + } + body := appendChatString(prefix, "hello") + body = append(body, byte(len(blob)>>8), byte(len(blob))) + body = append(body, blob...) + + if _, err := peer.Write(chatPacket(kind, body)); err != nil { + t.Fatal(err) + } + _, _, err := readChatPacket(peer) + + if err != io.EOF { + t.Fatalf("malformed metadata accepted: %v", err) + } + if ended := <-done; ended == nil { + t.Fatal("malformed metadata had no disconnect reason") + } + history, historyErr := world.chatHistory_locked(1) + if historyErr != nil || len(history) != 0 { + t.Fatalf("rejected metadata entered history: %+v %v", history, historyErr) + } + }) + } + } +} + +func TestChatDeliversVoiceWithoutText(t *testing.T) { + for _, channel := range []string{"tell", "Global", "Team", "vicinity"} { + t.Run(channel, func(t *testing.T) { + world := teamChatWorld(t) + if channel == "Team" { + formTestTeam(t, world, 1, 2) + } + alice := loginTeamChat(t, world, 1) + bob := loginTeamChat(t, world, 2) + if channel == "Team" { + expectTeamChatGroup(t, alice, 60, 1) + expectTeamChatGroup(t, bob, 60, 1) + } + voice := []byte{1, 1, 3, 0, 6, 's', 'i', 'm', 'p', 'l', 'e', 0, 3, 'y', 'e', 's'} + kind := uint16(65) + prefix := []byte{0x87, 0, 0, 0, 1} + blob := voice + if channel == "tell" || channel == "vicinity" { + kind = 30 + prefix = []byte{0, 0, 0, 2} + blob = append([]byte{0}, voice...) + } else if channel == "Team" { + prefix[0] = 2 + } + body := appendChatString(prefix, "") + body = appendChatString(body, string(blob)) + + if channel == "vicinity" { + world.sendVicinity(world.clients[1], 0, "", voice) + kind = 34 + } else if _, err := alice.Write(chatPacket(kind, body)); err != nil { + t.Fatal(err) + } + nameKind, _, nameErr := readChatPacket(bob) + actualKind, actual, err := readChatPacket(bob) + + if nameErr != nil || nameKind != 20 { + t.Fatalf("sender name: %d %v", nameKind, nameErr) + } + expected := []byte{0, 0, 0, 1, 0, 0, 0, 17, 0} + if kind == 65 { + expected = append(append([]byte(nil), prefix...), 0, 0, 0, 1, 0, 0, 0, 16) + } + expected = append(expected, voice...) + if err != nil || actualKind != kind || !bytes.Equal(actual, expected) { + t.Fatalf("voice without text: %d %x expected %x error %v", actualKind, actual, expected, err) + } + }) + } +} + +func TestChatIgnoresEmptyTextWithoutMetadata(t *testing.T) { + world := chatTestServer(t) + alice := loginChatTest(t, world, 1) + bob := loginChatTest(t, world, 2) + tell := appendChatString([]byte{0, 0, 0, 2}, "") + tell = appendChatString(tell, "\x00") + group := appendChatString([]byte{0x87, 0, 0, 0, 1}, "") + group = appendChatString(group, "") + + world.sendVicinity(world.clients[1], 0, "", nil) + if _, err := alice.Write(chatPacket(30, tell)); err != nil { + t.Fatal(err) + } + if _, err := alice.Write(chatPacket(65, group)); err != nil { + t.Fatal(err) + } + + expectChatPing(t, alice) + expectChatPing(t, bob) + history, err := world.chatHistory_locked(1) + if err != nil || len(history) != 0 { + t.Fatalf("empty messages entered history: %+v %v", history, err) + } +} + +func TestChatRejectsUnsupportedTellModes(t *testing.T) { + for _, blob := range [][]byte{nil, {1}, {2}} { + t.Run(fmt.Sprintf("blob_%x", blob), func(t *testing.T) { + world := chatTestServer(t) + peer, done := startChatTest(t, world, 0) + if _, err := peer.Write(chatTestAuth(1)); err != nil { + t.Fatal(err) + } + for range 3 { + if _, _, err := readChatPacket(peer); err != nil { + t.Fatal(err) + } + } + body := appendChatString([]byte{0, 0, 0, 2}, "hello") + body = appendChatString(body, string(blob)) + + if _, err := peer.Write(chatPacket(30, body)); err != nil { + t.Fatal(err) + } + _, _, err := readChatPacket(peer) + + if err != io.EOF { + t.Fatalf("unsupported tell mode was relayed: %v", err) + } + if ended := <-done; ended == nil { + t.Fatal("missing rejection reason") + } + }) + } +} + +func TestChatGroupMetadataFitsDeliveryFrame(t *testing.T) { + for _, size := range []int{65500, 65501} { + t.Run(fmt.Sprint(size), func(t *testing.T) { + world := chatTestServer(t) + alice, done := startChatTest(t, world, 0) + if _, err := alice.Write(chatTestAuth(1)); err != nil { + t.Fatal(err) + } + for range 3 { + if _, _, err := readChatPacket(alice); err != nil { + t.Fatal(err) + } + } + bob := loginChatTest(t, world, 2) + metadata := []byte{0, 0, 0, 195, 80, 0, 0, 0, 2, 0, 0, 0, 0} + metadata = appendChatString(metadata, strings.Repeat("x", size)) + metadata = appendChatString(metadata, "") + body := appendChatString([]byte{0x87, 0, 0, 0, 1}, "hello") + body = appendChatString(body, string(metadata)) + + if _, err := alice.Write(chatPacket(65, body)); err != nil { + t.Fatal(err) + } + + if size == 65501 { + if _, _, err := readChatPacket(alice); err != io.EOF { + t.Fatalf("oversized group accepted: %v", err) + } + if ended := <-done; ended == nil { + t.Fatal("missing rejection reason") + } + expectChatPing(t, bob) + history, err := world.chatHistory_locked(1) + if err != nil || len(history) != 0 { + t.Fatalf("rejected group entered history: %+v %v", history, err) + } + return + } + if kind, _, err := readChatPacket(bob); err != nil || kind != 20 { + t.Fatalf("name packet: %d %v", kind, err) + } + kind, actual, err := readChatPacket(bob) + if err != nil || kind != 65 || len(actual) != 65535 || !bytes.Equal(actual[18:], metadata) { + t.Fatalf("maximum group frame: %d length %d error %v", kind, len(actual), err) + } + }) + } +} + +func TestChatVicinityRejectsReplacedSession(t *testing.T) { + world := chatTestServer(t) + bob := loginChatTest(t, world, 2) + previous := &worldClient{id: 1, ready: true} + metadata := []byte{0, 0, 0, 195, 80, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 4, 'i', 'n', 'f', 'o'} + + world.sendVicinity(previous, 0, "stale reference", metadata) + + expectChatPing(t, bob) + history, err := world.chatHistory_locked(1) + if err != nil || len(history) != 0 { + t.Fatalf("stale session entered history: %+v %v", history, err) + } +} diff --git a/server/chat_output_test.go b/server/chat_output_test.go @@ -14,7 +14,7 @@ func TestChatSlowRecipientDoesNotBlockVicinityDelivery(t *testing.T) { done := make(chan struct{}) t.Cleanup(func() { alice.Close(); bob.Close(); <-done }) - go func() { world.sendVicinity(1, 0, "hello"); close(done) }() + go func() { world.sendVicinity(world.clients[1], 0, "hello", nil); close(done) }() select { case <-done: diff --git a/server/chat_test.go b/server/chat_test.go @@ -151,11 +151,11 @@ func TestChatGlobalIncludesSenderIdentity(t *testing.T) { server := chatTestServer(t) peer := loginChatTest(t, server, 1) - peer.Write([]byte{0, 65, 0, 12, 0x87, 0, 0, 0, 1, 0, 2, 'h', 'i', 0, 1, 0}) + peer.Write([]byte{0, 65, 0, 11, 0x87, 0, 0, 0, 1, 0, 2, 'h', 'i', 0, 0}) readChatPacket(peer) kind, body, err := readChatPacket(peer) - if err != nil || kind != 65 || !bytes.Equal(body, []byte{0x87, 0, 0, 0, 1, 0, 0, 0, 1, 0, 2, 'h', 'i', 0, 1, 0}) { + if err != nil || kind != 65 || !bytes.Equal(body, []byte{0x87, 0, 0, 0, 1, 0, 0, 0, 1, 0, 2, 'h', 'i', 0, 0}) { t.Fatalf("global chat: %d %x %v", kind, body, err) } } @@ -226,7 +226,7 @@ func TestChatVicinityUsesWorldDistanceAndReadiness(t *testing.T) { done := make(chan struct{}) go func() { - server.sendVicinity(1, test.kind, "hello") + server.sendVicinity(server.clients[1], test.kind, "hello", nil) close(done) }() if !test.delivered { diff --git a/server/main.go b/server/main.go @@ -450,8 +450,11 @@ func (server *server) serveWorldClient(client *worldClient) error { if strings.ContainsRune(message, '\x00') { return fmt.Errorf("invalid vicinity text") } - // Client metadata is not relayed until its reference/voice records are validated. - server.sendVicinity(character.id, kind, message) + metadata := packet[35+textLength:] + if !validChatMetadata(metadata) { + return fmt.Errorf("invalid vicinity metadata") + } + server.sendVicinity(client, kind, message, metadata) case 10: // The client compresses individual movement messages with zlib. body := packet[16:] diff --git a/server/users_test.go b/server/users_test.go @@ -280,7 +280,7 @@ func TestPlayerDirectoryPreservesProfileAndChatAfterRestart(t *testing.T) { } world.clients[1] = &worldClient{id: 1, ready: true} - world.sendVicinity(1, 0, "saved under player ID") + world.sendVicinity(world.clients[1], 0, "saved under player ID", nil) restarted := newServer() restarted.clients[1] = &worldClient{id: 1, ready: true} peer := loginChatTest(t, restarted, 1)