commit 0cceab8510e58e02f1be404cd68e53e97ce784cb
parent b259aaf9677d37a042839a8424b85c866cb7edd7
Author: anon <anon@example.com>
Date: Sat, 24 Oct 2026 09:33:57 +0000
Persist friends and publish chat presence
Diffstat:
11 files changed, 780 insertions(+), 7 deletions(-)
diff --git a/TODO.md b/TODO.md
@@ -707,8 +707,24 @@ and unresolved indoor lifecycle are explicit in [flight](docs/vehicles.md#yalmah
swimming, combat or other restrictions beyond the recovered client paths.
The reader permits 1..63 but the named table contains only 1..62; do not
invent a gesture, cooldown or posture change for the unresolved entry.
-- [ ] Persist a friend-list entry. Check: adding/removing a friend survives
+- [x] Persist a friend-list entry. Check: adding/removing a friend survives
reconnect and the appropriate online-status updates reach the owner.
+ Original 40/41 buddy packets and counted `/cc` commands share atomic SQLite
+ mutations. Saved and temporary entries, promotion, removal, clearing `?`,
+ offline/online changes, owner reload and process restart passed two-client
+ hardware WASM checks. Regressions cover SQL/commit/ignored-write failures,
+ partial-group rollback, interrupted acknowledgments, privacy, replacements,
+ control edits and world zoning gaps without persisting status traffic.
+ Source and verification: [friends](docs/buddies.md).
+- [ ] Recover remaining original friend-list policies. Check: period evidence
+ establishes temporary-entry durability, maximum list size, other presence
+ states and original denial behavior; do not invent limits or away flags.
+- [ ] Verify the native reference and Friends-window action paths. Check:
+ Alt+left-click creates a player reference, dropping it adds a permanent
+ friend, Accept promotes a temporary entry and Remove sends native 41.
+ Exercise self/NPC references and repeat actions. The manual reference attempt
+ left Knowledge empty; investigate input/reference handling before claiming
+ these UI paths work. Commands and incoming-tell addition are verified.
- [ ] Ignore one player. Check: the supported chat channels honor the saved
ignore entry and removing it restores delivery.
- [ ] Recover original channel flags, preferences and flood rules. Check: native
diff --git a/docs/buddies.md b/docs/buddies.md
@@ -0,0 +1,120 @@
+# Friends and recent correspondents
+
+The original 14.9.1 Friends window uses one entry per character, with status
+and an opaque metadata blob. Status 0 is offline and 1 is online. A one-byte
+blob of 0 places the entry in the temporary `?` group; 1 makes it permanent.
+The native UI treats other nonzero bytes as permanent and defaults to permanent
+when the blob length differs from one. Metadata is preserved byte for byte.
+
+## Original client evidence
+
+These observations use original `ddr.dll`, SHA-256
+`3c937161de8f690351c3c08e158431417cee9ced77a41b677e7123b61a8c9883`.
+The complete retained export and ledger are in `local/buddy-research/`.
+The export contains 94 records, 16,720,849 bytes, SHA-256
+`2fe84db4eee7a800eef409be9c4962e0887e5b8de794ce262e296a2d56474463`.
+
+Chat framing is big-endian type u16, body length u16. `I` is u32 and `D` is
+a u16 byte count followed by opaque bytes. Names use the same counted layout.
+
+| Direction/type | Body | Meaning |
+| --- | --- | --- |
+| C2S 40 | `ID` | Add/update entry |
+| S2C 40 | `IID` | ID, online status, metadata |
+| C2S/S2C 41 | `I` | Remove entry |
+| C2S 120 | Count u16, counted words | `/cc` account command |
+
+The selected receive dispatcher has no type 42 branch; presence is another
+type 40 update. Names arrive separately in type 20. Sending the name before
+the first buddy update avoids a transient unnamed row.
+
+Original symbols and retained evidence:
+
+- `ddr.dll` sender 0x1009d110 sends C2S 40 `ID`; sender 0x1009d140 sends 41
+ `I`. Evidence `ev_fb7a29e75b3c7686412c578c0391ef888fa792158963a0e6bdc6cf90387daa2a`,
+ `ev_1452ef70616b7ccbaea548c83d5e4f102e8e275ff3e2975c55bcfa2de8b892ad`,
+ `ev_b820a17916d35e4592be27b39ab310290eb92bba33fde47d6f4332be9df5de10`.
+- `ddr.dll` dispatcher 0x1009d780 receives 40 `IID`, updates existing entries,
+ removes them on 41 and updates names from 20. Evidence
+ `ev_7cbc389c64ec7925fb38fe8fc6d10d58ba346da89444cedd4d6c95b7832f2ddd`.
+- `IcqViewModule_t::UpdateBuddyList` 0x100554d0 -> 0x1004f7f0 interprets the
+ one-byte classification. Comparator 0x10053dd0 groups permanent online,
+ permanent offline, then temporary entries, sorting names within each group.
+ Draw 0x1004ea70 selects the online icon for status 1. Evidence
+ `ev_3dc259d94b94190f4b355ebbd968ff95468dc047c299562865c2d5ea3ca5e4e1`,
+ `ev_de098002d450cb312e002518c397e746605d576c995f39a9921deed226213a66`,
+ `ev_f2965c57a1066e4f8aa529a7e2b1867c79005259d3eb1691e14b6a240e80c4dc`.
+- `MaybeAddToBuddyList` 0x100554f0 -> 0x1004fbf0 adds a new correspondent
+ with blob 0, skipping self and existing entries. Accept 0x10051280 promotes
+ it with blob 1. Reference-drop 0x10055230 accepts only player identities;
+ add wrapper 0x10012880 suppresses self-add. Evidence
+ `ev_8fa4d52fe46e5e2a6eb45f1888465aa23620df0dc4844eab0669b2610ad14731`,
+ `ev_5e072fd65b3f3f268aee45904d6276274eb6987c6cd753d7ade44896830fac90`,
+ `ev_21e5562b65c605eb044bf18149d52867127ec5499b8a2f3b77e2b0f8a9eddb64`,
+ `ev_601077ae64b4a908adf11b327f3f4161c9e6c86c6de0be19d4a385675a289c36`.
+- `/cc` parser 0x1000cc00 -> sender 0x1009d2d0 sends a counted word array
+ as type 120. Evidence
+ `ev_87d2ac13670ed54a717efb645335afcce86a0c70ccfc263b1d04dddd9959fac7`,
+ `ev_be90e96b5f5dc4ac18813f39417fdb843cd1ccec18c303658077b625775c0693`.
+
+Shipped `cd_image/text/help/ChatHelp.txt` documents `/cc addbuddy <name>`,
+`/cc rembuddy <name>` and `/cc rembuddy ?` to clear the temporary group.
+`The Friends Window.txt` describes player-reference drops and online status
+at login. Ctrl+7 opens the native window.
+
+## Server behavior
+
+`buddies` stores owner ID, buddy ID and metadata, with player foreign keys and
+one row per pair. Add, promotion, removal and clearing the temporary group
+commit before memory or acknowledgment changes. An unchanged add does not
+rewrite the row. SQL failures, ignored writes and failed commits preserve
+the previous state. Clearing the temporary group is one transaction.
+
+The server loads this graph with the characters. Presence is derived from
+live chat sessions and never stored. Login restores the list with name
+packets before buddy updates, then notifies connected owners who have saved
+the arriving character. Logout notifies those owners only. Entries do not
+create reciprocal friends or notify unrelated players. A replacement chat
+does not emit a false offline event from the departing connection. Actual
+world departure closes chat; zoning and session replacements preserve it.
+Browser transport detachment retains the existing two-minute resume grace.
+Control-panel character edits preserve the graph in memory.
+
+Names in `/cc` commands match case-insensitively. UI packets and commands
+share the same mutation path. Self, unknown players and NPCs are rejected;
+malformed frames close chat. Error text, forged-request policy and exact
+original-server limits have not been recovered. No friend-count limit is
+invented. The metadata bound only ensures the outgoing u16-length frame fits.
+
+Temporary entries are also durable in this implementation. The shipped UI
+establishes their classification and promotion, but does not establish whether
+the original server kept them across logout. That policy remains a research
+question. Other status values, away state, flood rules, private groups and
+the separate native ignore system remain outside this feature.
+
+## Verification
+
+Go tests exercise actual chat framing and session handlers for offline add,
+promotion, duplicate add, persistence/reload, case-insensitive commands,
+removal, empty and opaque metadata, temporary-group clearing, online/offline
+changes, replacement sessions, owner reconnect, notification privacy, world
+departure, malformed input and control-panel preservation. Insert, update and
+delete failures cover SQL errors, ignored mutations and failed commits;
+partial group deletion must roll back together. Zoning targets remain online
+in new snapshots and adds; owners in the world-connection gap still receive
+status changes over their retained chat connection.
+
+Two hardware WASM clients verified the native `/cc` command route, incoming
+tell creation of a temporary entry, promotion to permanent, removal and owner
+reload without the entry returning. Wire capture confirmed the native counted
+word array and one-byte metadata. Native Friends-window rows were read without
+modifying game memory and checked against screenshots, packet fields and SQL.
+The browser wrapper automatically reloads after game exit, so ordinary timed
+logout produces an offline update followed by online when that new session
+connects. Stable logout testing closes that client's tab during its countdown.
+Both saved lists also restored after a real server restart. An administrative
+teleport exercised native world reconnection on the final build: the friend
+stayed online, with no offline packet during the round trip. Artifacts are
+retained in `local/buddy-smoke/`. Player-reference creation/drop and the
+Friends-window Accept/Remove controls remain explicit TODOs; the reference
+attempt left Knowledge empty and was not counted as a successful UI check.
diff --git a/docs/protocol.md b/docs/protocol.md
@@ -555,9 +555,13 @@ The local server supports vicinity, tells, one Global channel, name lookup and
ping. Browser chat uses `/browser-chat` with the same visitor cookie as the
world connection. Native chat accepts existing local characters with a world
connection; it cannot claim a browser character. Original account encryption,
-private groups, buddy state and channel subscription preferences are not
-implemented. Tests cover malformed frames, identity spoofing, distance and
-playfield filtering, and identical complete/fragmented WebSocket streams.
+private groups and channel subscription preferences are not implemented.
+Persistent friends use C2S 40 `ID`, S2C 40 `IID` and removal 41 `I`;
+online status is another 40 update. `/cc` buddy commands use type 120 with
+a counted string array. See [friends](buddies.md) for original evidence,
+temporary entries and session behavior. Tests cover malformed frames, identity
+spoofing, distance and playfield filtering, and identical complete/fragmented
+WebSocket streams.
## Combat in 14.9.1
diff --git a/server/buddies.go b/server/buddies.go
@@ -0,0 +1,214 @@
+package main
+
+import (
+ "encoding/binary"
+ "fmt"
+ "sort"
+ "strings"
+)
+
+func chatBuddyPacket(id, status uint32, metadata string) []byte {
+ body := binary.BigEndian.AppendUint32(nil, id)
+ body = binary.BigEndian.AppendUint32(body, status)
+ body = binary.BigEndian.AppendUint16(body, uint16(len(metadata)))
+ return chatPacket(40, append(body, metadata...))
+}
+
+func (server *server) loadBuddies() error {
+ db, err := server.database()
+ if err != nil {
+ return err
+ }
+ rows, err := db.Query("SELECT player_id, buddy_id, metadata FROM buddies")
+ if err != nil {
+ return err
+ }
+ defer rows.Close()
+ for rows.Next() {
+ var owner, id uint32
+ var metadata string
+ if err := rows.Scan(&owner, &id, &metadata); err != nil {
+ return err
+ }
+ if server.characters[owner].buddies == nil {
+ server.characters[owner].buddies = make(map[uint32]string)
+ }
+ server.characters[owner].buddies[id] = metadata
+ }
+ return rows.Err()
+}
+
+func (server *server) buddyList_locked(player *character) []byte {
+ ids := make([]uint32, 0, len(player.buddies))
+ for id := range player.buddies {
+ ids = append(ids, id)
+ }
+ sort.Slice(ids, func(i, j int) bool { return ids[i] < ids[j] })
+ var packets []byte
+ for _, id := range ids {
+ status := uint32(0)
+ if server.chats[id] != nil {
+ status = 1
+ }
+ packets = append(packets, chatNamePacket(id, server.characters[id].name)...)
+ packets = append(packets, chatBuddyPacket(id, status, player.buddies[id])...)
+ }
+ return packets
+}
+
+func (server *server) buddyPresence_locked(id, status uint32) map[*chatClient][]byte {
+ updates := make(map[*chatClient][]byte)
+ for owner, target := range server.chats {
+ if metadata, exists := server.characters[owner].buddies[id]; exists {
+ updates[target] = chatBuddyPacket(id, status, metadata)
+ }
+ }
+ return updates
+}
+
+func (server *server) handleChatBuddy(client *chatClient, kind uint16, body []byte) error {
+ // Order durable mutations and presence snapshots with chat session changes.
+ server.updateMutex.Lock()
+ defer server.updateMutex.Unlock()
+ server.mutex.Lock()
+ packet, err := server.changeBuddies_locked(client, kind, body)
+ server.mutex.Unlock()
+ if err != nil {
+ return err
+ }
+ if len(packet) != 0 {
+ return client.send(packet)
+ }
+ return nil
+}
+
+func (server *server) changeBuddies_locked(client *chatClient, kind uint16, body []byte) ([]byte, error) {
+ if server.chats[client.id] != client || server.clients[client.id] == nil {
+ return nil, fmt.Errorf("chat world session ended")
+ }
+ player := server.characters[client.id]
+ var id uint32
+ var metadata string
+ remove, clearRecent := kind == 41, false
+ switch kind {
+ case 40, 41:
+ if len(body) < 4 {
+ return nil, fmt.Errorf("invalid buddy identity")
+ }
+ id, body = binary.BigEndian.Uint32(body), body[4:]
+ if kind == 40 {
+ var ok bool
+ metadata, ok = readChatString(&body)
+ if !ok || len(metadata) > 65525 {
+ return nil, fmt.Errorf("invalid buddy metadata")
+ }
+ }
+ if len(body) != 0 {
+ return nil, fmt.Errorf("invalid buddy packet length")
+ }
+ case 120:
+ if len(body) < 2 {
+ return nil, fmt.Errorf("invalid chat command")
+ }
+ count := binary.BigEndian.Uint16(body)
+ body = body[2:]
+ var words []string
+ for range count {
+ word, ok := readChatString(&body)
+ if !ok || strings.ContainsRune(word, 0) {
+ return nil, fmt.Errorf("invalid chat command word")
+ }
+ words = append(words, word)
+ }
+ if len(body) != 0 {
+ return nil, fmt.Errorf("invalid chat command length")
+ }
+ if len(words) == 0 || !strings.EqualFold(words[0], "addbuddy") && !strings.EqualFold(words[0], "rembuddy") {
+ return nil, nil
+ }
+ if len(words) != 2 {
+ return chatPacket(36, appendChatString(nil, "Usage: /cc addbuddy <name> or /cc rembuddy <name|?>")), nil
+ }
+ remove = strings.EqualFold(words[0], "rembuddy")
+ clearRecent = remove && words[1] == "?"
+ metadata = "\x01"
+ if !clearRecent {
+ for _, target := range server.characters {
+ if !target.npc && strings.EqualFold(target.name, words[1]) {
+ id = target.id
+ break
+ }
+ }
+ }
+ }
+
+ // The recent-correspondent group is a collection of ordinary buddy rows.
+ var ids []uint32
+ if clearRecent {
+ for target, blob := range player.buddies {
+ if blob == "\x00" {
+ ids = append(ids, target)
+ }
+ }
+ sort.Slice(ids, func(i, j int) bool { return ids[i] < ids[j] })
+ } else {
+ if id == client.id {
+ return chatPacket(36, appendChatString(nil, "You cannot add yourself to your friends list.")), nil
+ }
+ if target := server.characters[id]; target == nil || target.npc {
+ return chatPacket(36, appendChatString(nil, "Player not found.")), nil
+ }
+ ids = []uint32{id}
+ }
+
+ // Persist every changed row together before publishing memory or acknowledgments.
+ db, err := server.database()
+ if err != nil {
+ return nil, err
+ }
+ tx, err := db.Begin()
+ if err != nil {
+ return nil, err
+ }
+ defer tx.Rollback()
+ for _, target := range ids {
+ previous, exists := player.buddies[target]
+ if remove && !exists || !remove && exists && previous == metadata {
+ continue
+ }
+ query := "INSERT INTO buddies (player_id, buddy_id, metadata) VALUES (?, ?, ?) ON CONFLICT(player_id, buddy_id) DO UPDATE SET metadata = excluded.metadata"
+ args := []any{client.id, target, []byte(metadata)}
+ if remove {
+ query, args = "DELETE FROM buddies WHERE player_id = ? AND buddy_id = ?", args[:2]
+ }
+ result, err := tx.Exec(query, args...)
+ if err != nil {
+ return nil, err
+ }
+ if count, err := result.RowsAffected(); err != nil || count != 1 {
+ return nil, fmt.Errorf("buddy mutation affected %d rows: %v", count, err)
+ }
+ }
+ if err := tx.Commit(); err != nil {
+ return nil, err
+ }
+ var packets []byte
+ for _, target := range ids {
+ if remove {
+ delete(player.buddies, target)
+ packets = append(packets, chatPacket(41, binary.BigEndian.AppendUint32(nil, target))...)
+ continue
+ }
+ if player.buddies == nil {
+ player.buddies = make(map[uint32]string)
+ }
+ player.buddies[target] = metadata
+ status := uint32(0)
+ if server.chats[target] != nil {
+ status = 1
+ }
+ packets = append(packets, chatNamePacket(target, server.characters[target].name)...)
+ packets = append(packets, chatBuddyPacket(target, status, metadata)...)
+ }
+ return packets, nil
+}
diff --git a/server/buddies_test.go b/server/buddies_test.go
@@ -0,0 +1,380 @@
+package main
+
+import (
+ "bytes"
+ "encoding/binary"
+ "fmt"
+ "io"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "reflect"
+ "strings"
+ "testing"
+ "time"
+
+ "go.yaml.in/yaml/v3"
+)
+
+func buddyTestWorld(t *testing.T) *server {
+ t.Helper()
+ world := teamChatWorld(t)
+ for i, name := range []string{"Alice", "Bob", "Carol"} {
+ world.characters[uint32(i+1)].name = name
+ if err := world.saveUser_locked(world.characters[uint32(i+1)]); err != nil {
+ t.Fatal(err)
+ }
+ }
+ return world
+}
+
+func buddyRequest(id uint32, metadata string) []byte {
+ body := binary.BigEndian.AppendUint32(nil, id)
+ body = binary.BigEndian.AppendUint16(body, uint16(len(metadata)))
+ return chatPacket(40, append(body, metadata...))
+}
+
+func buddyCommand(words ...string) []byte {
+ body := binary.BigEndian.AppendUint16(nil, uint16(len(words)))
+ for _, word := range words {
+ body = appendChatString(body, word)
+ }
+ return chatPacket(120, body)
+}
+
+func expectBuddy(t *testing.T, peer net.Conn, id, status uint32, metadata string) {
+ t.Helper()
+ kind, body, err := readChatPacket(peer)
+ expected := binary.BigEndian.AppendUint32(nil, id)
+ expected = binary.BigEndian.AppendUint32(expected, status)
+ expected = binary.BigEndian.AppendUint16(expected, uint16(len(metadata)))
+ expected = append(expected, metadata...)
+ if err != nil || kind != 40 || !bytes.Equal(body, expected) {
+ t.Fatalf("buddy: %d %x expected=%x error=%v", kind, body, expected, err)
+ }
+}
+
+func expectBuddyName(t *testing.T, peer net.Conn, id uint32, name string) {
+ t.Helper()
+ kind, body, err := readChatPacket(peer)
+ expected := appendChatString(binary.BigEndian.AppendUint32(nil, id), name)
+ if err != nil || kind != 20 || !bytes.Equal(body, expected) {
+ t.Fatalf("buddy name: %d %x expected=%x error=%v", kind, body, expected, err)
+ }
+}
+
+func expectBuddyRemoved(t *testing.T, peer net.Conn, id uint32) {
+ t.Helper()
+ kind, body, err := readChatPacket(peer)
+ if err != nil || kind != 41 || !bytes.Equal(body, binary.BigEndian.AppendUint32(nil, id)) {
+ t.Fatalf("buddy removal: %d %x error=%v", kind, body, err)
+ }
+}
+
+func TestBuddyAddPromoteDuplicateAndRemoveSurviveRestart(t *testing.T) {
+ world := buddyTestWorld(t)
+ alice := loginTeamChat(t, world, 1)
+
+ alice.Write(buddyRequest(2, "\x00"))
+ expectBuddyName(t, alice, 2, "Bob")
+ expectBuddy(t, alice, 2, 0, "\x00")
+ alice.Write(buddyRequest(2, "\x01"))
+ expectBuddyName(t, alice, 2, "Bob")
+ expectBuddy(t, alice, 2, 0, "\x01")
+ alice.Write(buddyRequest(2, "\x01"))
+ expectBuddyName(t, alice, 2, "Bob")
+ expectBuddy(t, alice, 2, 0, "\x01")
+ restored := newTestInventoryServer(t)
+ alice.Write(chatPacket(41, []byte{0, 0, 0, 2}))
+ expectBuddyRemoved(t, alice, 2)
+ afterRemoval := newTestInventoryServer(t)
+
+ if !reflect.DeepEqual(restored.characters[1].buddies, map[uint32]string{2: "\x01"}) ||
+ len(world.characters[1].buddies) != 0 || len(afterRemoval.characters[1].buddies) != 0 || len(restored.characters[2].buddies) != 0 {
+ t.Fatal("buddy durability, uniqueness or ownership failed")
+ }
+ expectChatPing(t, alice)
+}
+
+func TestBuddyPresenceReconnectReplacementAndRemoval(t *testing.T) {
+ world := buddyTestWorld(t)
+ alice := loginTeamChat(t, world, 1)
+ outsider := loginTeamChat(t, world, 3)
+ alice.Write(buddyCommand("ADDBUDDY", "bOb"))
+ expectBuddyName(t, alice, 2, "Bob")
+ expectBuddy(t, alice, 2, 0, "\x01")
+ if _, err := world.db.Exec("CREATE TRIGGER no_buddy_writes BEFORE UPDATE ON buddies BEGIN SELECT RAISE(FAIL, 'presence must not persist'); END"); err != nil {
+ t.Fatal(err)
+ }
+
+ bob := loginTeamChat(t, world, 2)
+ expectBuddy(t, alice, 2, 1, "\x01")
+ replacement := loginTeamChat(t, world, 2)
+ expectChatPing(t, alice)
+ bob.Close()
+ expectChatPing(t, replacement)
+ replacement.Close()
+ expectBuddy(t, alice, 2, 0, "\x01")
+ bob = loginTeamChat(t, world, 2)
+ expectBuddy(t, alice, 2, 1, "\x01")
+ aliceReplacement := loginTeamChat(t, world, 1)
+ expectBuddyName(t, aliceReplacement, 2, "Bob")
+ expectBuddy(t, aliceReplacement, 2, 1, "\x01")
+ aliceReplacement.Write(buddyCommand("rembuddy", "Bob"))
+ expectBuddyRemoved(t, aliceReplacement, 2)
+ bob.Close()
+
+ expectChatPing(t, aliceReplacement)
+ expectChatPing(t, outsider)
+ if len(newTestInventoryServer(t).characters[1].buddies) != 0 {
+ t.Fatal("removed entry returned on restart")
+ }
+}
+
+func TestBuddyPresenceKeepsZoningPlayersOnlineAndDeliversDuringOwnerZoning(t *testing.T) {
+ world := buddyTestWorld(t)
+ alice := loginTeamChat(t, world, 1)
+ bob := loginTeamChat(t, world, 2)
+ carol := loginTeamChat(t, world, 3)
+ alice.Write(buddyRequest(2, "\x01"))
+ expectBuddyName(t, alice, 2, "Bob")
+ expectBuddy(t, alice, 2, 1, "\x01")
+ world.mutex.Lock()
+ delete(world.clients, 2)
+ world.mutex.Unlock()
+
+ alice = loginTeamChat(t, world, 1)
+ expectBuddyName(t, alice, 2, "Bob")
+ expectBuddy(t, alice, 2, 1, "\x01")
+ carol.Write(buddyRequest(2, "\x01"))
+ expectBuddyName(t, carol, 2, "Bob")
+ expectBuddy(t, carol, 2, 1, "\x01")
+ world.mutex.Lock()
+ delete(world.clients, 1)
+ world.mutex.Unlock()
+ bob.Close()
+
+ expectBuddy(t, alice, 2, 0, "\x01")
+ expectBuddy(t, carol, 2, 0, "\x01")
+ if restored := newTestInventoryServer(t); restored.characters[1].buddies[2] != "\x01" || restored.characters[3].buddies[2] != "\x01" {
+ t.Fatal("zoning changed durable buddy membership")
+ }
+}
+
+func TestBuddyClearRecentPreservesPermanentAndOpaqueMetadata(t *testing.T) {
+ world := buddyTestWorld(t)
+ alice := loginTeamChat(t, world, 1)
+ for id, metadata := range map[uint32]string{2: "\x00", 3: "\x01", 4: "", 5: "\x00\xff"} {
+ alice.Write(buddyRequest(id, metadata))
+ expectBuddyName(t, alice, id, world.characters[id].name)
+ expectBuddy(t, alice, id, 0, metadata)
+ }
+
+ alice.Write(buddyCommand("rembuddy", "?"))
+ expectBuddyRemoved(t, alice, 2)
+ alice.Write(buddyCommand("rembuddy", "?"))
+ expectChatPing(t, alice)
+ restored := newTestInventoryServer(t)
+
+ if !reflect.DeepEqual(restored.characters[1].buddies, map[uint32]string{3: "\x01", 4: "", 5: "\x00\xff"}) {
+ t.Fatal("clearing recent entries removed permanent entries or changed opaque metadata", restored.characters[1].buddies)
+ }
+}
+
+func TestBuddyRejectsUnknownSelfNPCAndBadCommandWithoutDisconnecting(t *testing.T) {
+ world := buddyTestWorld(t)
+ world.characters[1000000] = &character{id: 1000000, name: "NPC", npc: true}
+ alice := loginTeamChat(t, world, 1)
+
+ for _, packet := range [][]byte{buddyRequest(1, "\x01"), buddyRequest(999999, "\x01"), buddyRequest(1000000, "\x01"),
+ buddyCommand("addbuddy", "Missing"), buddyCommand("addbuddy"), buddyCommand("rembuddy", "Bob", "Carol")} {
+ alice.Write(packet)
+ kind, _, err := readChatPacket(alice)
+ if err != nil || kind != 36 {
+ t.Fatalf("invalid buddy request did not report an error: %d %v", kind, err)
+ }
+ }
+ alice.Write(buddyCommand("unimplemented"))
+ alice.Write(chatPacket(41, []byte{0, 0, 0, 2}))
+ expectBuddyRemoved(t, alice, 2)
+
+ expectChatPing(t, alice)
+ if len(newTestInventoryServer(t).characters[1].buddies) != 0 {
+ t.Fatal("invalid request persisted an entry")
+ }
+}
+
+func TestBuddyMalformedFramesCloseWithoutMutation(t *testing.T) {
+ for index, packet := range [][]byte{chatPacket(40, []byte{0, 0, 0}), chatPacket(40, []byte{0, 0, 0, 2, 0, 2, 1}),
+ chatPacket(41, []byte{0, 0, 0, 2, 0}), chatPacket(120, []byte{0, 1}),
+ buddyRequest(2, strings.Repeat("x", 65526)), buddyCommand("addbuddy", "B\x00ob")} {
+ t.Run(fmt.Sprint(index), func(t *testing.T) {
+ world := buddyTestWorld(t)
+ peer, done := startChatTest(t, world, 1)
+ peer.Write(chatTestAuth(1))
+ for range 3 {
+ readChatPacket(peer)
+ }
+
+ peer.Write(packet)
+ err := <-done
+
+ if err == nil || len(world.characters[1].buddies) != 0 || len(newTestInventoryServer(t).characters[1].buddies) != 0 {
+ t.Fatal("malformed buddy request changed state", err)
+ }
+ })
+ }
+}
+
+func TestBuddyClearRecentRollsBackAllRemovalsOnFailure(t *testing.T) {
+ world := buddyTestWorld(t)
+ peer, done := startChatTest(t, world, 1)
+ peer.Write(chatTestAuth(1))
+ for range 3 {
+ readChatPacket(peer)
+ }
+ for _, id := range []uint32{2, 3} {
+ peer.Write(buddyRequest(id, "\x00"))
+ expectBuddyName(t, peer, id, world.characters[id].name)
+ expectBuddy(t, peer, id, 0, "\x00")
+ }
+ if _, err := world.db.Exec("CREATE TRIGGER fail_buddy BEFORE DELETE ON buddies WHEN OLD.buddy_id = 3 BEGIN SELECT RAISE(FAIL, 'second deletion failed'); END"); err != nil {
+ t.Fatal(err)
+ }
+
+ peer.Write(buddyCommand("rembuddy", "?"))
+ _, _, readErr := readChatPacket(peer)
+ err := <-done
+ restored := newTestInventoryServer(t)
+
+ expected := map[uint32]string{2: "\x00", 3: "\x00"}
+ if err == nil || readErr != io.EOF || !reflect.DeepEqual(world.characters[1].buddies, expected) || !reflect.DeepEqual(restored.characters[1].buddies, expected) {
+ t.Fatal("partial recent-group deletion escaped the transaction", err, readErr)
+ }
+}
+
+func TestBuddyWorldDepartureClosesChatAndPublishesOffline(t *testing.T) {
+ world := buddyTestWorld(t)
+ alice := loginTeamChat(t, world, 1)
+ alice.Write(buddyRequest(2, "\x01"))
+ expectBuddyName(t, alice, 2, "Bob")
+ expectBuddy(t, alice, 2, 0, "\x01")
+ world.mutex.Lock()
+ delete(world.clients, 2)
+ world.mutex.Unlock()
+ peer, host := net.Pipe()
+ peer.SetDeadline(time.Now().Add(10 * time.Second))
+ done := make(chan error, 1)
+ go func() { done <- world.serveWorldConnection(host) }()
+ t.Cleanup(func() { peer.Close(); <-done })
+ peer.Write(systemPacket(0x1b, []byte{0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0}))
+ readWorldUpdates(t, peer)
+ bob := loginTeamChat(t, world, 2)
+ expectBuddy(t, alice, 2, 1, "\x01")
+
+ peer.Close()
+
+ expectBuddy(t, alice, 2, 0, "\x01")
+ if _, _, err := readChatPacket(bob); err != io.EOF {
+ t.Fatal("departed world left the chat connection alive", err)
+ }
+}
+
+func TestBuddyControlEditPreservesSavedList(t *testing.T) {
+ world := buddyTestWorld(t)
+ alice := loginTeamChat(t, world, 1)
+ alice.Write(buddyRequest(2, "\x01"))
+ expectBuddyName(t, alice, 2, "Bob")
+ expectBuddy(t, alice, 2, 0, "\x01")
+ world.mutex.Lock()
+ world.clients[1].ready = false
+ data := world.characters[1].editor()
+ world.mutex.Unlock()
+ data.Level = 2
+ contents, err := yaml.Marshal(data)
+ if err != nil {
+ t.Fatal(err)
+ }
+ request := httptest.NewRequest("POST", "/control/users/1", strings.NewReader(url.Values{"data": {string(contents)}}.Encode()))
+ request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ request.SetPathValue("character", "1")
+ response := httptest.NewRecorder()
+
+ world.editUser(response, request)
+ restored := newTestInventoryServer(t)
+
+ if response.Code != http.StatusSeeOther || world.characters[1].level != 2 || world.characters[1].buddies[2] != "\x01" || restored.characters[1].buddies[2] != "\x01" {
+ t.Fatal("control edit changed the buddy list", response.Code, response.Body.String())
+ }
+ expectChatPing(t, alice)
+}
+
+func TestBuddyInterruptedAcknowledgmentRestoresCommittedEntry(t *testing.T) {
+ world := buddyTestWorld(t)
+ peer, done := startChatTest(t, world, 1)
+ peer.Write(chatTestAuth(1))
+ for range 3 {
+ readChatPacket(peer)
+ }
+
+ peer.Write(buddyRequest(2, "\x01"))
+ expectBuddyName(t, peer, 2, "Bob")
+ peer.Close()
+ <-done
+ restored := newTestInventoryServer(t)
+ restored.chats = make(map[uint32]*chatClient)
+ restored.clients[1] = &worldClient{id: 1}
+ reconnected := loginTeamChat(t, restored, 1)
+
+ expectBuddyName(t, reconnected, 2, "Bob")
+ expectBuddy(t, reconnected, 2, 0, "\x01")
+ if restored.characters[1].buddies[2] != "\x01" {
+ t.Fatal("interrupted acknowledgment lost the committed buddy")
+ }
+}
+
+func TestBuddyWriteFailuresPublishNoSuccessOrMemoryChange(t *testing.T) {
+ for _, operation := range []string{"INSERT", "UPDATE", "DELETE"} {
+ for _, failure := range []string{"write", "ignored", "commit"} {
+ t.Run(operation+"/"+failure, func(t *testing.T) {
+ world := buddyTestWorld(t)
+ peer, done := startChatTest(t, world, 1)
+ peer.Write(chatTestAuth(1))
+ for range 3 {
+ readChatPacket(peer)
+ }
+ before := map[uint32]string{}
+ if operation != "INSERT" {
+ peer.Write(buddyRequest(2, "\x00"))
+ expectBuddyName(t, peer, 2, "Bob")
+ expectBuddy(t, peer, 2, 0, "\x00")
+ before[2] = "\x00"
+ }
+ query := "CREATE TRIGGER fail_buddy BEFORE " + operation + " ON buddies BEGIN SELECT RAISE(FAIL, 'buddy write failed'); END"
+ if failure == "ignored" {
+ query = "CREATE TRIGGER fail_buddy BEFORE " + operation + " ON buddies BEGIN SELECT RAISE(IGNORE); END"
+ } else if failure == "commit" {
+ query = "CREATE TABLE pending_buddy (player_id INTEGER REFERENCES players(id) DEFERRABLE INITIALLY DEFERRED); CREATE TRIGGER fail_buddy AFTER " + operation + " ON buddies BEGIN INSERT INTO pending_buddy VALUES (999999); END"
+ }
+ if _, err := world.db.Exec(query); err != nil {
+ t.Fatal(err)
+ }
+
+ packet := buddyRequest(2, "\x01")
+ if operation == "DELETE" {
+ packet = chatPacket(41, []byte{0, 0, 0, 2})
+ }
+ peer.Write(packet)
+ _, _, readErr := readChatPacket(peer)
+ err := <-done
+ restored := newTestInventoryServer(t)
+
+ if err == nil || readErr != io.EOF || len(world.characters[1].buddies) != len(before) || len(restored.characters[1].buddies) != len(before) ||
+ world.characters[1].buddies[2] != before[2] || restored.characters[1].buddies[2] != before[2] {
+ t.Fatal("failed buddy transaction published state", err, readErr, restored.characters[1].buddies)
+ }
+ })
+ }
+ }
+}
diff --git a/server/chat.go b/server/chat.go
@@ -97,6 +97,11 @@ func (server *server) initializeChat(client *chatClient, id uint32) error {
previous.stream.replaced = true
previous.stream.mutex.Unlock()
}
+ buddies := server.buddyList_locked(character)
+ var presence map[*chatClient][]byte
+ if previous == nil {
+ presence = server.buddyPresence_locked(id, 1)
+ }
server.mutex.Unlock()
history, err := server.chatHistory_locked(id)
server.chatLogMutex.Unlock()
@@ -118,21 +123,35 @@ func (server *server) initializeChat(client *chatClient, id uint32) error {
if client.teamID != 0 {
initialization = append(initialization, teamChatJoinPacket(client.teamID)...)
}
+ initialization = append(initialization, buddies...)
for _, entry := range history {
initialization = append(initialization, entry.packet()...)
}
- return client.send_locked(initialization)
+ if err := client.send_locked(initialization); err != nil {
+ return err
+ }
+ for target, packet := range presence {
+ target.send(packet)
+ }
+ return nil
}
func (server *server) serveChatClient(client *chatClient) error {
client.startWriter(client.conn)
defer client.finishWriter()
defer func() {
+ server.updateMutex.Lock()
+ defer server.updateMutex.Unlock()
server.mutex.Lock()
+ var presence map[*chatClient][]byte
if server.chats[client.id] == client {
delete(server.chats, client.id)
+ presence = server.buddyPresence_locked(client.id, 0)
}
server.mutex.Unlock()
+ for target, packet := range presence {
+ target.send(packet)
+ }
}()
// The game responds to the seed with its account and selected character.
@@ -209,8 +228,12 @@ func (server *server) serveChatClient(client *chatClient) error {
if err := client.send(chatPacket(kind, body)); err != nil {
return err
}
- case 40, 41, 42, 64, 66, 110, 120:
- // Buddy, channel preference and account commands do not change delivery.
+ case 40, 41, 120:
+ if err := server.handleChatBuddy(client, kind, body); err != nil {
+ return err
+ }
+ case 42, 64, 66, 110:
+ // Channel preferences and other account commands are not implemented.
default:
return fmt.Errorf("unsupported chat packet %d", kind)
}
diff --git a/server/control.go b/server/control.go
@@ -312,6 +312,7 @@ func (server *server) prepareUser_locked(character, updated *character) {
updated.specialAttackLocks = character.specialAttackLocks
updated.activeNanos = character.activeNanos
updated.team = character.team
+ updated.buddies = character.buddies
// Reconnection cancels a pending cast; preserve its refund unless nano was edited.
if updated.nano == character.nano {
updated.nano = min(character.maximumNano(), character.nano+character.nanoReserved)
diff --git a/server/main.go b/server/main.go
@@ -276,8 +276,12 @@ func (server *server) serveWorldClient(client *worldClient) error {
log.Printf("Saving nano durations: %v", err)
}
delete(server.clients, character.id)
+ chat := server.chats[character.id]
playfield := character.playfield
server.mutex.Unlock()
+ if chat != nil {
+ chat.disconnect(chat.conn)
+ }
server.sendCombatUpdates(updates)
server.broadcast(playfield, character.id, n3Packet(0x36510078, 50000, character.id, nil))
}()
diff --git a/server/state.go b/server/state.go
@@ -27,6 +27,7 @@ type character struct {
corpse *npcCorpse
combatProfile *gamedata.NPCCombatProfile
team *playerTeam
+ buddies map[uint32]string
health uint32
nano uint32
nanoReserved uint32
diff --git a/server/users.go b/server/users.go
@@ -129,6 +129,9 @@ func (server *server) loadUsers() error {
if err := server.loadPlayers(); err != nil {
return err
}
+ if err := server.loadBuddies(); err != nil {
+ return err
+ }
if err := server.loadActiveNanos(); err != nil {
return err
}
diff --git a/server/world.sql b/server/world.sql
@@ -131,6 +131,13 @@ CREATE TABLE IF NOT EXISTS treatment_locks (
locked_until DATETIME NOT NULL,
PRIMARY KEY (player_id, patient_id)
);
+CREATE TABLE IF NOT EXISTS buddies (
+ player_id INTEGER NOT NULL REFERENCES players(id) ON DELETE CASCADE,
+ buddy_id INTEGER NOT NULL REFERENCES players(id) ON DELETE CASCADE,
+ metadata BLOB NOT NULL,
+ PRIMARY KEY (player_id, buddy_id),
+ CHECK (player_id != buddy_id)
+);
CREATE TABLE IF NOT EXISTS special_attack_locks (
player_id INTEGER NOT NULL REFERENCES players(id) ON DELETE CASCADE,
skill INTEGER NOT NULL,