commit 750c1e70162e19a0cc54d479042a971f079d0a02
parent 9501f5318638705882944540c00eb3268faa2fda
Author: anon <anon@example.com>
Date: Sat, 7 Nov 2026 05:12:14 +0000
Route visitor and native creation through the account coordinator
Diffstat:
13 files changed, 540 insertions(+), 179 deletions(-)
diff --git a/DEVELOPERS.md b/DEVELOPERS.md
@@ -170,14 +170,19 @@ cleanup. Password changes recheck the same credential in the SQL update after
hashing. These paths do not read the global character map. Native login listing
and selection also read durable identities.
-Browser claim, login and form-based creation use the same coordinator queue as
+Browser claim, login and character creation use the same coordinator queue as
mission retirement. Only affected zone owners pause while SQLite revalidates
credentials and commits the changes atomically. Existing actors stay with their
owners; detached identity updates are published after commit. Creation allocates
the player ID in that transaction and transfers the new actor and starting items
to its zone before reporting success. Session admission waits if authentication
-observes a committed player before publication. Visitor launch, native creation,
-production state partitioning and administrative/test entry points still need
+observes a committed player before publication. Visitor launch and synthetic
+native login use the same transactional player allocator and publication path.
+Pending native creation attempts belong to the coordinator; password derivation
+runs outside it and then rechecks both the credential and attempt identity.
+Native creation retains its browser cookie, so replacement revokes only the old
+player's streams and preserves a new connection already awaiting publication.
+Production state partitioning and administrative/test entry points still need
migration before the global simulation loops can be removed.
World and chat transport entry points use the routing directory and chat owner
diff --git a/server/browser_account_change.go b/server/browser_account_change.go
@@ -4,6 +4,7 @@ import (
"database/sql"
"errors"
"fmt"
+ "slices"
)
var (
@@ -75,9 +76,11 @@ func (write *browserAccountWrite) persist(tx *sql.Tx) error {
if write.created != nil {
// Allocation rolls back with the new character, its items and both
// credentials. The writer returns the committed identity to the caller.
- if err := tx.QueryRow("UPDATE world SET last_character_id=last_character_id+1 WHERE id=1 AND last_character_id<999999 RETURNING last_character_id").Scan(&write.target); err != nil {
+ id, err := allocatePlayerID(tx)
+ if err != nil {
return err
}
+ write.target = id
write.created.record.Profile.ID = write.target
if err := write.created.persist(tx); err != nil {
return err
@@ -145,6 +148,13 @@ func (change *browserAccountChange) persist(configuration *server) error {
if err := configuration.browserStartingItems_locked(change.created); err != nil {
return err
}
+ if change.action == "native" {
+ // Arrival Hall grants the chosen side's map and gifts on departure.
+ change.created.inventory.Items = slices.DeleteFunc(change.created.inventory.Items, func(item ownedItem) bool { return item.Template == 116697 })
+ for index := range change.created.inventory.Items {
+ change.created.inventory.Items[index].Slot = 64 + uint32(index)
+ }
+ }
created := prepareBrowserPlayerWrite(change.created, change.salt, change.hash)
write.created = &created
}
@@ -159,21 +169,22 @@ func (change *browserAccountChange) persist(configuration *server) error {
}
func (state *server) changeBrowserAccount(change *browserAccountChange) error {
+ return state.accountOperation(func(configuration *server) error {
+ return state.changeBrowserAccount_locked(configuration, change)
+ })
+}
+
+func (state *server) changeBrowserAccount_locked(configuration *server, change *browserAccountChange) error {
if state.world != nil {
- return state.world.operate(func(configuration *server) error {
- if err := state.world.changeAccount(configuration.emptyZone(), change); err != nil {
- return err
- }
- // Owners are released, but the next account operation must not
- // publish a newer session before this one's replacement finishes.
- state.replaceBrowserStreams(change.current, change.target)
- return nil
- })
+ if err := state.world.changeAccount(configuration, change); err != nil {
+ return err
+ }
+ // Release the owners before replacement, but finish replacement before
+ // another account operation can publish a newer session.
+ state.replaceAccountStreams_locked(change)
+ return nil
}
- state.updateMutex.Lock()
- defer state.updateMutex.Unlock()
- state.mutex.Lock()
- defer state.mutex.Unlock()
+
current := state.characters[change.current]
if current == nil || current.browserTokenHash != change.previous {
return errBrowserSessionChanged
@@ -188,10 +199,20 @@ func (state *server) changeBrowserAccount(change *browserAccountChange) error {
if change.created != nil {
state.publishBrowserPlayer_locked(change.created)
}
- state.replaceBrowserStreams(change.current, change.target)
+ state.replaceAccountStreams_locked(change)
return nil
}
+func (state *server) replaceAccountStreams_locked(change *browserAccountChange) {
+ if change.action == "native" {
+ // Native creation retains its cookie. The new player's connection may
+ // already be waiting for publication when the old session is replaced.
+ state.replaceBrowserStreams(change.current)
+ return
+ }
+ state.replaceBrowserStreams(change.current, change.target)
+}
+
type accountDecision struct {
updates []accountIdentity
err error
diff --git a/server/browser_account_owner_test.go b/server/browser_account_owner_test.go
@@ -225,7 +225,7 @@ func TestWorldPlayerAdmissionWaitsForCommittedCreationPublication(t *testing.T)
change := &browserAccountChange{action: "create", current: 1, previous: previous,
credential: "created", abandoned: "abandoned", name: "Alice", created: created,
salt: []byte{}, hash: []byte{}}
- if err := change.persist(configuration.emptyZone()); err != nil {
+ if err := change.persist(configuration); err != nil {
return err
}
close(committed)
diff --git a/server/browser_creation.go b/server/browser_creation.go
@@ -3,6 +3,7 @@ package main
import (
"ao/server/gamedata"
"database/sql"
+ "errors"
"fmt"
"net/http"
"slices"
@@ -137,6 +138,28 @@ func (server *server) browserStartingItems_locked(player *character) error {
return nil
}
+var errPlayerIdentitiesExhausted = errors.New("player identities exhausted")
+
+func allocatePlayerID(tx *sql.Tx) (uint32, error) {
+ var id uint32
+ err := tx.QueryRow("UPDATE world SET last_character_id=last_character_id+1 WHERE id=1 AND last_character_id<999999 RETURNING last_character_id").Scan(&id)
+ if err == sql.ErrNoRows {
+ return 0, errPlayerIdentitiesExhausted
+ }
+ return id, err
+}
+
+type allocatedPlayerWrite struct{ player browserPlayerWrite }
+
+func (write *allocatedPlayerWrite) persist(tx *sql.Tx) error {
+ id, err := allocatePlayerID(tx)
+ if err != nil {
+ return err
+ }
+ write.player.record.Profile.ID = id
+ return write.player.persist(tx)
+}
+
type browserPlayerWrite struct {
record characterRecord
items []ownedItem
diff --git a/server/browser_launch.go b/server/browser_launch.go
@@ -5,6 +5,7 @@ import (
"crypto/rand"
"crypto/sha256"
"database/sql"
+ "errors"
"fmt"
mathrand "math/rand/v2"
"net/http"
@@ -49,34 +50,37 @@ func (server *server) browserCharacter_locked(r *http.Request) *character {
return nil
}
-func (server *server) browserLaunch(w http.ResponseWriter, r *http.Request) {
- server.mutex.Lock()
- defer server.mutex.Unlock()
-
- // A browser owns one persistent character, independent of other online players.
- character := server.browserCharacter_locked(r)
- if r.URL.Query().Get("create") == "1" {
- if character == nil {
- http.Error(w, "Your browser session has ended. Reconnect to continue.", http.StatusUnauthorized)
- return
+func (state *server) browserLaunch(w http.ResponseWriter, r *http.Request) {
+ var id uint32
+ var token string
+ err := state.accountOperation(func(configuration *server) error {
+ credential := browserCredential(r)
+ var err error
+ id, err = state.browserPlayerID(credential)
+ if err != nil {
+ return err
}
- if server.browserCreations == nil {
- server.browserCreations = make(map[string]*browserCreationCredentials)
+ if r.URL.Query().Get("create") == "1" {
+ if id == 0 {
+ return errBrowserSessionChanged
+ }
+ if configuration.browserCreations == nil {
+ configuration.browserCreations = make(map[string]*browserCreationCredentials)
+ }
+ configuration.browserCreations[credential] = &browserCreationCredentials{}
+ } else if id != 0 {
+ // Returning to the game cancels an unfinished native creator.
+ delete(configuration.browserCreations, credential)
}
- server.browserCreations[character.browserTokenHash] = &browserCreationCredentials{}
- } else if character != nil {
- // Returning to the game cancels any unfinished creator using this credential.
- delete(server.browserCreations, character.browserTokenHash)
- }
- if character == nil {
- token := rand.Text()
- character = server.newCharacter_locked()
- character.title = "Visitor"
- character.running = true
- character.browserTokenHash = fmt.Sprintf("%x", sha256.Sum256([]byte(token)))
- character.playfield = 705
- character.position = [3]float32{960 + float32(mathrand.IntN(49)-24)/8, 16.5, 510 + float32(mathrand.IntN(49)-24)/8}
- character.rotation = [4]float32{0, 0.9238795, 0, -0.3826834}
+ if id != 0 {
+ return nil
+ }
+
+ token = rand.Text()
+ player := &character{title: "Visitor", running: true, level: 1, profession: 1,
+ browserTokenHash: fmt.Sprintf("%x", sha256.Sum256([]byte(token))),
+ playfield: 705, position: [3]float32{960 + float32(mathrand.IntN(49)-24)/8, 16.5, 510 + float32(mathrand.IntN(49)-24)/8},
+ rotation: [4]float32{0, 0.9238795, 0, -0.3826834}}
// Use complete native Solitus head choices with their matching skin race.
appearance := appearanceFields{Race: 1, Fatness: 1, Breed: 1, Sex: uint16(2 + mathrand.IntN(2)), Side: 2}
var heads []gamedata.PlayerHead
@@ -86,24 +90,38 @@ func (server *server) browserLaunch(w http.ResponseWriter, r *http.Request) {
}
}
head := heads[mathrand.IntN(len(heads))]
- character.headMesh, appearance.Race = head.Mesh, head.Race
- character.appearance = appearance.packed()
- if err := server.saveVisitor_locked(character); err != nil {
- delete(server.characters, character.id)
- server.nextCharacter--
- http.Error(w, err.Error(), http.StatusInternalServerError)
- return
+ player.headMesh, appearance.Race = head.Mesh, head.Race
+ player.appearance = appearance.packed()
+ player.stats = defaultCharacterStats(appearance.Breed)
+ player.health = player.maximumHealth()
+ if err := configuration.saveVisitor_locked(player); err != nil {
+ return err
+ }
+ id = player.id
+ if state.world != nil {
+ return state.world.createPlayer(player)
}
- server.publishChatPerson_locked(character)
- server.setBrowserCookie(w, r, token)
+ state.publishBrowserPlayer_locked(player)
+ return nil
+ })
+ if err != nil {
+ status := http.StatusInternalServerError
+ if errors.Is(err, errBrowserSessionChanged) {
+ status = http.StatusUnauthorized
+ }
+ http.Error(w, err.Error(), status)
+ return
+ }
+ if token != "" {
+ state.setBrowserCookie(w, r, token)
}
w.Header().Set("Content-Type", "text/plain")
w.Header().Set("Cache-Control", "no-store")
if r.URL.Query().Get("create") == "1" {
// Character zero selects the original creator and its login connection.
- w.Header().Set("X-AO-World-Port", fmt.Sprint(server.worldPort))
- fmt.Fprintf(w, "Clientr.exe localtest localtest 0 2130706433 %d 0 0", server.loginPort)
+ w.Header().Set("X-AO-World-Port", fmt.Sprint(state.worldPort))
+ fmt.Fprintf(w, "Clientr.exe localtest localtest 0 2130706433 %d 0 0", state.loginPort)
return
}
- fmt.Fprintf(w, "Clientr.exe localtest localtest %d 2130706433 %d 0 0", character.id, server.worldPort)
+ fmt.Fprintf(w, "Clientr.exe localtest localtest %d 2130706433 %d 0 0", id, state.worldPort)
}
diff --git a/server/main.go b/server/main.go
@@ -195,14 +195,11 @@ func (server *server) serveLogin(conn net.Conn) error {
}
if len(users) == 0 || len(packet) == 20 {
// The direct-launch test helpers request a fresh synthetic session.
- server.mutex.Lock()
- character := server.newCharacter_locked()
- err := server.saveUser_locked(character)
- users = []userData{character.userData()}
- server.mutex.Unlock()
+ user, err := server.createSyntheticPlayer()
if err != nil {
return err
}
+ users = []userData{user}
}
body := binary.BigEndian.AppendUint32(nil, uint32(len(users)))
for _, user := range users {
diff --git a/server/native_creation.go b/server/native_creation.go
@@ -6,13 +6,12 @@ import (
"crypto/rand"
"crypto/sha256"
"encoding/binary"
+ "errors"
"fmt"
"io"
"log"
"net"
"net/http"
- "slices"
- "strings"
"github.com/coder/websocket"
)
@@ -22,7 +21,12 @@ type browserCreationCredentials struct {
salt, hash []byte
}
-func (server *server) prepareBrowserCreation(w http.ResponseWriter, r *http.Request) {
+var (
+ errBrowserCreationRequired = errors.New("Start character creation first.")
+ errBrowserCreationEnded = errors.New("Character creation has ended. Start again to continue.")
+)
+
+func (state *server) prepareBrowserCreation(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "no-store")
r.Body = http.MaxBytesReader(w, r.Body, 4096)
if err := r.ParseForm(); err != nil {
@@ -35,82 +39,113 @@ func (server *server) prepareBrowserCreation(w http.ResponseWriter, r *http.Requ
http.Error(w, "Use a name of 4-12 letters or digits, with at least four initial letters and digits only at the end, and a password up to 1024 bytes.", http.StatusBadRequest)
return
}
- server.mutex.Lock()
- current := server.browserCharacter_locked(r)
- if current == nil {
- server.mutex.Unlock()
- http.Error(w, "Your browser session has ended. Reconnect to continue.", http.StatusUnauthorized)
- return
+ credential := browserCredential(r)
+ var currentID uint32
+ var pending *browserCreationCredentials
+ err := state.accountOperation(func(configuration *server) error {
+ var err error
+ currentID, err = state.browserPlayerID(credential)
+ if err != nil {
+ return err
+ }
+ if currentID == 0 {
+ return errBrowserSessionChanged
+ }
+ pending = configuration.browserCreations[credential]
+ if pending == nil {
+ return errBrowserCreationRequired
+ }
+ return nil
+ })
+ if err == nil {
+ // Derive outside ownership, then recheck the same attempt and identity.
+ salt := make([]byte, 16)
+ rand.Read(salt)
+ hash := state.browserPassword(password, salt)
+ err = state.accountOperation(func(configuration *server) error {
+ id, err := state.browserPlayerID(credential)
+ if err != nil {
+ return err
+ }
+ if id == 0 || id != currentID {
+ return errBrowserSessionChanged
+ }
+ if configuration.browserCreations[credential] != pending {
+ return errBrowserCreationEnded
+ }
+ var taken bool
+ if err := configuration.db.QueryRow("SELECT EXISTS(SELECT 1 FROM characters WHERE id<1000000 AND name=? COLLATE NOCASE)", name).Scan(&taken); err != nil {
+ return err
+ }
+ if taken {
+ return errBrowserNameTaken
+ }
+ pending.name, pending.salt, pending.hash = name, salt, hash
+ return nil
+ })
}
- currentID, credential := current.id, current.browserTokenHash
- pending := server.browserCreations[credential]
- server.mutex.Unlock()
- if pending == nil {
- http.Error(w, "Start character creation first.", http.StatusConflict)
+ if err != nil {
+ status := http.StatusInternalServerError
+ if errors.Is(err, errBrowserSessionChanged) {
+ status = http.StatusUnauthorized
+ } else if errors.Is(err, errBrowserCreationRequired) || errors.Is(err, errBrowserCreationEnded) || errors.Is(err, errBrowserNameTaken) {
+ status = http.StatusConflict
+ }
+ http.Error(w, err.Error(), status)
return
}
- // Keep only salted credentials while the original creator runs.
- salt := make([]byte, 16)
- rand.Read(salt)
- hash := server.browserPassword(password, salt)
- server.mutex.Lock()
- defer server.mutex.Unlock()
- current = server.browserCharacter_locked(r)
- if current == nil || current.id != currentID || current.browserTokenHash != credential {
- http.Error(w, "Your browser session changed. Reconnect to continue.", http.StatusUnauthorized)
- return
- }
- if server.browserCreations[credential] != pending {
- http.Error(w, "Character creation has ended. Start again to continue.", http.StatusConflict)
- return
- }
- for _, other := range server.characters {
- if !other.npc && strings.EqualFold(other.name, name) {
- http.Error(w, "That player name is already in use.", http.StatusConflict)
- return
- }
- }
- pending.name, pending.salt, pending.hash = name, salt, hash
w.Header().Set("X-AO-Creation-Name", name)
w.WriteHeader(http.StatusNoContent)
}
-func (server *server) browserCreate(w http.ResponseWriter, r *http.Request) {
- server.mutex.Lock()
- current := server.browserCharacter_locked(r)
+func (state *server) browserCreate(w http.ResponseWriter, r *http.Request) {
+ credential := browserCredential(r)
var id uint32
- var credential string
- if current != nil {
- id, credential = current.id, current.browserTokenHash
- }
- pending := server.browserCreations[credential]
- server.mutex.Unlock()
- if id == 0 {
- http.Error(w, "Open the game page to start a visitor session.", http.StatusUnauthorized)
- return
- }
- if pending == nil {
- http.Error(w, "Start character creation first.", http.StatusConflict)
+ var pending *browserCreationCredentials
+ err := state.accountOperation(func(configuration *server) error {
+ var err error
+ id, err = state.browserPlayerID(credential)
+ if err != nil {
+ return err
+ }
+ if id == 0 {
+ return errBrowserSessionChanged
+ }
+ pending = configuration.browserCreations[credential]
+ if pending == nil {
+ return errBrowserCreationRequired
+ }
+ return nil
+ })
+ if err != nil {
+ status := http.StatusInternalServerError
+ if errors.Is(err, errBrowserSessionChanged) {
+ status = http.StatusUnauthorized
+ } else if errors.Is(err, errBrowserCreationRequired) {
+ status = http.StatusConflict
+ }
+ http.Error(w, err.Error(), status)
return
}
+
socket, err := websocket.Accept(w, r, nil)
if err != nil {
return
}
defer socket.CloseNow()
- finish, accepted := server.tasks.enter(func() { socket.CloseNow() })
+ finish, accepted := state.tasks.enter(func() { socket.CloseNow() })
if !accepted {
return
}
defer finish()
connection := websocket.NetConn(context.Background(), socket, websocket.MessageBinary)
- if err := server.serveNativeCreation(connection, id, credential, pending); err != nil {
+ if err := state.serveNativeCreation(connection, id, credential, pending); err != nil {
log.Printf("Browser creation connection: %v", err)
}
}
-func (server *server) serveNativeCreation(conn net.Conn, currentID uint32, credential string, pending *browserCreationCredentials) error {
+func (state *server) serveNativeCreation(conn net.Conn, currentID uint32, credential string, pending *browserCreationCredentials) error {
var createdID uint32
for {
packet, err := readPacket(conn)
@@ -130,9 +165,10 @@ func (server *server) serveNativeCreation(conn net.Conn, currentID uint32, crede
// The browser cookie authenticates this connection, independently of launcher credentials.
response = systemPacket(0x0e, binary.BigEndian.AppendUint32(nil, 0))
case 0x55:
- server.mutex.Lock()
- name := pending.name
- server.mutex.Unlock()
+ var name string
+ if err := state.accountOperation(func(*server) error { name = pending.name; return nil }); err != nil {
+ return err
+ }
if name == "" {
name = randomVisitorName()
}
@@ -140,7 +176,7 @@ func (server *server) serveNativeCreation(conn net.Conn, currentID uint32, crede
case 0x0f:
var reason uint32
if createdID == 0 {
- createdID, reason, err = server.createNativeCharacter(currentID, credential, pending, packet[20:])
+ createdID, reason, err = state.createNativeCharacter(currentID, credential, pending, packet[20:])
if err != nil {
log.Printf("Creating browser character: %v", err)
reason = 9
@@ -157,7 +193,7 @@ func (server *server) serveNativeCreation(conn net.Conn, currentID uint32, crede
}
body := binary.BigEndian.AppendUint32(nil, createdID)
body = append(body, 127, 0, 0, 1)
- body = binary.BigEndian.AppendUint16(body, uint16(server.worldPort))
+ body = binary.BigEndian.AppendUint16(body, uint16(state.worldPort))
body = append(body, make([]byte, 8)...)
response = systemPacket(0x17, body)
default:
@@ -169,7 +205,7 @@ func (server *server) serveNativeCreation(conn net.Conn, currentID uint32, crede
}
}
-func (server *server) createNativeCharacter(currentID uint32, credential string, pending *browserCreationCredentials, body []byte) (uint32, uint32, error) {
+func (state *server) createNativeCharacter(currentID uint32, credential string, pending *browserCreationCredentials, body []byte) (uint32, uint32, error) {
// nr.dll!CharacterData_t::WriteDataStream and CharacterInfo_c::WriteStream use version 4.
if len(body) < 89 || binary.BigEndian.Uint32(body) != 4 || body[8] != 'a' || binary.BigEndian.Uint32(body[37:]) != 4 {
return 0, 9, nil
@@ -215,7 +251,7 @@ func (server *server) createNativeCharacter(currentID uint32, credential string,
if mesh == 0 {
return 0, 9, nil
}
- player, err := server.creationCharacter(mesh, uint16(profession), 0, uint16(build), uint16(height))
+ player, err := state.creationCharacter(mesh, uint16(profession), 0, uint16(build), uint16(height))
if err != nil {
return 0, 0, err
}
@@ -223,52 +259,35 @@ func (server *server) createNativeCharacter(currentID uint32, credential string,
player.playfield, player.position = 4604, [3]float32{190, 1.52, 200}
player.rotation, player.returnDoor = [4]float32{0, 1, 0, 0}, nil
- // Publish the player and transfer browser ownership only after the complete transaction commits.
- server.updateMutex.Lock()
- defer server.updateMutex.Unlock()
- server.mutex.Lock()
- defer server.mutex.Unlock()
- current := server.characters[currentID]
- if current == nil || current.browserTokenHash != credential || server.browserCreations[credential] != pending || len(pending.hash) == 0 {
- return 0, 2, nil
- }
- if name != pending.name {
- return 0, 0x1f, nil
- }
- for _, other := range server.characters {
- if !other.npc && strings.EqualFold(other.name, name) {
- return 0, 0x1e, nil
+ // The coordinator owns pending credentials until commit and publication finish.
+ var created, reason uint32
+ err = state.accountOperation(func(configuration *server) error {
+ if configuration.browserCreations[credential] != pending || len(pending.hash) == 0 {
+ reason = 2
+ return nil
}
- }
- if server.nextCharacter >= 999999 {
- return 0, 8, nil
- }
- player.id, player.browserTokenHash = server.nextCharacter+1, credential
- if err := server.browserStartingItems_locked(player); err != nil {
- return 0, 0, err
- }
- // The Arrival Hall grants the chosen side's map and gifts when the player departs.
- player.inventory.Items = slices.DeleteFunc(player.inventory.Items, func(item ownedItem) bool { return item.Template == 116697 })
- for index := range player.inventory.Items {
- player.inventory.Items[index].Slot = 64 + uint32(index)
- }
- abandoned := fmt.Sprintf("%x", sha256.Sum256([]byte(rand.Text())))
- if err := server.commitWrite(databaseBatch{
- prepareBrowserPlayerWrite(player, pending.salt, pending.hash),
- recordUpdate{"characters", "browser_token_hash", currentID, []any{abandoned}},
- }); err != nil {
- return 0, 0, err
- }
- server.publishBrowserPlayer_locked(player)
- delete(server.browserCreations, credential)
- current.browserTokenHash, current.savedProfile.BrowserTokenHash = abandoned, abandoned
- if client := server.clients[currentID]; client != nil {
- server.cancelPlayerTrade_locked(client)
- client.ready = false
- if client.stream == nil {
- client.disconnect(client.conn)
+ if name != pending.name {
+ reason = 0x1f
+ return nil
}
- }
- server.replaceBrowserStreams(currentID)
- return player.id, 0, nil
+ change := &browserAccountChange{action: "native", current: currentID, previous: credential,
+ credential: credential, abandoned: fmt.Sprintf("%x", sha256.Sum256([]byte(rand.Text()))),
+ name: name, salt: pending.salt, hash: pending.hash, created: player}
+ err := state.changeBrowserAccount_locked(configuration, change)
+ switch {
+ case errors.Is(err, errBrowserSessionChanged):
+ reason = 2
+ case errors.Is(err, errBrowserNameTaken):
+ reason = 0x1e
+ case errors.Is(err, errPlayerIdentitiesExhausted):
+ reason = 8
+ case err != nil:
+ return err
+ default:
+ created = change.target
+ delete(configuration.browserCreations, credential)
+ }
+ return nil
+ })
+ return created, reason, err
}
diff --git a/server/native_creation_owner_test.go b/server/native_creation_owner_test.go
@@ -0,0 +1,225 @@
+package main
+
+import (
+ "bytes"
+ "encoding/binary"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+ "time"
+)
+
+func TestNativeCreationRoutedCommitRetryAndCookieTransfer(t *testing.T) {
+ fixture := newTestServer(t)
+ fixture.world = newRoutedTestWorld(t, fixture)
+ t.Cleanup(func() {
+ if err := fixture.world.stop(); err != nil {
+ t.Error(err)
+ }
+ })
+ fixture.updateMutex.Lock()
+ defer fixture.updateMutex.Unlock()
+ fixture.mutex.Lock()
+ defer fixture.mutex.Unlock()
+ cookie := accountVisitor(t, fixture)
+ startNativeCreation(t, fixture, cookie)
+ prepareNativeCreation(t, fixture, cookie, "Alice", "secret")
+ connection := nativeCreationConnection(t, fixture, cookie)
+ if _, err := fixture.db.Exec("CREATE TRIGGER reject_creation BEFORE UPDATE OF browser_token_hash ON characters WHEN NEW.id=1 BEGIN SELECT RAISE(ABORT,'credential'); END"); err != nil {
+ t.Fatal(err)
+ }
+
+ failed := nativeCreationExchange(t, connection, nativeCreationAlice(t))
+
+ if binary.BigEndian.Uint32(failed) != 0x10 || binary.BigEndian.Uint32(failed[4:]) != 9 {
+ t.Fatalf("native creation ignored failed credential transfer: %x", failed)
+ }
+ var players, last uint32
+ if err := fixture.db.QueryRow("SELECT (SELECT count(*) FROM players),last_character_id FROM world WHERE id=1").Scan(&players, &last); err != nil || players != 1 || last != 1 {
+ t.Fatal("native failure published a player or consumed its identity", players, last, err)
+ }
+ if route, err := fixture.world.lookup(2); err != nil || route != nil {
+ t.Fatal("failed native creation published an owner", route, err)
+ }
+ if _, err := fixture.db.Exec("DROP TRIGGER reject_creation"); err != nil {
+ t.Fatal(err)
+ }
+
+ created := nativeCreationExchange(t, connection, nativeCreationAlice(t))
+ repeated := nativeCreationExchange(t, connection, nativeCreationAlice(t))
+
+ if binary.BigEndian.Uint32(created) != 0x11 || binary.BigEndian.Uint32(created[4:]) != 2 || !bytes.Equal(created, repeated) {
+ t.Fatalf("native retry did not publish exactly one player: %x %x", created, repeated)
+ }
+ request := httptest.NewRequest("GET", "/", nil)
+ request.AddCookie(cookie)
+ id, err := fixture.browserPlayerID(browserCredential(request))
+ if err != nil || id != 2 {
+ t.Fatal("native creation did not transfer its cookie", id, err)
+ }
+ owner, err := fixture.world.owner(2)
+ if err != nil {
+ t.Fatal(err)
+ }
+ query := &zoneAccountObservation{player: 2}
+ if err := owner.call(query); err != nil || query.name != "Alice" || query.items != 4 {
+ t.Fatal("native success preceded complete destination ownership", query, err)
+ }
+ location := &zoneTransferQuery{player: 2}
+ if err := owner.call(location); err != nil || location.playfield != 4604 {
+ t.Fatal("native creation did not arrive in Arrival Hall", location, err)
+ }
+ if err := fixture.accountOperation(func(configuration *server) error {
+ if len(configuration.browserCreations) != 0 {
+ t.Error("completed native attempt retained credentials")
+ }
+ return nil
+ }); err != nil {
+ t.Fatal(err)
+ }
+ if len(fixture.characters) != 0 || len(fixture.browserCreations) != 0 {
+ t.Fatal("routed creation repopulated global actors or pending credentials")
+ }
+}
+
+func TestBrowserRoutedVisitorRampAndSyntheticNativeLogin(t *testing.T) {
+ fixture := newTestServer(t)
+ fixture.world = newRoutedTestWorld(t, fixture)
+ t.Cleanup(func() {
+ if err := fixture.world.stop(); err != nil {
+ t.Error(err)
+ }
+ })
+ fixture.updateMutex.Lock()
+ defer fixture.updateMutex.Unlock()
+ fixture.mutex.Lock()
+ defer fixture.mutex.Unlock()
+ responses := make(chan *httptest.ResponseRecorder, 32)
+ for range 32 {
+ go func() {
+ response := httptest.NewRecorder()
+ fixture.browserLaunch(response, httptest.NewRequest("POST", "/browser-launch", nil))
+ responses <- response
+ }()
+ }
+ deadline := time.After(10 * time.Second)
+ for range 32 {
+ select {
+ case response := <-responses:
+ if response.Code != http.StatusOK || len(response.Result().Cookies()) != 1 {
+ t.Fatal("routed visitor launch failed", response.Code, response.Body.String())
+ }
+ case <-deadline:
+ t.Fatal("visitor creation waited for the global locks")
+ }
+ }
+ var players, names, items int
+ if err := fixture.db.QueryRow("SELECT count(*),count(DISTINCT name COLLATE NOCASE),(SELECT count(*) FROM items) FROM characters WHERE id<1000000").Scan(&players, &names, &items); err != nil || players != 32 || names != 32 || items != 224 {
+ t.Fatal("concurrent visitor creation lost names or starter items", players, names, items, err)
+ }
+ for id := uint32(1); id <= 32; id++ {
+ owner, err := fixture.world.owner(id)
+ if err != nil {
+ t.Fatal(err)
+ }
+ query := &zoneAccountObservation{player: id}
+ if err := owner.call(query); err != nil || query.items != 7 {
+ t.Fatal("visitor response preceded complete ownership", id, query, err)
+ }
+ }
+
+ // An empty native login packet requests a fresh synthetic player rather
+ // than listing visitors. It shares the same durable player ID allocation.
+ peer, native := net.Pipe()
+ defer peer.Close()
+ peer.SetDeadline(time.Now().Add(3 * time.Second))
+ finished := make(chan error, 1)
+ go func() { defer native.Close(); finished <- fixture.serveLogin(native) }()
+ if _, err := peer.Write(systemPacket(0x25, nil)); err != nil {
+ t.Fatal(err)
+ }
+ listing, err := readPacket(peer)
+ if err != nil || binary.BigEndian.Uint32(listing[20:24]) != 1 || binary.BigEndian.Uint32(listing[28:32]) != 33 || !bytes.Contains(listing, []byte("Local Explorer 33")) {
+ t.Fatal("native login did not create a distinct synthetic player", listing, err)
+ }
+ peer.Close()
+ if err := <-finished; err != nil {
+ t.Fatal(err)
+ }
+ owner, err := fixture.world.owner(33)
+ if err != nil {
+ t.Fatal(err)
+ }
+ query := &zoneTransferQuery{player: 33}
+ if err := owner.call(query); err != nil || query.playfield != 950 || !query.present {
+ t.Fatal("synthetic login returned before destination publication", query, err)
+ }
+ if len(fixture.characters) != 0 {
+ t.Fatal("creation repopulated the global actor map")
+ }
+}
+
+func TestNativeCreationRoutedRefreshDuringPasswordDerivation(t *testing.T) {
+ fixture := newTestServer(t)
+ fixture.world = newRoutedTestWorld(t, fixture)
+ t.Cleanup(func() {
+ if err := fixture.world.stop(); err != nil {
+ t.Error(err)
+ }
+ })
+ fixture.updateMutex.Lock()
+ defer fixture.updateMutex.Unlock()
+ fixture.mutex.Lock()
+ defer fixture.mutex.Unlock()
+ cookie := accountVisitor(t, fixture)
+ startNativeCreation(t, fixture, cookie)
+ connection := nativeCreationConnection(t, fixture, cookie)
+ fixture.passwordMutex.Lock()
+ locked := true
+ defer func() {
+ if locked {
+ fixture.passwordMutex.Unlock()
+ }
+ }()
+ queries := fixture.databaseQueries.Load()
+ finished := make(chan *httptest.ResponseRecorder, 1)
+ done := make(chan struct{})
+ t.Cleanup(func() { <-done })
+ go func() {
+ defer close(done)
+ finished <- nativePreparationRequest(fixture, cookie, "Alice", "secret")
+ }()
+ deadline := time.After(5 * time.Second)
+ poll := time.NewTicker(time.Millisecond)
+ defer poll.Stop()
+ for fixture.databaseQueries.Load() == queries {
+ select {
+ case <-poll.C:
+ case <-deadline:
+ t.Fatal("native preparation did not read its credential")
+ }
+ }
+
+ // Refresh reaches the coordinator while derivation is still blocked. The
+ // eventual hash must not authorize either the old or the refreshed attempt.
+ startNativeCreation(t, fixture, cookie)
+ fixture.passwordMutex.Unlock()
+ locked = false
+ select {
+ case response := <-finished:
+ if response.Code != http.StatusConflict {
+ t.Fatal(response.Code, response.Body.String())
+ }
+ case <-deadline:
+ t.Fatal("native preparation did not resume after derivation")
+ }
+ refused := nativeCreationExchange(t, connection, nativeCreationAlice(t))
+ if binary.BigEndian.Uint32(refused) != 0x10 || binary.BigEndian.Uint32(refused[4:]) != 2 {
+ t.Fatalf("stale prepared credentials created a player: %x", refused)
+ }
+ var players int
+ if err := fixture.db.QueryRow("SELECT count(*) FROM players").Scan(&players); err != nil || players != 1 {
+ t.Fatal("replaced attempt changed persistent players", players, err)
+ }
+}
diff --git a/server/state.go b/server/state.go
@@ -263,16 +263,21 @@ func (server *server) newCharacter() *character {
func (server *server) newCharacter_locked() *character {
server.nextCharacter++
- character := &character{
- id: server.nextCharacter, name: fmt.Sprintf("Local Explorer %d", server.nextCharacter),
- playfield: 950, position: [3]float32{52.625, 14.75, 56.875 + float32((server.nextCharacter-1)%4)*3},
+ player := newPlayerCharacter(server.nextCharacter)
+ player.geometry = server.geometry
+ server.characters[player.id] = player
+ return player
+}
+
+func newPlayerCharacter(id uint32) *character {
+ player := &character{
+ id: id, name: fmt.Sprintf("Local Explorer %d", id),
+ playfield: 950, position: [3]float32{52.625, 14.75, 56.875 + float32((id-1)%4)*3},
rotation: [4]float32{0, 0, 0, 1}, appearance: 0x315, level: 1, profession: 1,
- geometry: server.geometry,
}
- character.stats = defaultCharacterStats(character.appearance >> 4 & 7)
- character.health = character.maximumHealth()
- server.characters[character.id] = character
- return character
+ player.stats = defaultCharacterStats(player.appearance >> 4 & 7)
+ player.health = player.maximumHealth()
+ return player
}
func (server *server) broadcast(playfield, exclude uint32, packet []byte) {
diff --git a/server/synthetic_player.go b/server/synthetic_player.go
@@ -0,0 +1,31 @@
+package main
+
+import "database/sql"
+
+type syntheticPlayerWrite struct{ player *character }
+
+func (write *syntheticPlayerWrite) persist(tx *sql.Tx) error {
+ id, err := allocatePlayerID(tx)
+ if err != nil {
+ return err
+ }
+ write.player = newPlayerCharacter(id)
+ return prepareBrowserPlayerWrite(write.player, []byte{}, []byte{}).persist(tx)
+}
+
+func (state *server) createSyntheticPlayer() (userData, error) {
+ var user userData
+ err := state.accountOperation(func(configuration *server) error {
+ write := &syntheticPlayerWrite{}
+ if err := configuration.commitWrite(write); err != nil {
+ return err
+ }
+ user = write.player.userData()
+ if state.world != nil {
+ return state.world.createPlayer(write.player)
+ }
+ state.publishBrowserPlayer_locked(write.player)
+ return nil
+ })
+ return user, err
+}
diff --git a/server/visitor_names.go b/server/visitor_names.go
@@ -90,13 +90,14 @@ func (server *server) saveVisitor_locked(player *character) error {
continue
}
// The index also protects against a competing database writer after the check.
- err = server.commitWrite(prepareBrowserPlayerWrite(player, []byte{}, []byte{}))
+ write := &allocatedPlayerWrite{player: prepareBrowserPlayerWrite(player, []byte{}, []byte{})}
+ err = server.commitWrite(write)
var constraint sqlite3.Error
if errors.As(err, &constraint) && constraint.ExtendedCode == sqlite3.ErrConstraintUnique {
continue
}
if err == nil {
- server.publishBrowserPlayer_locked(player)
+ player.id = write.player.record.Profile.ID
}
return err
}
diff --git a/server/world_operations.go b/server/world_operations.go
@@ -20,6 +20,19 @@ func (world *worldRuntime) operate(run func(*server) error) error {
}
}
+// The coordinator owns account drafts and pending native creation credentials.
+// Its callbacks finish before the next account or mission lifecycle operation.
+func (state *server) accountOperation(run func(*server) error) error {
+ if state.world != nil {
+ return state.world.operate(run)
+ }
+ state.updateMutex.Lock()
+ defer state.updateMutex.Unlock()
+ state.mutex.Lock()
+ defer state.mutex.Unlock()
+ return run(state)
+}
+
type playerCreation struct {
player *character
reply chan *worldRoute
diff --git a/server/world_runtime.go b/server/world_runtime.go
@@ -94,7 +94,10 @@ func newWorldRuntime(configuration *server, states map[uint32]*server) (*worldRu
if configuration.teamService == nil {
configuration.teamService = newTeamDirectory(configuration.databaseWriter, teams)
}
+ creations := configuration.browserCreations
+ configuration.browserCreations = nil
configuration = configuration.emptyZone()
+ configuration.browserCreations = creations
zones := make(map[uint32]*zoneRuntime)
for playfield, state := range states {
state.world, state.playfield, state.identities = world, playfield, configuration.identities