aorecomp

Anarchy Online classic in the browser

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


server/chat.go (13331B)


      1 package main
      2 
      3 import (
      4 	"crypto/rand"
      5 	"encoding/binary"
      6 	"fmt"
      7 	"io"
      8 	"log"
      9 	"net"
     10 	"slices"
     11 	"strconv"
     12 	"strings"
     13 )
     14 
     15 type chatClient struct {
     16 	clientOutput
     17 	conn             net.Conn
     18 	stream           *browserStream
     19 	browserTokenHash string
     20 	id               uint32
     21 	teamID           uint32 // Announced channel membership; owned by the chat goroutine.
     22 	statusURL        string
     23 }
     24 
     25 func chatPacket(kind uint16, body []byte) []byte {
     26 	packet := binary.BigEndian.AppendUint16(nil, kind)
     27 	packet = binary.BigEndian.AppendUint16(packet, uint16(len(body)))
     28 	return append(packet, body...)
     29 }
     30 
     31 func appendChatString(body []byte, value string) []byte {
     32 	body = binary.BigEndian.AppendUint16(body, uint16(len(value)))
     33 	return append(body, value...)
     34 }
     35 
     36 func readChatString(body *[]byte) (string, bool) {
     37 	if len(*body) < 2 {
     38 		return "", false
     39 	}
     40 	length := int(binary.BigEndian.Uint16(*body))
     41 	if length > len(*body)-2 {
     42 		return "", false
     43 	}
     44 	value := string((*body)[2 : 2+length])
     45 	*body = (*body)[2+length:]
     46 	return value, true
     47 }
     48 
     49 func readChatPacket(reader io.Reader) (uint16, []byte, error) {
     50 	var header [4]byte
     51 	if _, err := io.ReadFull(reader, header[:]); err != nil {
     52 		return 0, nil, err
     53 	}
     54 	body := make([]byte, binary.BigEndian.Uint16(header[2:]))
     55 	_, err := io.ReadFull(reader, body)
     56 	return binary.BigEndian.Uint16(header[:]), body, err
     57 }
     58 
     59 func (client *chatClient) send(packet []byte) error {
     60 	client.mutex.Lock()
     61 	defer client.mutex.Unlock()
     62 	return client.send_locked(packet)
     63 }
     64 
     65 func (client *chatClient) send_locked(packet []byte) error {
     66 	return client.enqueue_locked(client.conn, packet)
     67 }
     68 
     69 func chatNamePacket(id uint32, name string) []byte {
     70 	return chatPacket(20, appendChatString(binary.BigEndian.AppendUint32(nil, id), name))
     71 }
     72 
     73 func (server *chatState) initializeChat(client *chatClient, id uint32) error {
     74 	character := server.people[id]
     75 	if character == nil || !character.online || character.credential != "" && client.id == 0 {
     76 		return fmt.Errorf("chat requires an authenticated world character")
     77 	}
     78 	if client.browserTokenHash != "" && client.browserTokenHash != character.credential {
     79 		return fmt.Errorf("browser credential was replaced")
     80 	}
     81 	if err := checkGameBan(server.db, id, client.conn.RemoteAddr().String()); err != nil {
     82 		return err
     83 	}
     84 	name := character.name
     85 	previous := server.clients[id]
     86 	client.id = id
     87 	if character.team != 0 {
     88 		client.teamID = character.team
     89 	}
     90 	server.clients[id] = client
     91 	if previous != nil && previous.stream != nil {
     92 		previous.stream.mutex.Lock()
     93 		previous.stream.stopCode = browserSessionReplaced
     94 		previous.stream.mutex.Unlock()
     95 	}
     96 	buddies := server.buddyList(character)
     97 	var presence map[*chatClient][]byte
     98 	if previous == nil {
     99 		presence = server.buddyPresence(id, 1)
    100 	}
    101 	history, err := readChatHistory(server.db, id)
    102 	if previous != nil {
    103 		previous.disconnect(previous.conn)
    104 	}
    105 	if err != nil {
    106 		log.Printf("Restore chat history for character %d: %v", id, err)
    107 	}
    108 	log.Printf("Chat connected: character %d from %s", id, client.conn.RemoteAddr())
    109 
    110 	// Announce the player's name and public channel before displaying history.
    111 	channel := binary.BigEndian.AppendUint32([]byte{0x87}, 1)
    112 	channel = appendChatString(channel, "Global")
    113 	channel = binary.BigEndian.AppendUint32(channel, 0)
    114 	channel = append(channel, 0, 0)
    115 	initialization := append(chatPacket(5, nil), chatNamePacket(id, name)...)
    116 	initialization = append(initialization, chatPacket(60, channel)...)
    117 	if client.teamID != 0 {
    118 		initialization = append(initialization, teamChatJoinPacket(client.teamID)...)
    119 	}
    120 	initialization = append(initialization, buddies...)
    121 	for _, entry := range history {
    122 		initialization = append(initialization, entry.packet()...)
    123 	}
    124 	if client.statusURL != "" {
    125 		online := 0
    126 		for _, person := range server.people {
    127 			if person.online {
    128 				online++
    129 			}
    130 		}
    131 		players := "players"
    132 		if online == 1 {
    133 			players = "player"
    134 		}
    135 		message := fmt.Sprintf("[Server] %d %s online. Find other players at %s", online, players, client.statusURL)
    136 		initialization = append(initialization, chatPacket(36, appendChatString(nil, message))...)
    137 	}
    138 	if err := client.send(initialization); err != nil {
    139 		return err
    140 	}
    141 	for _, message := range character.pending {
    142 		client.send(chatPacket(36, appendChatString(nil, message)))
    143 	}
    144 	character.pending = nil
    145 	for target, packet := range presence {
    146 		target.send(packet)
    147 	}
    148 	return nil
    149 }
    150 
    151 func (server *server) serveChatClient(client *chatClient) error {
    152 	// Browser transports supply their public origin; native clients use HTTP.
    153 	if client.statusURL == "" {
    154 		client.statusURL = strings.TrimSuffix(server.baseURL, "/") + "/status"
    155 		if address, ok := client.conn.LocalAddr().(*net.TCPAddr); ok {
    156 			client.statusURL = "http://" + net.JoinHostPort(address.IP.String(), strconv.Itoa(server.httpPort)) + client.statusURL
    157 		}
    158 	}
    159 	finish, accepted := server.tasks.enter(func() { client.conn.Close() })
    160 	if !accepted {
    161 		return net.ErrClosed
    162 	}
    163 	defer finish()
    164 
    165 	return server.chatService.serveClient(client)
    166 }
    167 
    168 func (runtime *chatRuntime) serveClient(client *chatClient) error {
    169 	client.startWriter(client.conn)
    170 	defer client.finishWriter()
    171 	defer runtime.call(chatLeave{client})
    172 
    173 	// The game responds to the seed with its account and selected character.
    174 	seed := make([]byte, 32)
    175 	if _, err := rand.Read(seed); err != nil {
    176 		return err
    177 	}
    178 	for index := range seed {
    179 		if seed[index] == 0 {
    180 			seed[index] = 1
    181 		}
    182 	}
    183 	if err := client.send(chatPacket(0, appendChatString(nil, string(seed)))); err != nil {
    184 		return err
    185 	}
    186 	kind, body, err := readChatPacket(client.conn)
    187 	if err != nil {
    188 		return err
    189 	}
    190 	if kind != 0 || len(body) < 8 {
    191 		return fmt.Errorf("invalid chat authentication")
    192 	}
    193 	id := binary.BigEndian.Uint32(body[4:8])
    194 	body = body[8:]
    195 	_, usernameOK := readChatString(&body)
    196 	_, keyOK := readChatString(&body)
    197 	if !usernameOK || !keyOK || len(body) != 0 || client.id != 0 && client.id != id {
    198 		return fmt.Errorf("invalid chat character credentials")
    199 	}
    200 
    201 	if err := runtime.call(chatJoin{client, id}); err != nil {
    202 		return err
    203 	}
    204 
    205 	for {
    206 		kind, body, err := readChatPacket(client.conn)
    207 		if err == io.EOF {
    208 			return nil
    209 		}
    210 		if err != nil {
    211 			return err
    212 		}
    213 		if err := runtime.call(chatInput{client, kind, body}); err != nil {
    214 			return err
    215 		}
    216 	}
    217 }
    218 
    219 func (server *chatState) handlePacket(client *chatClient, kind uint16, body []byte) error {
    220 	person := server.people[client.id]
    221 	if server.clients[client.id] != client || !person.online || client.browserTokenHash != "" && client.browserTokenHash != person.credential {
    222 		return fmt.Errorf("chat world session ended")
    223 	}
    224 	switch kind {
    225 	case 21:
    226 		requested, ok := readChatString(&body)
    227 		requested = strings.TrimSuffix(requested, "\x00")
    228 		if !ok || len(body) != 0 || len(requested) == 0 || len(requested) > 4096 || strings.ContainsRune(requested, 0) {
    229 			return fmt.Errorf("invalid chat name lookup")
    230 		}
    231 		found := uint32(0xffffffff)
    232 		for _, character := range server.people {
    233 			if strings.EqualFold(character.name, requested) {
    234 				found = character.id
    235 				requested = character.name
    236 				break
    237 			}
    238 		}
    239 		if err := client.send(chatPacket(21, appendChatString(binary.BigEndian.AppendUint32(nil, found), requested))); err != nil {
    240 			return err
    241 		}
    242 	case 30, 65:
    243 		if err := server.handleChatMessage(client, kind, body); err != nil {
    244 			return err
    245 		}
    246 	case 100:
    247 		if err := client.send(chatPacket(kind, body)); err != nil {
    248 			return err
    249 		}
    250 	case 40, 41, 120:
    251 		if err := server.handleChatBuddy(client, kind, body); err != nil {
    252 			return err
    253 		}
    254 	case 42, 64, 66, 110:
    255 		// Channel preferences and other account commands are not implemented.
    256 	default:
    257 		return fmt.Errorf("unsupported chat packet %d", kind)
    258 	}
    259 	return nil
    260 }
    261 
    262 func (server *chatState) handleChatMessage(client *chatClient, kind uint16, body []byte) error {
    263 	// Public-group delivery adds a sender ID to the client's counted body.
    264 	if kind == 65 && len(body) > 65531 {
    265 		return fmt.Errorf("chat message exceeds delivery frame")
    266 	}
    267 	var recipient, groupID uint32
    268 	var groupType byte
    269 	if kind == 30 {
    270 		if len(body) < 4 {
    271 			return fmt.Errorf("invalid chat tell")
    272 		}
    273 		recipient = binary.BigEndian.Uint32(body[:4])
    274 		body = body[4:]
    275 	} else {
    276 		if len(body) < 5 || body[0] != 2 && (body[0] != 0x87 || binary.BigEndian.Uint32(body[1:5]) != 1) {
    277 			return fmt.Errorf("invalid chat channel")
    278 		}
    279 		groupType = body[0]
    280 		groupID = binary.BigEndian.Uint32(body[1:5])
    281 		body = body[5:]
    282 	}
    283 	message, ok := readChatString(&body)
    284 	blob, blobOK := readChatString(&body)
    285 	message = strings.TrimSuffix(message, "\x00")
    286 	if !ok || !blobOK || len(body) != 0 || len(message) > 4096 || strings.ContainsRune(message, 0) {
    287 		return fmt.Errorf("invalid chat message")
    288 	}
    289 	metadata := []byte(blob)
    290 	if kind == 30 {
    291 		if len(metadata) == 0 || metadata[0] != 0 {
    292 			return fmt.Errorf("invalid chat tell mode")
    293 		}
    294 		metadata = metadata[1:]
    295 	}
    296 	if !validChatMetadata(metadata) {
    297 		return fmt.Errorf("invalid chat metadata")
    298 	}
    299 	if message == "" && len(metadata) == 0 {
    300 		return nil
    301 	}
    302 
    303 	// Keep membership checks, history and output ordered with roster changes.
    304 	id := client.id
    305 	if server.clients[id] != client || !server.people[id].online {
    306 		return fmt.Errorf("chat world session ended")
    307 	}
    308 	player := server.people[id]
    309 	// A queued send from a departed channel is harmless and must not disconnect.
    310 	if groupType == 2 && (player.team == 0 || player.team != groupID || client.teamID != groupID) {
    311 		return nil
    312 	}
    313 	name := player.name
    314 	var recipientName string
    315 	var recipients []*chatClient
    316 	if kind == 30 {
    317 		if target := server.clients[recipient]; target != nil && server.people[recipient].online {
    318 			recipients = append(recipients, target)
    319 			recipientName = server.people[recipient].name
    320 		}
    321 	} else {
    322 		for otherID, target := range server.clients {
    323 			if server.people[otherID].online && (groupType != 2 || server.people[otherID].team == player.team) {
    324 				recipients = append(recipients, target)
    325 			}
    326 		}
    327 	}
    328 	if kind == 30 && len(recipients) == 0 {
    329 		if err := client.send(chatPacket(36, appendChatString(nil, "Player not online."))); err != nil {
    330 			return err
    331 		}
    332 		return nil
    333 	}
    334 	var outgoing []byte
    335 	if kind == 65 {
    336 		outgoing = binary.BigEndian.AppendUint32([]byte{groupType}, groupID)
    337 	}
    338 	outgoing = binary.BigEndian.AppendUint32(outgoing, id)
    339 	outgoing = appendChatString(outgoing, message)
    340 	outgoing = appendChatString(outgoing, blob)
    341 	channel := "tell"
    342 	if kind == 65 {
    343 		channel = "Global"
    344 		if groupType == 2 {
    345 			channel = "Team"
    346 		}
    347 	}
    348 	server.logChat(chatHistoryEntry{Channel: channel, SenderID: id, Sender: name, RecipientID: recipient, Recipient: recipientName, Message: message}, recipients)
    349 	for _, target := range recipients {
    350 		if target.send(chatNamePacket(id, name)) == nil {
    351 			target.send(chatPacket(kind, outgoing))
    352 		}
    353 	}
    354 	return nil
    355 }
    356 
    357 func (server *server) sendVicinity(client *worldClient, kind uint32, message string, metadata []byte) {
    358 	runtime, delivery, err := server.prepareVicinity(client, kind, message, metadata)
    359 	if err == nil && delivery != nil {
    360 		err = runtime.call(*delivery)
    361 	}
    362 	if err != nil {
    363 		log.Printf("Vicinity chat: %v", err)
    364 	}
    365 }
    366 
    367 func (server *server) prepareVicinity(client *worldClient, kind uint32, message string, metadata []byte) (*chatRuntime, *chatVicinity, error) {
    368 	message = strings.TrimSuffix(message, "\x00")
    369 	if kind > 3 || len(message) == 0 && len(metadata) == 0 || len(message) > 4096 || strings.ContainsRune(message, 0) {
    370 		return nil, nil, nil
    371 	}
    372 	radius := [4]float32{10, 1.5, 60, 10}[kind]
    373 	sender := server.characters[client.id]
    374 	if sender == nil || server.clients[client.id] != client || !client.ready {
    375 		return nil, nil, nil
    376 	}
    377 	runtime, err := server.chat()
    378 	if err != nil {
    379 		return nil, nil, err
    380 	}
    381 	var recipients []uint32
    382 	for id, otherClient := range server.clients {
    383 		other := server.characters[id]
    384 		if !otherClient.ready || other.playfield != sender.playfield {
    385 			continue
    386 		}
    387 		x, y, z := other.position[0]-sender.position[0], other.position[1]-sender.position[1], other.position[2]-sender.position[2]
    388 		if x*x+y*y+z*z <= radius*radius {
    389 			recipients = append(recipients, id)
    390 		}
    391 	}
    392 	entry := chatHistoryEntry{Channel: [4]string{"say", "whisper", "shout", "emote"}[kind],
    393 		SenderID: sender.id, Sender: sender.name, Playfield: sender.playfield, Message: message}
    394 	return runtime, &chatVicinity{entry: entry, recipients: recipients, kind: kind, metadata: slices.Clone(metadata)}, nil
    395 }
    396 
    397 type chatVicinity struct {
    398 	entry      chatHistoryEntry
    399 	recipients []uint32
    400 	kind       uint32
    401 	metadata   []byte
    402 }
    403 
    404 func (command chatVicinity) execute(state *chatState) error {
    405 	if state.people[command.entry.SenderID] == nil {
    406 		return nil
    407 	}
    408 	var recipients []*chatClient
    409 	for _, id := range command.recipients {
    410 		if client := state.clients[id]; client != nil && state.people[id].online {
    411 			recipients = append(recipients, client)
    412 		}
    413 	}
    414 	state.logChat(command.entry, recipients)
    415 	body := appendChatString(binary.BigEndian.AppendUint32(nil, command.entry.SenderID), command.entry.Message)
    416 	body = binary.BigEndian.AppendUint16(body, uint16(1+len(command.metadata)))
    417 	body = append(body, byte(command.kind))
    418 	body = append(body, command.metadata...)
    419 	for _, target := range recipients {
    420 		if target.send(chatNamePacket(command.entry.SenderID, command.entry.Sender)) == nil {
    421 			target.send(chatPacket(34, body))
    422 		}
    423 	}
    424 	return nil
    425 }