aorecomp

Anarchy Online classic in the browser

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


commit 71df73ea41e19b904bbd582d8f25e0eaba752648
parent 0c3df83d9a08b21a4cb9c170e338ed892bdb60db
Author: anon <anon@example.com>
Date:   Thu, 22 Oct 2026 10:58:35 +0000

Recover inventory through the native reclaim booth

Diffstat:
MTODO.md | 4+++-
Mdocs/combat-client-reconstruction.md | 3++-
Mdocs/insurance.md | 6++++--
Mdocs/player-resurrection.md | 7++++---
Adocs/reclaim.md | 156+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/combat.go | 8++++++++
Mserver/equipment.go | 3++-
Mserver/equipment_test.go | 2+-
Mserver/insurance.go | 14++++++++++----
Mserver/insurance_test.go | 8++++----
Mserver/inventory.go | 27+++++++++++++++++++++++----
Mserver/loot.go | 4+++-
Mserver/main.go | 8++++++--
Aserver/reclaim.go | 140+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/reclaim_test.go | 432+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/state.go | 1+
16 files changed, 799 insertions(+), 24 deletions(-)

diff --git a/TODO.md b/TODO.md @@ -135,7 +135,7 @@ recorded in [inventory behavior](docs/inventory.md). resurrection location and usable character without reloading the browser. - [x] Save a resurrection location. Check: using one save terminal persists the location and a later death returns the character there. -- [ ] Reclaim items after death. Check: the applicable items move to reclaim and +- [x] Reclaim items after death. Check: the applicable items move to reclaim and can be recovered once, including after reconnect. - [ ] Apply the classic insurance/XP-loss policy. Check: recorded before/after XP and save-point cases match the documented 14.9.1 rule. @@ -146,6 +146,8 @@ Native player return and provisional location/resources are recorded in [player resurrection](docs/player-resurrection.md). The supported scanner, saved identity and provisional arrival/fee policy are recorded in [insurance](docs/insurance.md). +Native private item retrieval, NoDrop handling and provisional collection timing +are recorded in [reclaim](docs/reclaim.md). ## Loot and credits diff --git a/docs/combat-client-reconstruction.md b/docs/combat-client-reconstruction.md @@ -88,7 +88,8 @@ unknowns for each area: | Creature respawn | Explicit provisional level-1 Leet delay; historical district units unresolved | One fresh replacement after 100 seconds; see [respawn](npc-respawn.md) | | Player resurrection | Native action 152 and Resurrect handler | Automatic native return with provisional location/resources; see [player resurrection](player-resurrection.md) | | Insurance return point | Shipped Omni-Med scanner and native Use/success response | One persistent saved scanner; arrival offset and free fee policy provisional; see [insurance](insurance.md) | -| XP, reclaim and insurance fees | Separate rules and state required | Not implemented | +| Item reclaim | Native level boundary, NoDrop cleanup and private container packets | Level-10 ordinary items persist in private reclaim; delay and retention policies provisional; see [reclaim](reclaim.md) | +| XP and insurance fees | Separate rules and state required | Not implemented | ## Implementation order and acceptance checks diff --git a/docs/insurance.md b/docs/insurance.md @@ -67,8 +67,10 @@ Socket writes occur outside the shared state mutex. A successful use completes GenericCmd and sends CharacterAction 79. Its saved XP fields are zero because durable XP progression and insurance snapshots are -not implemented. This feature saves the return location; reclaim, XP loss, -fees and shock stat penalties remain separate work. Ordinary profile edits +not implemented. This feature saves the return location; XP loss, fees and +shock stat penalties remain separate work. [Private reclaim](reclaim.md) now +handles ordinary inventory items from level 10 and prevents saving until all +reclaim items are collected. Ordinary profile edits and teleports preserve the saved scanner. Unknown scanner identities in saved profiles fail loading rather than silently selecting another location. diff --git a/docs/player-resurrection.md b/docs/player-resurrection.md @@ -67,9 +67,10 @@ equipment and inventory at the saved return point. Health and nano remain runtime state. Ordinary reconnect behavior still revives a defeated player with full health, and server restart initializes resources from the saved character profile. One insurance terminal and its saved return -are now supported; other scanners, insurance fees, item reclaim, XP loss and -resurrection shock stat penalties remain unimplemented. Inventory remains -owned across death. See the [scanner evidence and limits](insurance.md). +are now supported; other scanners, insurance fees, XP loss and resurrection +shock stat penalties remain unimplemented. Ordinary inventory items now enter +[private reclaim](reclaim.md) from level 10; equipment and NoDrop items remain +with the player. See the [scanner evidence and limits](insurance.md). ## Verification diff --git a/docs/reclaim.md b/docs/reclaim.md @@ -0,0 +1,156 @@ +# Reclaim after death + +Level 10 and higher players now send ordinary inventory items to private +reclaim storage when defeated in PvE. Equipment and NoDrop items stay with the +player. One shipped reclaim booth in Omni Entertainment supports native use, +contents, close/reopen and collection into the next free inventory slot. +Ownership and availability survive reconnect and server restart. + +The collection delay is provisionally 75 seconds from the killing blow. This +uses the native DeadTimer fallback, not a recovered historical server timer. +Uncollected items accumulate across deaths without expiry; each keeps its own +availability time. Those repeated-death and retention policies are also +provisional. XP insurance, uninsured/PvP corpse loot, backpacks and resurrection +shock penalties are separate work. + +## Shipped rules and placement + +The target is original `anarchy-vanilla-14.9.1/kkr.dll`, SHA-256 +`a37bc1c15053fdcc5572772309f7074c4f83baffe2faa164df40b059b7c480c0`. +Original addresses use base `0x10000000`; generated C uses `0x36000000`. + +- Recovery helper `0x10053230` calls inventory cleanup `0x1005fa40` only above + level 9. Cleanup iterates ordinary inventory slots beginning at native 48, + leaving equipment slots alone, and skips items with flag `0x04000000`. + Native drop check `0x1002a6e6` and trade check `0x1001fce1` independently + identify this bit as NoDrop. The starter weapon template 121567 has this bit; + Kinetic Axe 209283 and Monster Parts 42640 do not. +- Death reason handler `0x10072340` reads stat 34, DeadTimer, and substitutes + 75 seconds when it is below one. Shipped string `0x101c0020` instead says + items remain with the corpse for one minute before collection. This conflict + leaves the original server timing unresolved. +- String `0x101c00f0` says reclaim must be emptied before saving. The supported + scanner now rejects insurance while any reclaim items remain, including + items still awaiting collection. Whether the historical save restriction also + covered items awaiting corpse collection remains unresolved. +- Shipped `cd_image/text/help/Death and insurance.txt` describes a short delay + and retrieval at any reclaim terminal. It does not require the terminal + beside the saved scanner. This implementation enables one known booth; + affiliation and the player's saved scanner do not restrict reclaim use. +- Resource 1000026, instance 705, statel index 262 at payload offset 42025, + contains the 84-byte booth `51059:0xc00902c1`, XYZ + `[915, 20.2000999, 580]`, quaternion WZYX + `[0.7071073055, 0, 0.7071061730, 0]`. Template 37180, Insurance Reclaim, + uses type 51059 and mesh 55874. Its description mentions uninsured items + and the reach of reclaim bots without defining those routing rules. + +Fresh native evidence is exported in +`local/reports/reclaim-1491-evidence.json`. Important records are: + +| Observation | Evidence | +| --- | --- | +| Inventory cleanup | `ev_87f71e020ce431375897aaf4b4252a4941b273a5a0903c88c7dcafbbb5bc204d` | +| NoDrop drop check | `ev_547b11d20dc910631449b1fb5632aae40248137f1549a6288d68d549f407dc9f` | +| Level boundary | `ev_1b21acc396ea4989a9ac1e27ebab5fb938fd43da7c23b1a2356a09892e2d2de3` | +| Booth Use | `ev_06f39d9fd1879e171e9c2d604df319f9c7708fa05d2892d92c23c979ecc06f39` | +| Private inventory reader | `ev_78bdaa1170c391535fdb4e71f7ba9506978fd5044a6a8efd6b7c827eb342d9e4` | +| Private inventory activation | `ev_2ee904fa8143419f5ef800199e974fc3ff4c69b8298f34bc7b530c86b22408b2` | +| Native capacity bound | `ev_8a79ec83e7157a3eb923b942f4e96cff697bd171a48122cc9e4804e5dfccb3db` | +| Close receiver | `ev_2246a9df35b3d8df1881e1e0f5dfff95176879777cac8b7bef8d0caed53fe059` | + +## Native wire contract + +Right-click first sends GenericCmd Use (`0x52526858`) for the booth. Its +successful acknowledgement schedules native Use through `0x10087a70`, +`0x1004ccc0` and `0x1004d780`. Booth implementation `0x1009b260` then emits +CharacterAction 109 with zero identity arguments. Closing an existing window +follows the same Use path and emits CharacterAction 110. These actions carry +no booth identity, so the server checks proximity to the supported booth. + +`BankCorpseIIR_t`, key `0x52213420`, opens the private container. Reader +`0x1007d1a0` delegates to proxy reader `0x101516d0` and inventory reader +`0x1002dba0`. Its payload starts with `(entryCount + 1) * 1009`, followed by +32-byte entries: slot, uint16 flags, uint16 count, item identity, low/high +templates, quality and auxiliary value. Entries use flags 3, count 1 and zero +auxiliary value, as in the native corpse template-proxy transfer. A final +uint32 supplies the private proxy instance, currently the owner's character +ID. The envelope identifies that owner as type 50000. + +Activation `0x1007d210` installs the proxy of type 57006 and opens its native +window through `0x100530c0`. The proxy constructor creates 100 slots; +`0x1002db10` discards entries outside that bound. Each opening therefore shows +at most 100 currently available items. Further items remain durable and can +appear after collection and reopening. This bounds the native packet without +claiming the original server's storage limit or overflow policy. + +Left-clicking a displayed item sends `ContainerAddItem`, key `0x47537a24`: +source `(106, windowSlot)`, destination owner `(50000, playerID)`, and slot +sentinel 111. The successful reply substitutes the chosen empty inventory slot, +translated into the native 48..77 range. This removes the reclaim icon and +adds the same item to inventory. CharacterAction 110 closes and unregisters +the private window via `0x1005dc40` and `0x10053160`. + +## Persistence and validation + +`inventory.yaml` contains both ordinary `items` and optional `reclaim` entries. +Each reclaim entry contains the complete owned item plus `available_at`. +`last_id` covers both locations, and loading rejects duplicate identities +within or across them. The item's old inventory slot is retained as metadata; +collection selects a currently free slot. Repeated deaths can therefore retain +items that occupied the same old slot without treating them as duplicates. + +A lethal hit saves the inventory/reclaim transfer before changing health or +publishing death. Failed persistence logs the error, cancels the fight and +leaves the player alive with the original items. Retrieval saves both sides in +one atomic file replacement before its move reply. Full inventory, failed +writes, repeated pickups and stale sessions keep the source unchanged. +Ordinary grants, moves, deletion, equipment changes and corpse loot preserve +pending reclaim entries. + +Each open window retains a fixed mapping from its native slots to owned item +IDs. Taking an item clears its mapping entry rather than shifting another item +into the same slot. Duplicate opens do not replace that mapping. The server +checks current loaded/alive session, actor and destination ownership, readiness, +availability, open window and five-metre three-dimensional booth range. +Reclaim messages are private to the requesting owner. State changes use the +normal update/state lock order; packet sends occur after releasing the state +mutex. + +## Verification + +`server/reclaim_test.go` covers the level 9/10 boundary, equipment/NoDrop +retention, persisted delay, failed death saves, native private contents and +pickup packets, restart, invalid sessions/identities/range, full inventory, +failed pickup saves, concurrent/repeated pickup, stable window slots, inventory +transaction preservation, pools larger than the native window and insurance +rejection with unclaimed items. A native wire round trip exercises GenericCmd, +CharacterAction 109/110 and page 106 pickup through normal server dispatch. + +Two published WASM clients exercised the shipped booth. A fixture supplied a +level-10 player with equipped axe ID 1 (template 209283), ordinary Monster Parts +ID 100 (42640), and NoDrop starter weapon ID 101 (121567). At the starter fight +location the low-health player attacked the profiled Leet and died to its +retaliation. Native resurrection returned to the saved scanner without a page +reload. Only ID 100 entered reclaim; the other two items remained owned. +The native death message displayed the 75-second fallback. + +A native opening before the deadline showed an empty window while the pending +item stayed in the saved inventory file. Server restart and browser reconnect +retained its identity and deadline. After availability, the owner saw Monster +Parts while the second player's private window stayed empty. Native left-click +sent page 106 pickup and recovered the same ID 100 into logical slot 64; +repeated empty-slot clicks did not create another copy. Another restart retained +all three owned identities and an empty reclaim window. Screenshots also show +the retained equipped weapon and both final inventory icons. + +There were zero page errors and 30 connection-refused console messages during +the two intentional restarts. No client adapter change was required. Test-owned +browser contexts and servers were closed before the full Go checks. Evidence +is under `local/reclaim-death-smoke/`: `verification.json`, `tmp_verify.py`, +`encounter-packets.log`, `retrieval-packets.log`, saved pending/recovered +inventory snapshots, and per-step PNG/JSON files. The earlier wire-only probe +is under `local/reclaim-smoke/`. + +The final maintained suite, `go test ./server/...`, passed. Focused race checks +passed for `TestReclaim`, `TestInsurance`, `TestResurrection`, `TestLoot` and +`TestEquipment`, including concurrent pickup and shared Use sequencing. diff --git a/server/combat.go b/server/combat.go @@ -232,6 +232,13 @@ func (server *server) advanceCombat(now time.Time) { damage = 5 } damage = min(damage, target.health) + if damage == target.health && !target.npc { + if err := server.collectReclaim_locked(target, now); err != nil { + log.Printf("Reclaim: %v", err) + server.cancelCombat_locked(target.id, updates) + continue + } + } target.health -= damage attack, recharge := attacker.attackDelays() attacker.rechargeUntil = now.Add(recharge) @@ -246,6 +253,7 @@ func (server *server) advanceCombat(now time.Time) { client := server.clients[target.id] target.position = predictedPosition_locked(target, client, now) client.forward = 0 + client.reclaimItems = nil } server.cancelCombat_locked(target.id, updates) server.queueCombat_locked(updates, target, target, deathPacket(target)) diff --git a/server/equipment.go b/server/equipment.go @@ -126,7 +126,8 @@ func (server *server) advanceEquipment(now time.Time) { } // Save the entire move before publishing inventory or appearance changes. - inventory := playerInventory{LastID: character.inventory.LastID, Items: slices.Clone(character.inventory.Items)} + inventory := character.inventory + inventory.Items = slices.Clone(character.inventory.Items) inventory.Items[index].Slot = move.destination if err := server.saveInventory_locked(character, inventory); err != nil { log.Printf("Equipment: %v", err) diff --git a/server/equipment_test.go b/server/equipment_test.go @@ -162,7 +162,7 @@ func TestEquipmentFullInventoryDoesNotLoseEquippedWeapon(t *testing.T) { t.Fatalf("fill inventory: %v %v", granted, err) } } - before := playerInventory{world.characters[1].inventory.LastID, append([]ownedItem(nil), world.characters[1].inventory.Items...)} + before := playerInventory{LastID: world.characters[1].inventory.LastID, Items: append([]ownedItem(nil), world.characters[1].inventory.Items...)} err := world.handleInventory(world.clients[1], itemMovePacket(1, 6, 111)[20:]) diff --git a/server/insurance.go b/server/insurance.go @@ -5,7 +5,7 @@ import ( "time" ) -func (server *server) handleInsuranceUse(client *worldClient, body []byte) error { +func (server *server) handleTerminalUse(client *worldClient, body []byte) error { server.updateMutex.Lock() defer server.updateMutex.Unlock() server.mutex.Lock() @@ -31,7 +31,13 @@ func (server *server) handleInsuranceUse(client *worldClient, body []byte) error accepted := client.target && player.playfield == 705 && player.appearance>>9&3 == 2 && binary.BigEndian.Uint32(body[40:44]) == 51005 && binary.BigEndian.Uint32(body[44:48]) == 0xc00202c1 && x*x+y*y+z*z <= 5*5 - if accepted { + reclaim := binary.BigEndian.Uint32(body[40:44]) == 51059 + if reclaim { + accepted = client.target && binary.BigEndian.Uint32(body[44:48]) == 0xc00902c1 && server.nearReclaim_locked(client) + } else { + accepted = accepted && len(player.inventory.Reclaim) == 0 + } + if accepted && !reclaim { // Persist the scanner before acknowledging use or changing live state. updated := *player updated.resurrectionTerminal = 0xc00202c1 @@ -43,7 +49,7 @@ func (server *server) handleInsuranceUse(client *worldClient, body []byte) error } server.mutex.Unlock() - // GenericCmd completes the use; CharacterAction 79 confirms the save. + // Complete native Use before sending any insurance confirmation. reply := append([]byte(nil), body[16:]...) binary.BigEndian.PutUint32(reply, 2) if accepted { @@ -52,7 +58,7 @@ func (server *server) handleInsuranceUse(client *worldClient, body []byte) error if err := client.send(n3Packet(0x52526858, 50000, client.id, reply)); err != nil { return err } - if accepted { + if accepted && !reclaim { var action []byte for _, value := range []uint32{79, 0, 0, 0, 0} { action = binary.BigEndian.AppendUint32(action, value) diff --git a/server/insurance_test.go b/server/insurance_test.go @@ -113,7 +113,7 @@ func TestInsuranceRejectsInvalidUseWithoutSaving(t *testing.T) { client.target = false } - if err := world.handleInsuranceUse(client, body); err != nil { + if err := world.handleTerminalUse(client, body); err != nil { t.Fatal(err) } @@ -147,14 +147,14 @@ func TestInsuranceRepeatedUsesShareTheGenericCommandSequence(t *testing.T) { var uses sync.WaitGroup for range 8 { uses.Go(func() { - if err := world.handleInsuranceUse(client, insuranceUseRequest(2)[20:]); err != nil { + if err := world.handleTerminalUse(client, insuranceUseRequest(2)[20:]); err != nil { t.Error(err) } }) } uses.Wait() world.handleLootUse(client, lootUseRequest(1)) - world.handleInsuranceUse(client, insuranceUseRequest(1)[20:]) + world.handleTerminalUse(client, insuranceUseRequest(1)[20:]) if len(conn.packets) != 2 || client.useSequence != 2 || player.resurrectionTerminal != 0xc00202c1 { t.Fatal("repeated or older use replayed insurance acknowledgement") @@ -172,7 +172,7 @@ func TestInsuranceSaveFailureDoesNotAcknowledgeOrChangeThePoint(t *testing.T) { t.Fatal(err) } - err := world.handleInsuranceUse(world.clients[1], insuranceUseRequest(1)[20:]) + err := world.handleTerminalUse(world.clients[1], insuranceUseRequest(1)[20:]) if err == nil || len(conn.packets) != 0 || player.resurrectionTerminal != 0 || player.savedProfile.ResurrectionTerminal != 0 { t.Fatal("failed save changed or acknowledged the scanner") diff --git a/server/inventory.go b/server/inventory.go @@ -5,6 +5,7 @@ import ( "encoding/binary" "fmt" "slices" + "time" "go.yaml.in/yaml/v3" ) @@ -17,9 +18,15 @@ type ownedItem struct { Slot uint32 `yaml:"slot"` } +type reclaimItem struct { + Item ownedItem `yaml:"item"` + AvailableAt time.Time `yaml:"available_at"` +} + type playerInventory struct { - LastID uint32 `yaml:"last_id"` - Items []ownedItem `yaml:"items"` + LastID uint32 `yaml:"last_id"` + Items []ownedItem `yaml:"items"` + Reclaim []reclaimItem `yaml:"reclaim,omitempty"` } func (inventory playerInventory) validate() error { @@ -33,6 +40,12 @@ func (inventory playerInventory) validate() error { } ids[item.ID], slots[item.Slot] = true, true } + for _, entry := range inventory.Reclaim { + if entry.Item.ID == 0 || entry.Item.ID > inventory.LastID || ids[entry.Item.ID] || entry.Item.Slot < 64 || entry.Item.Slot >= 94 { + return fmt.Errorf("invalid reclaim item identity or slot") + } + ids[entry.Item.ID] = true + } return nil } @@ -68,7 +81,9 @@ func (server *server) grantItem_locked(character *character, template uint32) (b } // Publish the new identity only after the complete inventory reaches disk. - inventory := playerInventory{LastID: server.nextItem + 1, Items: slices.Clone(character.inventory.Items)} + inventory := character.inventory + inventory.LastID = server.nextItem + 1 + inventory.Items = slices.Clone(character.inventory.Items) inventory.Items = append(inventory.Items, ownedItem{inventory.LastID, definition.HeaderWords[0], template, *definition.Quality, slot}) if err := server.saveInventory_locked(character, inventory); err != nil { return false, err @@ -82,6 +97,9 @@ func (server *server) handleInventory(client *worldClient, body []byte) error { if len(body) != 36 { return fmt.Errorf("invalid inventory message length") } + if key == 0x47537a24 && binary.BigEndian.Uint32(body[16:20]) == 106 { + return server.takeReclaim(client, body) + } server.updateMutex.Lock() defer server.updateMutex.Unlock() server.mutex.Lock() @@ -113,7 +131,8 @@ func (server *server) handleInventory(client *worldClient, body []byte) error { if sourceSlot == 6 { return nil } - inventory := playerInventory{LastID: character.inventory.LastID, Items: slices.Clone(character.inventory.Items)} + inventory := character.inventory + inventory.Items = slices.Clone(character.inventory.Items) if key == 0x47537a24 { destination := binary.BigEndian.Uint32(body[32:36]) if binary.BigEndian.Uint32(body[24:28]) != 50000 || binary.BigEndian.Uint32(body[28:32]) != client.id || diff --git a/server/loot.go b/server/loot.go @@ -168,7 +168,9 @@ func (server *server) takeLoot_locked(client *worldClient, body []byte) error { // Persist the new owner before removing the corpse item or publishing its move. item := corpse.corpse.items[index] item.Slot = slot - inventory := playerInventory{LastID: max(player.inventory.LastID, item.ID), Items: append(slices.Clone(player.inventory.Items), item)} + inventory := player.inventory + inventory.LastID = max(player.inventory.LastID, item.ID) + inventory.Items = append(slices.Clone(player.inventory.Items), item) if err := server.saveInventory_locked(player, inventory); err != nil { return err } diff --git a/server/main.go b/server/main.go @@ -407,8 +407,8 @@ func (server *server) serveWorldClient(client *worldClient) error { switch binary.BigEndian.Uint32(body[0:4]) { case 0x52526858: var err error - if len(body) == 48 && binary.BigEndian.Uint32(body[40:44]) == 51005 { - err = server.handleInsuranceUse(client, body) + if len(body) == 48 && (binary.BigEndian.Uint32(body[40:44]) == 51005 || binary.BigEndian.Uint32(body[40:44]) == 51059) { + err = server.handleTerminalUse(client, body) } else { err = server.handleLootUse(client, body) } @@ -432,6 +432,10 @@ func (server *server) serveWorldClient(client *worldClient) error { return fmt.Errorf("short character action message") } switch binary.BigEndian.Uint32(body[16:20]) { + case 109, 110: + if err := server.handleReclaim(client, body); err != nil { + return err + } case 152: if err := server.handleResurrection(client, body); err != nil { return err diff --git a/server/reclaim.go b/server/reclaim.go @@ -0,0 +1,140 @@ +package main + +import ( + "ao/server/gamedata" + "encoding/binary" + "slices" + "time" +) + +func (server *server) collectReclaim_locked(player *character, now time.Time) error { + if player.level < 10 { + return nil + } + + // kkr.dll FUN_1005fa40 retains equipment and items with the NoDrop flag. + inventory := player.inventory + inventory.Items = nil + inventory.Reclaim = slices.Clone(player.inventory.Reclaim) + for _, item := range player.inventory.Items { + if item.Slot < 64 || itemStat(gamedata.ItemTemplates[item.Template], 0)&0x04000000 != 0 { + inventory.Items = append(inventory.Items, item) + } else { + // The native DeadTimer fallback is provisional until server timing is known. + inventory.Reclaim = append(inventory.Reclaim, reclaimItem{item, now.Add(75 * time.Second)}) + } + } + if len(inventory.Reclaim) == len(player.inventory.Reclaim) { + return nil + } + return server.saveInventory_locked(player, inventory) +} + +func (server *server) nearReclaim_locked(client *worldClient) bool { + player := server.characters[client.id] + position := predictedPosition_locked(player, client, time.Now()) + x, y, z := position[0]-915, position[1]-20.2001, position[2]-580 + return player.playfield == 705 && x*x+y*y+z*z <= 5*5 +} + +func reclaimInventoryPacket(player *character, slots []uint32) []byte { + body := binary.BigEndian.AppendUint32(nil, uint32(len(slots)+1)*1009) + for slot, id := range slots { + index := slices.IndexFunc(player.inventory.Reclaim, func(entry reclaimItem) bool { return entry.Item.ID == id }) + item := player.inventory.Reclaim[index].Item + for _, value := range []uint32{uint32(slot), 0x00030001, item.Type, item.ID, item.Template, item.Template, item.Quality, 0} { + body = binary.BigEndian.AppendUint32(body, value) + } + } + body = binary.BigEndian.AppendUint32(body, player.id) + return n3Packet(0x52213420, 50000, player.id, body) +} + +func (server *server) handleReclaim(client *worldClient, body []byte) error { + server.updateMutex.Lock() + defer server.updateMutex.Unlock() + server.mutex.Lock() + player := server.characters[client.id] + if !client.target || server.clients[client.id] != client || !client.ready || client.loading || player.health == 0 || + binary.BigEndian.Uint32(body[4:8]) != 50000 || binary.BigEndian.Uint32(body[8:12]) != client.id || + binary.BigEndian.Uint32(body[20:24]) != 0 || binary.BigEndian.Uint32(body[24:28]) != 0 || + binary.BigEndian.Uint32(body[28:32]) != 0 || binary.BigEndian.Uint32(body[32:36]) != 0 { + server.mutex.Unlock() + return nil + } + var packet []byte + if binary.BigEndian.Uint32(body[16:20]) == 110 { + if client.reclaimItems != nil { + client.reclaimItems = nil + packet = n3Packet(0x5e477770, 50000, client.id, body[16:]) + } + } else if client.reclaimItems == nil && server.nearReclaim_locked(client) { + // Snapshot at most the native proxy's 100 slots; pending items stay durable. + client.reclaimItems = make([]uint32, 0, 100) + now := time.Now() + for _, entry := range player.inventory.Reclaim { + if !now.Before(entry.AvailableAt) { + client.reclaimItems = append(client.reclaimItems, entry.Item.ID) + if len(client.reclaimItems) == 100 { + break + } + } + } + packet = reclaimInventoryPacket(player, client.reclaimItems) + } + server.mutex.Unlock() + if packet != nil { + return client.send(packet) + } + return nil +} + +func (server *server) takeReclaim(client *worldClient, body []byte) error { + server.updateMutex.Lock() + defer server.updateMutex.Unlock() + server.mutex.Lock() + player := server.characters[client.id] + source := binary.BigEndian.Uint32(body[20:24]) + if !client.target || server.clients[client.id] != client || !client.ready || client.loading || player.health == 0 || client.equipment != nil || + binary.BigEndian.Uint32(body[4:8]) != 50000 || binary.BigEndian.Uint32(body[8:12]) != client.id || + binary.BigEndian.Uint32(body[24:28]) != 50000 || binary.BigEndian.Uint32(body[28:32]) != client.id || + binary.BigEndian.Uint32(body[32:36]) != 111 || source >= uint32(len(client.reclaimItems)) || + client.reclaimItems[source] == 0 || !server.nearReclaim_locked(client) { + server.mutex.Unlock() + return nil + } + index := slices.IndexFunc(player.inventory.Reclaim, func(entry reclaimItem) bool { return entry.Item.ID == client.reclaimItems[source] }) + if index < 0 || time.Now().Before(player.inventory.Reclaim[index].AvailableAt) { + server.mutex.Unlock() + return nil + } + var slot uint32 + for slot = 64; slot < 94; slot++ { + if !slices.ContainsFunc(player.inventory.Items, func(item ownedItem) bool { return item.Slot == slot }) { + break + } + } + if slot == 94 { + server.mutex.Unlock() + return nil + } + + // Both sides of the transfer commit in one file before the native move reply. + inventory := player.inventory + item := inventory.Reclaim[index].Item + item.Slot = slot + inventory.Items = append(slices.Clone(inventory.Items), item) + inventory.Reclaim = slices.Delete(slices.Clone(inventory.Reclaim), index, index+1) + if len(inventory.Reclaim) == 0 { + inventory.Reclaim = nil + } + if err := server.saveInventory_locked(player, inventory); err != nil { + server.mutex.Unlock() + return err + } + client.reclaimItems[source] = 0 + reply := append([]byte(nil), body[16:]...) + binary.BigEndian.PutUint32(reply[16:20], slot) + server.mutex.Unlock() + return client.send(n3Packet(0x47537a24, 50000, client.id, reply)) +} diff --git a/server/reclaim_test.go b/server/reclaim_test.go @@ -0,0 +1,432 @@ +package main + +import ( + "encoding/binary" + "os" + "reflect" + "slices" + "strconv" + "sync" + "testing" + "time" +) + +func reclaimRequest(action uint32) []byte { + var body []byte + for _, value := range []uint32{action, 0, 0, 0, 0} { + body = binary.BigEndian.AppendUint32(body, value) + } + return n3Packet(0x5e477770, 50000, 1, body)[20:] +} + +func reclaimTakeRequest(slot uint32) []byte { + var body []byte + for _, value := range []uint32{106, slot, 50000, 1, 111} { + body = binary.BigEndian.AppendUint32(body, value) + } + return n3Packet(0x47537a24, 50000, 1, body)[20:] +} + +func newReclaimWorld(t *testing.T) (*server, *combatTestConn) { + t.Helper() + t.Chdir(t.TempDir()) + world, conn := newCombatWorld() + player := world.characters[1] + player.name, player.level, player.appearance = "Reclaimer", 10, 0x515 + player.playfield, player.position, player.rotation = 705, [3]float32{918, 20.7, 578}, [4]float32{0, 0, 0, 1} + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + player.inventory = playerInventory{LastID: 3, Items: []ownedItem{ + {1, 51018, 209283, 1, 6}, {2, 51018, 121567, 1, 64}, {3, 51005, 42640, 1, 65}, + }} + world.nextItem = 3 + if err := world.saveInventory_locked(player, player.inventory); err != nil { + t.Fatal(err) + } + return world, conn +} + +func defeatReclaimPlayer(t *testing.T, world *server) time.Time { + t.Helper() + player, npc := world.characters[1], world.characters[1000000] + player.health = 1 + npc.playfield, npc.position = player.playfield, player.position + if err := world.handleCombat(world.clients[1], attackPacket(1, 1000000)[20:]); err != nil { + t.Fatal(err) + } + world.advanceCombat(player.nextAttack) + fatal := npc.nextAttack + world.advanceCombat(fatal) + return fatal +} + +func TestReclaimDeathKeepsEquipmentAndNoDropAtLevelTen(t *testing.T) { + for _, level := range []uint16{9, 10} { + t.Run(strconv.Itoa(int(level)), func(t *testing.T) { + world, _ := newReclaimWorld(t) + player := world.characters[1] + player.level = level + before := slices.Clone(player.inventory.Items) + + fatal := defeatReclaimPlayer(t, world) + restarted := newTestInventoryServer(t) + + if player.health != 0 { + t.Fatal("player survived lethal combat") + } + if level == 9 { + if !reflect.DeepEqual(player.inventory.Items, before) || len(player.inventory.Reclaim) != 0 { + t.Fatal("level nine lost items") + } + } else { + if !reflect.DeepEqual(player.inventory.Items, before[:2]) || len(player.inventory.Reclaim) != 1 || + player.inventory.Reclaim[0].Item != before[2] || !player.inventory.Reclaim[0].AvailableAt.Equal(fatal.Add(75*time.Second)) { + t.Fatalf("incorrect death collection: %+v", player.inventory) + } + } + saved := restarted.characters[1].inventory + if !reflect.DeepEqual(player.inventory.Items, saved.Items) || len(player.inventory.Reclaim) != len(saved.Reclaim) || restarted.nextItem != 3 { + t.Fatal("death collection did not persist") + } + if level == 10 && (saved.Reclaim[0].Item != before[2] || !saved.Reclaim[0].AvailableAt.Equal(fatal.Add(75*time.Second))) { + t.Fatal("pending reclaim changed on restart") + } + }) + } +} + +func TestReclaimFailedDeathSaveDoesNotKillOrLoseItems(t *testing.T) { + world, _ := newReclaimWorld(t) + before := world.characters[1].inventory + if err := os.Remove("data/players/1/inventory.yaml"); err != nil { + t.Fatal(err) + } + if err := os.Mkdir("data/players/1/inventory.yaml", 0700); err != nil { + t.Fatal(err) + } + + defeatReclaimPlayer(t, world) + + if world.characters[1].health != 1 || !reflect.DeepEqual(world.characters[1].inventory, before) || len(world.fighting) != 0 { + t.Fatal("failed persistence partially committed death") + } +} + +func TestReclaimPendingThenPrivatePickupPersistsOnce(t *testing.T) { + world, conn := newReclaimWorld(t) + player, client := world.characters[1], world.clients[1] + defeatReclaimPlayer(t, world) + player.health = 1 + + world.handleReclaim(client, reclaimRequest(109)) + pending := conn.packets[len(conn.packets)-1] + world.handleReclaim(client, reclaimRequest(110)) + inventory := player.inventory + inventory.Reclaim = slices.Clone(inventory.Reclaim) + inventory.Reclaim[0].AvailableAt = time.Now().Add(-time.Second).UTC() + if err := world.saveInventory_locked(player, inventory); err != nil { + t.Fatal(err) + } + world.handleReclaim(client, reclaimRequest(109)) + contents := conn.packets[len(conn.packets)-1] + if err := world.handleInventory(client, reclaimTakeRequest(0)); err != nil { + t.Fatal(err) + } + moved := conn.packets[len(conn.packets)-1] + count := len(conn.packets) + world.handleInventory(client, reclaimTakeRequest(0)) + restarted := newTestInventoryServer(t) + + if binary.BigEndian.Uint32(pending[16:20]) != 0x52213420 || binary.BigEndian.Uint32(pending[29:33]) != 1009 || + binary.BigEndian.Uint32(contents[29:33]) != 2018 || binary.BigEndian.Uint32(contents[45:49]) != 3 || binary.BigEndian.Uint32(contents[65:69]) != 1 { + t.Fatalf("incorrect native private contents: %x %x", pending, contents) + } + if binary.BigEndian.Uint32(moved[16:20]) != 0x47537a24 || binary.BigEndian.Uint32(moved[29:33]) != 106 || binary.BigEndian.Uint32(moved[45:49]) != 49 { + t.Fatalf("incorrect native pickup: %x", moved) + } + expected := ownedItem{3, 51005, 42640, 1, 65} + if len(player.inventory.Items) != 3 || player.inventory.Items[2] != expected || len(player.inventory.Reclaim) != 0 || len(conn.packets) != count || + !reflect.DeepEqual(player.inventory, restarted.characters[1].inventory) { + t.Fatal("pickup lost or duplicated an item") + } +} + +func TestReclaimRejectsInvalidOpenAndPickup(t *testing.T) { + for _, scenario := range []string{"foreign actor", "foreign destination", "loading", "unready", "replaced", "dead", "far", "zone", "closed", "empty slot", "wrong destination", "11.0", "pending"} { + t.Run(scenario, func(t *testing.T) { + world, conn := newReclaimWorld(t) + player, client := world.characters[1], world.clients[1] + player.inventory.Reclaim = []reclaimItem{{ownedItem{4, 51005, 42640, 1, 65}, time.Now().Add(-time.Second)}} + player.inventory.LastID = 4 + world.handleReclaim(client, reclaimRequest(109)) + request := reclaimTakeRequest(0) + switch scenario { + case "foreign actor": + binary.BigEndian.PutUint32(request[8:12], 2) + case "foreign destination": + binary.BigEndian.PutUint32(request[28:32], 2) + case "loading": + client.loading = true + case "unready": + client.ready = false + case "replaced": + world.clients[1] = &worldClient{id: 1} + case "dead": + player.health = 0 + case "far": + player.position[0] = 930 + case "zone": + player.playfield = 950 + case "closed": + client.reclaimItems = nil + case "empty slot": + binary.BigEndian.PutUint32(request[20:24], 1) + case "wrong destination": + binary.BigEndian.PutUint32(request[32:36], 64) + case "11.0": + client.target = false + case "pending": + player.inventory.Reclaim[0].AvailableAt = time.Now().Add(time.Hour) + } + before := player.inventory + before.Reclaim = slices.Clone(before.Reclaim) + conn.packets = nil + + err := world.handleInventory(client, request) + client.reclaimItems = nil + world.handleReclaim(client, reclaimRequest(109)) + + if err != nil || !reflect.DeepEqual(before, player.inventory) { + t.Fatalf("invalid pickup changed ownership: %v", err) + } + if scenario == "loading" || scenario == "unready" || scenario == "replaced" || scenario == "dead" || scenario == "far" || scenario == "zone" || scenario == "11.0" { + if len(conn.packets) != 0 { + t.Fatal("invalid user opened reclaim") + } + } + }) + } +} + +func TestReclaimFullInventoryAndFailedPickupSaveRetainSource(t *testing.T) { + for _, scenario := range []string{"full", "failed save"} { + t.Run(scenario, func(t *testing.T) { + world, conn := newReclaimWorld(t) + player, client := world.characters[1], world.clients[1] + player.inventory.Reclaim = []reclaimItem{{ownedItem{4, 51005, 42640, 1, 65}, time.Now().Add(-time.Second)}} + player.inventory.LastID = 4 + world.nextItem = 4 + if scenario == "full" { + for len(player.inventory.Items) < 31 { + world.grantItem_locked(player, 42640) + } + } else { + os.Remove("data/players/1/inventory.yaml") + os.Mkdir("data/players/1/inventory.yaml", 0700) + } + world.handleReclaim(client, reclaimRequest(109)) + before := player.inventory + conn.packets = nil + + err := world.handleInventory(client, reclaimTakeRequest(0)) + + if (scenario == "failed save") != (err != nil) || !reflect.DeepEqual(before, player.inventory) || len(conn.packets) != 0 || client.reclaimItems[0] != 4 { + t.Fatalf("failed pickup lost its source: %v", err) + } + }) + } +} + +func TestReclaimConcurrentPickupKeepsOtherWindowSlotsStable(t *testing.T) { + world, _ := newReclaimWorld(t) + player, client := world.characters[1], world.clients[1] + player.inventory.LastID = 5 + player.inventory.Reclaim = []reclaimItem{ + {ownedItem{4, 51005, 42640, 1, 65}, time.Now().Add(-time.Second)}, + {ownedItem{5, 51005, 42640, 1, 65}, time.Now().Add(-time.Second)}, + } + world.handleReclaim(client, reclaimRequest(109)) + var group sync.WaitGroup + + for range 8 { + group.Add(1) + go func() { + defer group.Done() + if err := world.handleInventory(client, reclaimTakeRequest(0)); err != nil { + t.Error(err) + } + }() + } + group.Wait() + world.handleReclaim(client, reclaimRequest(109)) + + if len(player.inventory.Items) != 4 || player.inventory.Items[3].ID != 4 || len(player.inventory.Reclaim) != 1 || player.inventory.Reclaim[0].Item.ID != 5 || + !reflect.DeepEqual(client.reclaimItems, []uint32{0, 5}) { + t.Fatal("repeated pickup consumed another window slot") + } +} + +func TestReclaimSurvivesOtherInventoryTransactions(t *testing.T) { + for _, operation := range []string{"grant", "move", "delete", "equipment", "loot"} { + t.Run(operation, func(t *testing.T) { + world, _ := newReclaimWorld(t) + player, client := world.characters[1], world.clients[1] + player.inventory.LastID = 4 + player.inventory.Reclaim = []reclaimItem{{ownedItem{4, 51005, 42640, 1, 65}, time.Now().Add(time.Minute).UTC()}} + world.nextItem = 4 + expected := slices.Clone(player.inventory.Reclaim) + + switch operation { + case "grant": + if granted, err := world.grantItem_locked(player, 42640); err != nil || !granted { + t.Fatalf("grant: %v %v", granted, err) + } + case "move": + if err := world.handleInventory(client, inventoryMovePacket(1, 65, 93)[20:]); err != nil { + t.Fatal(err) + } + case "delete": + if err := world.handleInventory(client, inventoryDeletePacket(1, 64)[20:]); err != nil { + t.Fatal(err) + } + case "equipment": + if err := world.handleInventory(client, itemMovePacket(1, 6, 93)[20:]); err != nil { + t.Fatal(err) + } + if client.equipment == nil { + t.Fatal("unequip did not start") + } + world.advanceEquipment(client.equipment.readyAt) + case "loot": + npc := world.characters[1000000] + npc.health, npc.playfield, npc.position = 0, player.playfield, player.position + npc.corpse = &npcCorpse{looter: 1, items: []ownedItem{{ID: 17, Type: 51005, Template: 42640, Quality: 1}}} + client.lootCorpse = npc.id + if err := world.handleInventory(client, lootTakeRequest()); err != nil { + t.Fatal(err) + } + } + restarted := newTestInventoryServer(t) + + if !reflect.DeepEqual(expected, player.inventory.Reclaim) || !reflect.DeepEqual(expected, restarted.characters[1].inventory.Reclaim) { + t.Fatal("inventory transaction erased pending reclaim") + } + }) + } +} + +func TestReclaimLargePoolRemainsAvailableAcrossWindows(t *testing.T) { + world, _ := newReclaimWorld(t) + player, client := world.characters[1], world.clients[1] + player.inventory.LastID = 104 + for id := uint32(4); id <= 104; id++ { + player.inventory.Reclaim = append(player.inventory.Reclaim, reclaimItem{ownedItem{id, 51005, 42640, 1, 65}, time.Now().Add(-time.Second)}) + } + + world.handleReclaim(client, reclaimRequest(109)) + if len(client.reclaimItems) != 100 || client.reclaimItems[99] != 103 { + t.Fatal("private proxy exceeded 100 slots") + } + world.handleInventory(client, reclaimTakeRequest(0)) + world.handleReclaim(client, reclaimRequest(110)) + world.handleReclaim(client, reclaimRequest(109)) + + if len(player.inventory.Reclaim) != 100 || len(client.reclaimItems) != 100 || client.reclaimItems[0] != 5 || client.reclaimItems[99] != 104 { + t.Fatal("items beyond the native window capacity were lost or inaccessible") + } +} + +func TestReclaimPreventsInsuranceUntilEmptied(t *testing.T) { + world, conn := newReclaimWorld(t) + player := world.characters[1] + player.inventory.Reclaim = []reclaimItem{{ownedItem{4, 51005, 42640, 1, 65}, time.Now().Add(-time.Second)}} + + err := world.handleTerminalUse(world.clients[1], insuranceUseRequest(1)[20:]) + + if err != nil || player.resurrectionTerminal != 0 || len(conn.packets) != 1 || binary.BigEndian.Uint32(conn.packets[0][29:33]) != 2 { + t.Fatal("scanner accepted insurance with unclaimed items") + } +} + +func TestReclaimNativeWireRoundTripAndRestart(t *testing.T) { + useNPCData(t, testNPCData()) + world := newTestServer(t) + player := world.newCharacter() + player.playfield, player.position = 705, [3]float32{918, 20.7, 578} + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + player.inventory = playerInventory{LastID: 17, Reclaim: []reclaimItem{{ownedItem{17, 51005, 42640, 1, 64}, time.Now().Add(-time.Second).UTC()}}} + if err := world.saveInventory_locked(player, player.inventory); err != nil { + t.Fatal(err) + } + connection := connectZoningClient(t, world, true) + use := insuranceUseRequest(1) + binary.BigEndian.PutUint32(use[60:64], 51059) + binary.BigEndian.PutUint32(use[64:68], 0xc00902c1) + + connection.Write(targetPacket(use)) + acknowledged, err := readPacket(connection) + if err != nil { + t.Fatal(err) + } + connection.Write(targetPacket(n3Packet(0x5e477770, 50000, 1, reclaimRequest(109)[16:]))) + contents, err := readPacket(connection) + if err != nil { + t.Fatal(err) + } + connection.Write(targetPacket(n3Packet(0x47537a24, 50000, 1, reclaimTakeRequest(0)[16:]))) + moved, err := readPacket(connection) + if err != nil { + t.Fatal(err) + } + connection.Write(targetPacket(n3Packet(0x5e477770, 50000, 1, reclaimRequest(110)[16:]))) + closed, err := readPacket(connection) + if err != nil { + t.Fatal(err) + } + connection.Close() + restarted := newTestInventoryServer(t) + + if binary.BigEndian.Uint32(acknowledged[16:20]) != 0x52526858 || binary.BigEndian.Uint32(acknowledged[29:33]) != 1 || + binary.BigEndian.Uint32(contents[16:20]) != 0x52213420 || binary.BigEndian.Uint32(contents[45:49]) != 17 || + binary.BigEndian.Uint32(moved[16:20]) != 0x47537a24 || binary.BigEndian.Uint32(moved[45:49]) != 48 || + binary.BigEndian.Uint32(closed[29:33]) != 110 { + t.Fatalf("incorrect native reclaim round trip: %x %x %x %x", acknowledged, contents, moved, closed) + } + if !reflect.DeepEqual(restarted.characters[1].inventory.Items, []ownedItem{{17, 51005, 42640, 1, 64}}) || len(restarted.characters[1].inventory.Reclaim) != 0 { + t.Fatal("native pickup did not persist its sole owner") + } +} + +func TestReclaimLoadRejectsDuplicateAndInvalidIdentities(t *testing.T) { + for _, scenario := range []string{"owned duplicate", "reclaim duplicate", "above watermark", "equipment slot"} { + t.Run(scenario, func(t *testing.T) { + world, _ := newReclaimWorld(t) + player := world.characters[1] + player.inventory.LastID = 4 + player.inventory.Reclaim = []reclaimItem{{ownedItem{4, 51005, 42640, 1, 65}, time.Now().UTC()}} + switch scenario { + case "owned duplicate": + player.inventory.Reclaim[0].Item.ID = 3 + case "reclaim duplicate": + player.inventory.Reclaim = append(player.inventory.Reclaim, player.inventory.Reclaim[0]) + case "above watermark": + player.inventory.Reclaim[0].Item.ID = 5 + case "equipment slot": + player.inventory.Reclaim[0].Item.Slot = 6 + } + if err := world.saveInventory_locked(player, player.inventory); err != nil { + t.Fatal(err) + } + + reloaded := &server{characters: make(map[uint32]*character)} + err := reloaded.loadUsers() + + if err == nil { + t.Fatal("invalid reclaim ownership loaded successfully") + } + }) + } +} diff --git a/server/state.go b/server/state.go @@ -60,6 +60,7 @@ type worldClient struct { dialogue *npcDialogue equipment *equipmentMove lootCorpse uint32 + reclaimItems []uint32 useSequence uint32 }