aorecomp

Anarchy Online classic in the browser

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


commit b84d3ba8bfda582406cd7c4b13d9a5cb9fba5c05
parent 5ecf67df1a3b137b05e661d7a646ed516da1e749
Author: anon <anon@example.com>
Date:   Sat, 24 Oct 2026 00:36:05 +0000

Deliver private team chat through native channels

Diffstat:
MTODO.md | 12+++++++++++-
Adocs/team-chat.md | 97+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mdocs/teams.md | 7++++---
Mserver/chat.go | 170+++++++++++++++++++++++++++++++++++++++++++++++++------------------------------
Aserver/team_chat.go | 34++++++++++++++++++++++++++++++++++
Aserver/team_chat_test.go | 443+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/teams.go | 6++++++
7 files changed, 700 insertions(+), 69 deletions(-)

diff --git a/TODO.md b/TODO.md @@ -507,8 +507,11 @@ client rendering fixes and checks are in [nano damage](docs/nano-damage.md). expected shares once and excludes ineligible members. - [ ] Apply one team loot policy. Check: a known two-player loot sequence follows that policy while unrelated players remain excluded. -- [ ] Deliver private team chat. Check: only current members receive it across +- [x] Deliver private team chat. Check: only current members receive it across zones; joining, leaving, disconnect and restart update channel access. + Native type2 channels follow committed membership; forged/stale IDs are + excluded, and per-owner history remains private. Protocol and verification: + [Team chat](docs/team-chat.md). Native consent, roster order, persistent membership, departure and the remaining policy limits are documented in [teams](docs/teams.md). Three connected WASM @@ -612,6 +615,9 @@ and unresolved indoor lifecycle are explicit in [flight](docs/vehicles.md#yalmah reconnect and the appropriate online-status updates reach the owner. - [ ] 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 + listen/mute/log controls and rate limits follow period evidence across + reconnect; Team announcement flags/blob policy is explicitly verified. - [ ] Create one organization. Check: its name, identity and founder membership survive restart. - [ ] Invite an organization member. Check: accepting a valid invitation creates @@ -809,6 +815,10 @@ and server restarts. Turn every reproduced bug into a focused regression test. RightPress becoming RightHold before binding dispatch at a one-second frame delta. Measure live timing and establish the intended slow-frame behavior before changing the adapter. Evidence: `local/team-leadership-smoke/menu-audit.md`. + The Team chat run also reproduced the missing popup with hardware OpenGL + on the GPU, including a single remaining WASM page; hover mode25 was + present. Closing extra pages did not resolve this occurrence. Live timing + remains unmeasured: `local/team-chat-research/menu-input-state.json`. - [x] Prevent browser wheel camera gestures from activating native GUI items. Check: wheel/trackpad input over inventory cannot equip or use the hovered item; world-camera gestures still work. A WASM armor test reproduced a wheel diff --git a/docs/team-chat.md b/docs/team-chat.md @@ -0,0 +1,97 @@ +# Private team chat + +Accepted team members receive a native Team channel over the separate chat +connection. Messages reach connected teammates across playfields, including +members who are dead, distant or still loading. Invitations do not grant access. +A voluntary departure, kick or dissolution removes the affected channel; a +leadership transfer keeps it. Authentication restores the channel for retained +accepted membership after reconnect or server restart. + +Use `/g team message` for one message, or `/ch team` to select Team before typing +ordinary text. Ctrl+7 opens the original channel window. In this client `/team` +is the world loot/help command; no `/t` chat alias was established by the audit. +Removing a selected Team channel makes the native client select Vicinity. + +## Original client contract + +Original DDR packet60 announces a group using `GSID`: five-byte group identity, +BE16-length name, BE32 flags, and BE16-length blob. Packet61 removes a group +using `G`. Client packet65 uses `GSD`; server packet65 uses `GISD`, inserting the +authenticated sender's character ID before the text. Name packets20 precede +message delivery. Group type2 selects native Team colors and sound behavior. +The numeric group ID is opaque to the client; this server allocates it from +the durable world team ID. The announced name is `Team`, flags are zero and the +announcement blob is empty. Original server ID allocation and complete Team +flag/blob policy remain unverified. + +Shipped 14.9.1 `tips/OnSelectPlayer.txt` and `tips/InvitedToATeam.txt` explicitly +establish private, location-independent Team chat. `help/Chatting With Others.txt` +and `help/ChatHelp.txt` establish the channel commands. These are target-version +resources, rather than later manuals. + +Static evidence comes from original DDR SHA-256 +`3c937161de8f690351c3c08e158431417cee9ced77a41b677e7123b61a8c9883`. +REA records include outbound packet65 producer1009d240 +`ev_930c84e04acec31bc006bf9108f7e68976f684c31bc8c70eb6cef37ef9dbc9c1`, +group decoder100a6300 +`ev_83d52ecdc7b8c8d6f4f2527f3892c5e889c30e6336d1a841ae1a313020acca2b`, +Team discriminator10051720 +`ev_8da6617a1ee611927839ea27aa93f2452e2a3f60a2fa82ad781889dae65b41f6` +and join/part dispatcher10007300 +`ev_30d81dee9e01261c5a7140bf5e64d21845f2e0337097bac9c6e3b0fcff2df6b7`. +The full bundle, instruction audits, PE checks and limitations are retained in +`local/team-chat-research/`. These static queries do not claim observed original +server execution. + +## Authorization and ordering + +The server checks current authenticated chat/world association and accepted +membership for every Team send. A fabricated or departed Team ID produces no +delivery or history and leaves the connection usable; malformed packet bodies +close the connection. This harmless handling of stale channel requests is a +reconstruction policy, not an original denial-message claim. + +The existing update mutex serializes roster commits, channel announcements, +chat initialization, recipient selection, history and output queueing. A message +can precede a departure or be excluded by it; it cannot reach that former member +after the channel-part packet. Significant roster changes commit before channel +success is published. Socket writers retain their existing bounded queues; +network writes do not hold the shared world mutex. + +Scrollback uses the existing per-owner history. Only the sender and selected +connected recipients receive copies, committed together. New members and offline +members do not inherit messages they never received. The existing two-minute +browser transport grace keeps its game/chat connection alive and queues output; +closing a tab briefly is therefore not a completed session disconnect. A former +member can retain their own earlier history. History failure preserves the +existing best-effort chat delivery behavior. History replay, disconnect retention duration, flood +policy, preference enforcement and historical Team flags remain independent +policy questions; this change does not establish their original rules. + +## Verification + +Protocol tests drive authenticated chat connections and public team actions. +They check accepted-only announcements, decline and SQL failure, cross-zone +privacy, exact native join/part/message fields, Windows-1252 text, malformed +messages, forged/stale IDs, leadership transfer, kick, dissolution, new team IDs, +restart history and no inherited history for new/offline members. Concurrent +message/departure tests check packet order against the received history copies. +Additional eligibility tests cover dead, distant, loading and offline members. + +The full Go suite passed in 299 seconds. All chat/team tests passed twice under +the race detector in 144 seconds; the completed Team-chat cases passed twice +under the race detector in 117 seconds. Logs are retained alongside the evidence. + +The native member popup intermittently failed to open during the kick attempt, +including with one hardware-rendered page. Hover mode25 was present, but live +frame timing was not measured. This run therefore claims automated kick +verification only; the existing native-input follow-up retains that limitation. +No adapter change was inferred from a failed UI action. Faster scripted typing +also lost the first slash after load; separated native key actions supplied the +successful command checks, and failed vicinity attempts are excluded from the +private-delivery assertions. + +`local/team-chat-research/verification.json` records the native/wire/privacy +checks and item conservation. The test roster was dissolved, original profiles +restored and owned browser contexts closed. The shared LAN preview remains on +HTTPS 8443. diff --git a/docs/teams.md b/docs/teams.md @@ -3,8 +3,9 @@ Recruit, Yes, No and Leave now use the original 14.9.1 team controls. Accepted rosters and their leader persist atomically in SQLite before membership is published. Each player belongs to at most one team, with at most six members. -This implements formation, leadership transfer and member removal; chat, -rewards, loot policy and resource replication are separate work. +This implements formation, leadership transfer and member removal. Private +[Team chat](team-chat.md) and [resource replication](team-resources.md) are also +implemented; rewards and loot policy remain separate work. ## Original client contract @@ -187,5 +188,5 @@ level updates, but original progression thresholds, penalties and bonuses are unverified. A later official manual describes time-based growth, but does not establish a 14.9.1 timer. [Remote HP/nano updates](team-resources.md) now use the native resource packet with combat ordering and per-observer modifier accounting. -Team-level progression, chat, XP sharing, loot rotation and disconnect expiry +Team-level progression, XP sharing, loot rotation and disconnect expiry remain separate open work. diff --git a/server/chat.go b/server/chat.go @@ -15,6 +15,7 @@ type chatClient struct { conn net.Conn stream *browserStream id uint32 + teamID uint32 // Announced channel membership; protected by server.mutex. } func chatPacket(kind uint16, body []byte) []byte { @@ -69,6 +70,10 @@ func chatNamePacket(id uint32, name string) []byte { } func (server *server) initializeChat(client *chatClient, id uint32) error { + // Serialize channel announcements with roster changes and private messages. + server.updateMutex.Lock() + defer server.updateMutex.Unlock() + // Restore scrollback before live messages can write to the new connection. client.mutex.Lock() defer client.mutex.Unlock() @@ -83,6 +88,9 @@ func (server *server) initializeChat(client *chatClient, id uint32) error { name := character.name previous := server.chats[id] client.id = id + if character.team != nil { + client.teamID = character.team.id + } server.chats[id] = client if previous != nil && previous.stream != nil { previous.stream.mutex.Lock() @@ -107,6 +115,9 @@ func (server *server) initializeChat(client *chatClient, id uint32) error { channel = append(channel, 0, 0) initialization := append(chatPacket(5, nil), chatNamePacket(id, name)...) initialization = append(initialization, chatPacket(60, channel)...) + if client.teamID != 0 { + initialization = append(initialization, teamChatJoinPacket(client.teamID)...) + } for _, entry := range history { initialization = append(initialization, entry.packet()...) } @@ -191,71 +202,8 @@ func (server *server) serveChatClient(client *chatClient) error { return err } case 30, 65: - var recipient uint32 - if kind == 30 { - if len(body) < 4 { - return fmt.Errorf("invalid chat tell") - } - recipient = binary.BigEndian.Uint32(body[:4]) - body = body[4:] - } else { - if len(body) < 5 || body[0] != 0x87 || binary.BigEndian.Uint32(body[1:5]) != 1 { - return fmt.Errorf("invalid chat channel") - } - body = body[5:] - } - message, ok := readChatString(&body) - _, 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 == "" { - continue - } - - server.chatLogMutex.Lock() - server.mutex.Lock() - name := server.characters[id].name - var recipientName string - var recipients []*chatClient - if kind == 30 { - if target := server.chats[recipient]; target != nil && server.clients[recipient] != nil { - recipients = append(recipients, target) - recipientName = server.characters[recipient].name - } - } else { - for otherID, target := range server.chats { - if server.clients[otherID] != nil { - recipients = append(recipients, target) - } - } - } - server.mutex.Unlock() - if kind == 30 && len(recipients) == 0 { - server.chatLogMutex.Unlock() - if err := client.send(chatPacket(36, appendChatString(nil, "Player not online."))); err != nil { - return err - } - continue - } - var outgoing []byte - if kind == 65 { - outgoing = binary.BigEndian.AppendUint32([]byte{0x87}, 1) - } - outgoing = binary.BigEndian.AppendUint32(outgoing, id) - outgoing = appendChatString(outgoing, message) - outgoing = appendChatString(outgoing, "") - channel := "tell" - if kind == 65 { - channel = "Global" - } - server.logChat_locked(chatHistoryEntry{Channel: channel, SenderID: id, Sender: name, RecipientID: recipient, Recipient: recipientName, Message: message}, recipients) - server.chatLogMutex.Unlock() - for _, target := range recipients { - if target.send(chatNamePacket(id, name)) == nil { - target.send(chatPacket(kind, outgoing)) - } + if err := server.handleChatMessage(client, kind, body); err != nil { + return err } case 100: if err := client.send(chatPacket(kind, body)); err != nil { @@ -269,6 +217,98 @@ func (server *server) serveChatClient(client *chatClient) error { } } +func (server *server) handleChatMessage(client *chatClient, kind uint16, body []byte) error { + var recipient, groupID uint32 + var groupType byte + if kind == 30 { + if len(body) < 4 { + return fmt.Errorf("invalid chat tell") + } + recipient = binary.BigEndian.Uint32(body[:4]) + body = body[4:] + } else { + if len(body) < 5 || body[0] != 2 && (body[0] != 0x87 || binary.BigEndian.Uint32(body[1:5]) != 1) { + return fmt.Errorf("invalid chat channel") + } + groupType = body[0] + groupID = binary.BigEndian.Uint32(body[1:5]) + body = body[5:] + } + message, ok := readChatString(&body) + _, 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 == "" { + return nil + } + + // Keep membership checks, history and output ordered with roster changes. + server.updateMutex.Lock() + defer server.updateMutex.Unlock() + server.chatLogMutex.Lock() + server.mutex.Lock() + id := client.id + if server.chats[id] != client || server.clients[id] == nil { + server.mutex.Unlock() + server.chatLogMutex.Unlock() + return fmt.Errorf("chat world session ended") + } + player := server.characters[id] + // A queued send from a departed channel is harmless and must not disconnect. + if groupType == 2 && (player.team == nil || player.team.id != groupID || client.teamID != groupID) { + server.mutex.Unlock() + server.chatLogMutex.Unlock() + return nil + } + name := player.name + var recipientName string + var recipients []*chatClient + if kind == 30 { + if target := server.chats[recipient]; target != nil && server.clients[recipient] != nil { + recipients = append(recipients, target) + recipientName = server.characters[recipient].name + } + } else { + for otherID, target := range server.chats { + if server.clients[otherID] != nil && (groupType != 2 || server.characters[otherID].team == player.team) { + recipients = append(recipients, target) + } + } + } + server.mutex.Unlock() + if kind == 30 && len(recipients) == 0 { + server.chatLogMutex.Unlock() + if err := client.send(chatPacket(36, appendChatString(nil, "Player not online."))); err != nil { + return err + } + return nil + } + var outgoing []byte + if kind == 65 { + outgoing = binary.BigEndian.AppendUint32([]byte{groupType}, groupID) + } + outgoing = binary.BigEndian.AppendUint32(outgoing, id) + outgoing = appendChatString(outgoing, message) + outgoing = appendChatString(outgoing, "") + channel := "tell" + if kind == 65 { + channel = "Global" + if groupType == 2 { + channel = "Team" + } + } + server.logChat_locked(chatHistoryEntry{Channel: channel, SenderID: id, Sender: name, RecipientID: recipient, Recipient: recipientName, Message: message}, recipients) + server.chatLogMutex.Unlock() + for _, target := range recipients { + if target.send(chatNamePacket(id, name)) == nil { + target.send(chatPacket(kind, outgoing)) + } + } + return nil +} + 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) { diff --git a/server/team_chat.go b/server/team_chat.go @@ -0,0 +1,34 @@ +package main + +import "encoding/binary" + +func teamChatJoinPacket(id uint32) []byte { + body := binary.BigEndian.AppendUint32([]byte{2}, id) + body = appendChatString(body, "Team") + body = binary.BigEndian.AppendUint32(body, 0) + body = append(body, 0, 0) + return chatPacket(60, body) +} + +func (server *server) teamChatUpdates_locked() map[*chatClient][][]byte { + updates := make(map[*chatClient][][]byte) + for id, client := range server.chats { + teamID := uint32(0) + if server.characters[id].team != nil { + teamID = server.characters[id].team.id + } + if client.teamID == teamID { + continue + } + + // Depart the old group before announcing the newly committed membership. + if client.teamID != 0 { + updates[client] = append(updates[client], chatPacket(61, binary.BigEndian.AppendUint32([]byte{2}, client.teamID))) + } + if teamID != 0 { + updates[client] = append(updates[client], teamChatJoinPacket(teamID)) + } + client.teamID = teamID + } + return updates +} diff --git a/server/team_chat_test.go b/server/team_chat_test.go @@ -0,0 +1,443 @@ +package main + +import ( + "bytes" + "encoding/binary" + "fmt" + "io" + "net" + "strings" + "sync" + "testing" + "time" +) + +func teamChatWorld(t *testing.T) *server { + t.Helper() + world, _ := newTeamWorld(t) + world.chats = make(map[uint32]*chatClient) + return world +} + +func loginTeamChat(t *testing.T, world *server, id uint32) net.Conn { + t.Helper() + peer, done := startChatTest(t, world, id) + peer.SetDeadline(time.Now().Add(30 * time.Second)) + t.Cleanup(func() { peer.Close(); <-done }) + if _, err := peer.Write(chatTestAuth(id)); err != nil { + t.Fatal(err) + } + for _, expected := range []uint16{5, 20, 60} { + kind, _, err := readChatPacket(peer) + if err != nil || kind != expected { + t.Fatalf("team chat login: %d %v", kind, err) + } + } + return peer +} + +func expectTeamChatGroup(t *testing.T, peer net.Conn, kind uint16, id uint32) { + t.Helper() + expected := binary.BigEndian.AppendUint32([]byte{2}, id) + if kind == 60 { + expected = append(expected, 0, 4, 'T', 'e', 'a', 'm', 0, 0, 0, 0, 0, 0) + } + actualKind, body, err := readChatPacket(peer) + if err != nil || actualKind != kind || !bytes.Equal(body, expected) { + t.Fatalf("team channel: kind=%d body=%x expected=%d/%x error=%v", actualKind, body, kind, expected, err) + } +} + +func teamChatRequest(id uint32, message string) []byte { + body := binary.BigEndian.AppendUint32([]byte{2}, id) + return chatPacket(65, appendChatString(appendChatString(body, message), "")) +} + +func expectTeamChatMessage(t *testing.T, peer net.Conn, team, sender uint32, message string) { + t.Helper() + kind, body, err := readChatPacket(peer) + if err != nil || kind != 20 || binary.BigEndian.Uint32(body) != sender { + t.Fatalf("team sender name: %d %x %v", kind, body, err) + } + kind, body, err = readChatPacket(peer) + expected := binary.BigEndian.AppendUint32([]byte{2}, team) + expected = binary.BigEndian.AppendUint32(expected, sender) + expected = appendChatString(appendChatString(expected, message), "") + if err != nil || kind != 65 || !bytes.Equal(body, expected) { + t.Fatalf("team message: %d %x expected=%x error=%v", kind, body, expected, err) + } +} + +func expectChatPing(t *testing.T, peer net.Conn) { + t.Helper() + if _, err := peer.Write(chatPacket(100, []byte{0, 1, 'x'})); err != nil { + t.Fatal(err) + } + kind, body, err := readChatPacket(peer) + if err != nil || kind != 100 || !bytes.Equal(body, []byte{0, 1, 'x'}) { + t.Fatalf("unexpected delivery before ping: %d %x %v", kind, body, err) + } +} + +func TestTeamChatJoinsOnlyAfterAcceptedMembership(t *testing.T) { + world := teamChatWorld(t) + alice := loginTeamChat(t, world, 1) + bob := loginTeamChat(t, world, 2) + outsider := loginTeamChat(t, world, 3) + + world.handleTeamAction(world.clients[1], teamRequest(1, 26, 2, 0)) + expectChatPing(t, alice) + expectChatPing(t, bob) + world.handleTeamAction(world.clients[2], teamRequest(2, 28, 1, 1)) + + team := world.characters[1].team.id + expectTeamChatGroup(t, alice, 60, team) + expectTeamChatGroup(t, bob, 60, team) + expectChatPing(t, outsider) +} + +func TestTeamChatCrossesZonesAndKeepsHistoryPrivate(t *testing.T) { + world := teamChatWorld(t) + formTestTeam(t, world, 1, 2) + formTestTeam(t, world, 3, 4) + team := world.characters[1].team.id + world.characters[2].playfield = 1183 + alice := loginTeamChat(t, world, 1) + bob := loginTeamChat(t, world, 2) + outsider := loginTeamChat(t, world, 3) + expectTeamChatGroup(t, alice, 60, team) + expectTeamChatGroup(t, bob, 60, team) + expectTeamChatGroup(t, outsider, 60, world.characters[3].team.id) + + alice.Write(teamChatRequest(team, "h\xe9 team")) + + expectTeamChatMessage(t, alice, team, 1, "h\xe9 team") + expectTeamChatMessage(t, bob, team, 1, "h\xe9 team") + expectChatPing(t, outsider) + for _, id := range []uint32{1, 2, 3, 4} { + history, err := world.chatHistory_locked(id) + if err != nil { + t.Fatal(err) + } + if id <= 2 { + if len(history) != 1 || history[0].Channel != "Team" || history[0].SenderID != 1 || history[0].Message != "h\u00e9 team" { + t.Fatalf("member %d history: %+v", id, history) + } + } else if len(history) != 0 { + t.Fatalf("team history leaked to %d: %+v", id, history) + } + } +} + +func TestTeamChatRejectsForgedAndDepartedChannelsWithoutDisconnecting(t *testing.T) { + world := teamChatWorld(t) + formTestTeam(t, world, 1, 2) + team := world.characters[1].team.id + alice := loginTeamChat(t, world, 1) + bob := loginTeamChat(t, world, 2) + outsider := loginTeamChat(t, world, 3) + expectTeamChatGroup(t, alice, 60, team) + expectTeamChatGroup(t, bob, 60, team) + + outsider.Write(teamChatRequest(team, "forged")) + expectChatPing(t, outsider) + alice.Write(teamChatRequest(team+1, "wrong team")) + expectChatPing(t, alice) + world.handleTeamAction(world.clients[2], teamRequest(2, 24, 0, 0)) + expectTeamChatGroup(t, alice, 61, team) + expectTeamChatGroup(t, bob, 61, team) + bob.Write(teamChatRequest(team, "late send")) + + expectChatPing(t, bob) + expectChatPing(t, alice) + expectChatPing(t, outsider) + for _, id := range []uint32{1, 2, 3} { + history, err := world.chatHistory_locked(id) + if err != nil || len(history) != 0 { + t.Fatalf("rejected message history for %d: %+v %v", id, history, err) + } + } +} + +func TestTeamChatMalformedMessagesCloseConnection(t *testing.T) { + for _, body := range [][]byte{ + {2, 0, 0, 0}, + {2, 0, 0, 0, 1, 0, 2, 'h', 'i'}, + appendChatString(appendChatString([]byte{2, 0, 0, 0, 1}, "bad\x00text"), ""), + appendChatString(appendChatString([]byte{2, 0, 0, 0, 1}, strings.Repeat("x", 4097)), ""), + } { + t.Run(fmt.Sprintf("length_%d", len(body)), func(t *testing.T) { + world := teamChatWorld(t) + peer := loginTeamChat(t, world, 1) + + peer.Write(chatPacket(65, body)) + _, _, err := readChatPacket(peer) + + if err != io.EOF { + t.Fatalf("malformed team message did not close promptly: %v", err) + } + }) + } +} + +func TestTeamChatRecipientEligibilityFollowsMembershipAndConnection(t *testing.T) { + for _, scenario := range []string{"dead", "loading", "far away", "world offline", "chat offline"} { + t.Run(scenario, func(t *testing.T) { + world := teamChatWorld(t) + formTestTeam(t, world, 1, 2) + team := world.characters[1].team.id + alice := loginTeamChat(t, world, 1) + bob := loginTeamChat(t, world, 2) + expectTeamChatGroup(t, alice, 60, team) + expectTeamChatGroup(t, bob, 60, team) + world.mutex.Lock() + switch scenario { + case "dead": + world.characters[2].health = 0 + case "loading": + world.clients[2].ready = false + world.clients[2].loading = true + case "far away": + world.characters[2].position = [3]float32{10000, 0, 10000} + case "world offline": + delete(world.clients, 2) + case "chat offline": + delete(world.chats, 2) + } + world.mutex.Unlock() + + alice.Write(teamChatRequest(team, scenario)) + expectTeamChatMessage(t, alice, team, 1, scenario) + + if scenario != "world offline" && scenario != "chat offline" { + expectTeamChatMessage(t, bob, team, 1, scenario) + } else { + bob.SetReadDeadline(time.Now().Add(20 * time.Millisecond)) + kind, body, err := readChatPacket(bob) + if timeout, ok := err.(net.Error); !ok || !timeout.Timeout() { + t.Fatalf("offline recipient delivery: %d %x %v", kind, body, err) + } + history, err := world.chatHistory_locked(2) + if err != nil || len(history) != 0 { + t.Fatalf("offline recipient history: %+v %v", history, err) + } + } + }) + } +} + +func TestTeamChatDeclineAndFailedAcceptanceDoNotAnnounceChannel(t *testing.T) { + for _, scenario := range []string{"decline", "failed commit"} { + t.Run(scenario, func(t *testing.T) { + world := teamChatWorld(t) + alice := loginTeamChat(t, world, 1) + bob := loginTeamChat(t, world, 2) + world.handleTeamAction(world.clients[1], teamRequest(1, 26, 2, 0)) + accepted := uint32(0) + if scenario == "failed commit" { + accepted = 1 + failDatabaseWrites(t, world) + } + + err := world.handleTeamAction(world.clients[2], teamRequest(2, 28, 1, accepted)) + + if (err != nil) != (scenario == "failed commit") || world.characters[1].team != nil || world.characters[2].team != nil { + t.Fatalf("uncommitted team membership: %v", err) + } + expectChatPing(t, alice) + expectChatPing(t, bob) + }) + } +} + +func TestTeamChatLeadershipKickAndDissolutionUpdateOnlyAffectedChannels(t *testing.T) { + world := teamChatWorld(t) + formTestTeam(t, world, 1, 2) + formTestTeam(t, world, 1, 3) + team := world.characters[1].team.id + alice := loginTeamChat(t, world, 1) + bob := loginTeamChat(t, world, 2) + carol := loginTeamChat(t, world, 3) + for _, peer := range []net.Conn{alice, bob, carol} { + expectTeamChatGroup(t, peer, 60, team) + } + + world.handleTeamAction(world.clients[1], teamRequest(1, 25, 2, 0)) + for _, peer := range []net.Conn{alice, bob, carol} { + expectChatPing(t, peer) + } + world.handleTeamAction(world.clients[2], teamRequest(2, 22, 3, 0)) + expectTeamChatGroup(t, carol, 61, team) + bob.Write(teamChatRequest(team, "remaining pair")) + expectTeamChatMessage(t, alice, team, 2, "remaining pair") + expectTeamChatMessage(t, bob, team, 2, "remaining pair") + expectChatPing(t, carol) + world.handleTeamAction(world.clients[1], teamRequest(1, 24, 0, 0)) + expectTeamChatGroup(t, alice, 61, team) + expectTeamChatGroup(t, bob, 61, team) + formTestTeam(t, world, 1, 3) + + newTeam := world.characters[1].team.id + if newTeam == team { + t.Fatal("dissolved team channel was reused") + } + expectTeamChatGroup(t, alice, 60, newTeam) + expectTeamChatGroup(t, carol, 60, newTeam) + alice.Write(teamChatRequest(team, "stale old channel")) + expectChatPing(t, alice) + expectChatPing(t, bob) + expectChatPing(t, carol) +} + +func TestTeamChatFailedRosterCommitPreservesChannelAccess(t *testing.T) { + world := teamChatWorld(t) + formTestTeam(t, world, 1, 2) + team := world.characters[1].team.id + alice := loginTeamChat(t, world, 1) + bob := loginTeamChat(t, world, 2) + expectTeamChatGroup(t, alice, 60, team) + expectTeamChatGroup(t, bob, 60, team) + failDatabaseWrites(t, world) + + err := world.handleTeamAction(world.clients[2], teamRequest(2, 24, 0, 0)) + alice.Write(teamChatRequest(team, "still members")) + + if err == nil || world.characters[2].team == nil { + t.Fatalf("failed departure changed membership: %v", err) + } + expectTeamChatMessage(t, alice, team, 1, "still members") + expectTeamChatMessage(t, bob, team, 1, "still members") +} + +func TestTeamChatRestartRestoresMembershipAndOnlyReceivedHistory(t *testing.T) { + world := teamChatWorld(t) + formTestTeam(t, world, 1, 2) + team := world.characters[1].team.id + alice := loginTeamChat(t, world, 1) + bob := loginTeamChat(t, world, 2) + expectTeamChatGroup(t, alice, 60, team) + expectTeamChatGroup(t, bob, 60, team) + alice.Write(teamChatRequest(team, "before restart")) + expectTeamChatMessage(t, alice, team, 1, "before restart") + expectTeamChatMessage(t, bob, team, 1, "before restart") + + restarted := newTestInventoryServer(t) + restarted.chats = make(map[uint32]*chatClient) + restarted.clients[2] = &worldClient{id: 2, ready: true} + reconnected := loginTeamChat(t, restarted, 2) + + expectTeamChatGroup(t, reconnected, 60, team) + kind, body, err := readChatPacket(reconnected) + if err != nil || kind != 36 || !bytes.Contains(body, []byte("[Team] Member: before restart")) { + t.Fatalf("private restored history: %d %s %v", kind, body, err) + } + expectChatPing(t, reconnected) + history, err := restarted.chatHistory_locked(3) + if err != nil || len(history) != 0 { + t.Fatalf("history reached outsider on restart: %+v %v", history, err) + } +} + +func TestTeamChatNewMemberDoesNotInheritEarlierHistory(t *testing.T) { + world := teamChatWorld(t) + formTestTeam(t, world, 1, 2) + team := world.characters[1].team.id + alice := loginTeamChat(t, world, 1) + expectTeamChatGroup(t, alice, 60, team) + alice.Write(teamChatRequest(team, "before recruitment")) + expectTeamChatMessage(t, alice, team, 1, "before recruitment") + + formTestTeam(t, world, 1, 3) + carol := loginTeamChat(t, world, 3) + + expectTeamChatGroup(t, carol, 60, team) + expectChatPing(t, carol) + for _, id := range []uint32{2, 3} { + history, err := world.chatHistory_locked(id) + if err != nil || len(history) != 0 { + t.Fatalf("unreceived history reached %d: %+v %v", id, history, err) + } + } +} + +func TestTeamChatConcurrentDepartureCannotReceiveAfterPart(t *testing.T) { + world := teamChatWorld(t) + formTestTeam(t, world, 1, 2) + formTestTeam(t, world, 1, 3) + team := world.characters[1].team.id + alice := loginTeamChat(t, world, 1) + bob := loginTeamChat(t, world, 2) + expectTeamChatGroup(t, alice, 60, team) + expectTeamChatGroup(t, bob, 60, team) + for iteration := range 12 { + if iteration != 0 { + formTestTeam(t, world, 1, 2) + expectTeamChatGroup(t, bob, 60, team) + } + message := fmt.Sprintf("concurrent %d", iteration) + start := make(chan struct{}) + var operations sync.WaitGroup + operations.Add(2) + errors := make(chan error, 2) + + go func() { + defer operations.Done() + <-start + _, err := alice.Write(teamChatRequest(team, message)) + errors <- err + }() + go func() { + defer operations.Done() + <-start + errors <- world.handleTeamAction(world.clients[2], teamRequest(2, 24, 0, 0)) + }() + close(start) + operations.Wait() + expectTeamChatMessage(t, alice, team, 1, message) + bob.Write(chatPacket(100, nil)) + + for range 2 { + if err := <-errors; err != nil { + t.Fatal(err) + } + } + parted, delivered := false, false + for { + kind, body, err := readChatPacket(bob) + if err != nil { + t.Fatal(err) + } + if kind == 100 { + break + } + switch kind { + case 20, 65: + if parted { + t.Fatal("private delivery followed channel departure") + } + delivered = kind == 65 + case 61: + if parted || !bytes.Equal(body, binary.BigEndian.AppendUint32([]byte{2}, team)) { + t.Fatalf("unexpected departure: %x", body) + } + parted = true + default: + t.Fatalf("unexpected packet: %d %x", kind, body) + } + } + if !parted { + t.Fatal("missing team departure") + } + history, err := world.chatHistory_locked(2) + if err != nil { + t.Fatal(err) + } + found := false + for _, entry := range history { + found = found || entry.Message == message + } + if found != delivered { + t.Fatal("history does not match serialized private delivery") + } + } +} diff --git a/server/teams.go b/server/teams.go @@ -182,8 +182,14 @@ func (server *server) handleTeamAction(client *worldClient, body []byte) error { server.mutex.Lock() updates := make(map[*worldClient][][]byte) defer func() { + chatUpdates := server.teamChatUpdates_locked() server.mutex.Unlock() server.sendCombatUpdates(updates) + for client, packets := range chatUpdates { + for _, packet := range packets { + client.send(packet) + } + } }() player := server.characters[client.id] if server.clients[client.id] != client || !client.ready || client.loading ||